id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
8106318 | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RDeoptimr(RPackage):
"""Differential Evolution Optimization in Pure R.
Differential E... | StarcoderdataPython |
8023415 | import claripy
import logging
l = logging.getLogger('fidget.techniques')
class FidgetTechnique(object):
project = None
def constrain_variables(self, func, solver, stack):
raise NotImplementedError()
def set_project(self, project):
self.project = project
class FidgetDefaultTechnique(Fidge... | StarcoderdataPython |
6546560 | from p1.foo import foo
| StarcoderdataPython |
11261475 | <filename>test/1.2.0/doi-identifiers/_I/test_1_2_0_doi_identifiers__I_endnote_object.py<gh_stars>10-100
import os
import pytest
from test.contracts.endnote_object import Contract
from cffconvert.behavior_1_2_x.endnote_object import EndnoteObject
from cffconvert import Citation
@pytest.fixture(scope="module")
def endn... | StarcoderdataPython |
8016661 | from bs4 import BeautifulSoup
from urllib.request import urlopen
import pprint,webbrowser
gaana_com_url=urlopen('https://gaana.com/')
soup=BeautifulSoup(gaana_com_url,'html.parser')
h2_link=soup.find('h2',{'id':'themechange','class':'themechange'}).find('a').get('href')
top_charts=('https://gaana.com'+h2_link)
link=url... | StarcoderdataPython |
6462007 | # Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the S... | StarcoderdataPython |
9749856 | from cart.models import CartItem
from catalog.models import Product
from BuyIT_Lite import settings
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.db.models import Max
from datetime import datetime, timedelta
import decimal
import random
CART_ID_SE... | StarcoderdataPython |
6667146 | from datetime import datetime
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Pressao
class PressaoList... | StarcoderdataPython |
5066489 | from rest_framework import permissions
from rest_framework.exceptions import PermissionDenied
ERROR_MESSAGES = {
'update_denied': 'Изменение чужого контента запрещено!',
'delete_denied': 'Удаление чужого контента запрещено!'
}
class AuthorOrReadOnly(permissions.IsAuthenticatedOrReadOnly):
def has_object_... | StarcoderdataPython |
379558 | import uctypes as ct
SERCOM_I2CM = {
'CTRLA' : ( 0x00, {
'reg' : 0x00 | ct.UINT32,
'SWRST' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 1 << ct.BF_LEN,
'ENABLE' : 0x00 | ct.BFUINT32 | 1 << ct.BF_POS | 1 << ct.BF_LEN,
'MODE' : 0x00 | ct.BFUINT32 | 2 << ct.BF_POS | 3 << ct.BF_LEN,
'RUNSTDB... | StarcoderdataPython |
168091 | <gh_stars>0
import logging
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional
from thenewboston_node.business_logic.validators import (
validate_gte_value, validate_is_none, validate_not_none, validate_type
)
from thenewboston_node.core.logging import validates
from ... | StarcoderdataPython |
4844537 | import sys
import numpy as np
from bitstring import BitArray
from util.log import *
def flipFloat(val, bit=None, log=False):
# Cast float to BitArray and flip (invert) random bit 0-31
faultValue = BitArray(float=val, length=32)
if bit == None:
bit = np.random.randint(0, faultValue.len)
fault... | StarcoderdataPython |
5184516 | from flask import Flask, render_template, request, redirect
import os
from core.dbdriver import get_db, init_tables
app = Flask(__name__)
# Init tables in db
init_tables()
@app.route('/')
def index():
""" Index page
Show list of `asks`, and cheer count of each ask
"""
with get_db().cursor() as cursor :
cur... | StarcoderdataPython |
4887419 | from collections import defaultdict
from datetime import timedelta
from typing import Dict, List
from celery import shared_task
from django.db import connection, transaction
from django.db.models import QuerySet
from django.utils import timezone
from django.utils.timezone import now
from sentry_sdk import capture_exce... | StarcoderdataPython |
208258 | #!/usr/bin/env python
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
Non-signalized junctions: crossing negotiation:
The hero vehicle is passing through a junction without traffic lights
And encounters another vehicle passing across the junc... | StarcoderdataPython |
11264146 | <reponame>karimbahgat/GeoStream
import pygeoj
class GeoJSON(object):
def __init__(self, filepath, **kwargs):
self.filepath = filepath
self.kwargs = kwargs
self.reader = self.load_reader()
self.fieldnames, self.fieldtypes = self.load_fields()
self.meta = self.load_meta()
... | StarcoderdataPython |
6514550 | # <NAME>
# https://github.com/danieljoserodriguez
import numpy as np
# Cross-entropy loss, or log loss, measures the performance of a classification model whose output is a
# probability value between 0 and 1
def cross_entropy(y_hat, y):
return -np.log(y_hat) if y == 1 else -np.log(1 - y_hat)
# Used for clas... | StarcoderdataPython |
315783 | <reponame>musslick/sweetpea-py
import operator as op
import pytest
from itertools import permutations
from sweetpea import factor, derived_level, else_level, within_trial, at_most_k_in_a_row, transition
from sweetpea import fully_cross_block, synthesize_trials_non_uniform
congruency = factor("congruency"... | StarcoderdataPython |
11376382 | """
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License ... | StarcoderdataPython |
9687257 | import jsonschema
import json
with open("schema.json") as schema_file:
schema = json.load(schema_file)
def validate(manifest):
""" Validate a given manifest
"""
if type(manifest) is dict:
jsonschema.validate(manifest, schema)
elif type(manifest) is str:
decoded = json.loads(manif... | StarcoderdataPython |
271687 | <reponame>lumisota/ietfdata<gh_stars>1-10
# Copyright (C) 2020 University of Glasgow
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# t... | StarcoderdataPython |
4854180 | <gh_stars>1-10
from collections import defaultdict
import logging
from typing import Dict, List, Optional, Set, Tuple, Union
import torch
from torch.autograd import Variable
from allennlp.nn import util
from allennlp.nn.decoding.decoder_step import DecoderStep
from allennlp.nn.decoding.decoder_state import DecoderSta... | StarcoderdataPython |
3559885 | # -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... | StarcoderdataPython |
1863691 | #CASE14 Power flow data for IEEE 14 bus test case.
# Please see CASEFORMAT for details on the case file format.
# This data was converted from IEEE Common Data Format
# (ieee14cdf.txt) on 15-Oct-2014 by cdf2matp, rev. 2393
# See end of file for warnings generated during conversion.
#
# Converted from IEEE ... | StarcoderdataPython |
3209418 | <filename>docs/source/gallery/examples/stemplot.py
"""
Spectra : stemplot
====================
Once you have a table, one way to visualise how the ion peaks are distributed is to use
:func:`~interferences.plot.spectra.stemplot`, which you can also access from your
dataframe using the :class:`~interferences.mz` a... | StarcoderdataPython |
3453955 | ''' Input Output of TSP related objects '''
from .population import (
City,
Route,
)
def read_cities(fp):
'''reads in the starter cities from a saved file'''
cities = []
with open(fp, 'r') as f:
f.readline()
for line in f:
xy = line.split('\t')
x = ... | StarcoderdataPython |
4938730 | <reponame>biobdeveloper/p52
class SameCardsInOneDeckError(Exception):
pass
| StarcoderdataPython |
3518351 | <filename>train_net.py
"""
Yolo Training script
This script is a simplified version of the script in detectron2/tools
"""
from pathlib import Path
import torch
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.engine import (
DefaultTrainer,
default_argument_parser,
default_setup,
... | StarcoderdataPython |
3526808 | <filename>core/urls.py
from django.urls import path
from .views import client_view
app_name = "core"
urlpatterns = [
path("", view=client_view, name="client-app"),
] | StarcoderdataPython |
11323424 | <gh_stars>10-100
from aser.database.db_API import KG_Connection
import time
from tqdm import tqdm
# import aser
import ujson as json
from multiprocessing import Pool
import spacy
import random
import pandas
import numpy as np
from itertools import combinations
from scipy import spatial
import os
def get_ConceptNet_inf... | StarcoderdataPython |
239462 | # -*- encoding: utf-8 -*-
'''
@project : LeetCode
@File : getLeastNumbers.py
@Contact : <EMAIL>
@Desc :
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
示例 1:
输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]
示例 2:
输入:a... | StarcoderdataPython |
6477992 | from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score , confusion_matrix
from sklearn.preprocessing import MinMaxScaler ,Normalizer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X = data.data
y ... | StarcoderdataPython |
8071474 | <reponame>mattsayar-splunk/phantom-apps
# File: mfservicemanager_connector.py
# Copyright (c) 2020 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
import phantom.app as phantom
from phantom.base_connector import BaseConnector
from phantom.action_result import ActionResult
i... | StarcoderdataPython |
311580 | from Enemy.enemy import *
from Enemy.enemy1 import *
from Enemy.boss1 import *
from Enemy.boss2 import *
from Enemy.boss3 import *
class Stage():
def __init__(self):
self.deployEnemy()
def deployEnemy(self):
for i in range(0, 1):
x = 100 + int(i % 10) * 40
y ... | StarcoderdataPython |
9716904 | """
Client for interacting with the Neuromorphic Computing Platform of the Human Brain Project
as an administrator.
Authors: <NAME>, <NAME>, UNIC, CNRS
Copyright 2016 <NAME> and <NAME>, Centre National de la Recherche Scientifique
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this ... | StarcoderdataPython |
30566 | <gh_stars>1000+
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from fclib.models.dilated_cnn import create_dcnn_model
def test_create_dcnn_model():
mod0 = create_dcnn_model(seq_len=1) # default args
assert mod0 is not None
mod1 = create_dcnn_model(
seq_len=1, n_dyn_fea... | StarcoderdataPython |
6502904 | from __future__ import annotations
# Standard library
from pathlib import Path
# Third-party
import yaml
__all__ = ['load_yaml_config']
def load_yaml_config(file_path: str | Path) -> dict:
"""
Parameters
----------
file_path : str or Path
Yaml config file name. The file is assumed to be i... | StarcoderdataPython |
6674308 | from pyVDMC import *
@vdm_module('n1', 'n2')
class fibonacci:
"""
state State of
n1 : nat
n2 : nat
init s == s = mk_State(0, 1)
end
operations
next : () ==> nat
next() == (dcl n : nat := n1 + n2; n1 := n2; n2 := n; return n)
post RESULT = n1~ + n2~ and n... | StarcoderdataPython |
9680173 | <gh_stars>0
from bisect import bisect
from typing import List, Callable, Dict
class OneTimeCancelFunction:
"""
A one time cancellation function
"""
def __init__(self, cancel: Callable):
self.cancelled: bool = False
self.__cancel = cancel
def run_cancel(self):
if self.cance... | StarcoderdataPython |
8048648 | import threading
from pathlib import Path
#pylint: disable=no-name-in-module
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import (QWidget, QToolButton, QLineEdit, QPushButton,
QFrame, QLabel, QApplication, QMessageBox)
import src.images
from utils.logger import logger
from utils.v... | StarcoderdataPython |
11365264 | import random
import numpy as np
import cv2
import torch
import torch.utils.data as data
import data.util as util
import os.path as osp
class LQGT_dataset(data.Dataset):
def __init__(self, opt):
super(LQGT_dataset, self).__init__()
self.opt = opt
self.data_type = self.opt['data_type']
... | StarcoderdataPython |
352195 | <reponame>myles-novick/ml-workflow<gh_stars>0
"""
This module has a Master, which polls Splice Machine
for new jobs and dispatches them to Workers for execution
(in threads). This execution happens in parallel.
"""
import json
from os import environ as env_vars
from fastapi import FastAPI
from handlers.modifier_handle... | StarcoderdataPython |
6675603 | <reponame>junhoyeo/fastdj
from django.urls import path
from comment import views
urlpatterns = [
path('get_comments_view/', views.get_comments_view, name='get_comments_view'),
path('', views.create_comment_view.as_view(), name='create_comment_view'),
] | StarcoderdataPython |
318038 | <reponame>PacktPublishing/Raspberry-Pi-Cookbook-for-Python-Programmers-SecondEdition
#import the necessary packages
import cv2
import numpy as np
BLUR=(5,5)
HIBLUR=(30,30)
GAUSSIAN=(21,21)
imageBG=None
gray=True
movement=[]
AVG=2
avgX=0
avgY=0
count=0
def process_image(raw_image,control):
global imageBG
global ... | StarcoderdataPython |
206596 | <gh_stars>0
import numpy
from audionmf.transforms.nmf import NMF
def nmf_matrix(matrix, max_iter=100, rank=30):
# increment the matrix to make sure it's positive
matrix_inc, min_val = increment_by_min(matrix)
# TODO save
# use Kullback-Leibler divergence
# nmf = nimfa.Nmf(matrix_inc, max_iter=ma... | StarcoderdataPython |
113425 | <reponame>garrethmartin/HSC_UML
import sys
import numpy
import config as cf
import log
import os
import inspect
import pandas as pd
import h5py
from time import gmtime, strftime
from helpers import boundingbox
from helpers import fitshelper
from astropy.stats import sigma_clipped_stats
from helpers.image_types import S... | StarcoderdataPython |
215193 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import logging
import threading
from natrixclient.common.config import NatrixConfig
from natrixclient.command.performance.webdriver import Firefox
from natrixclient.command.performance.webdriver import Chrome
from natrixclient.command.performance.webdriver impo... | StarcoderdataPython |
3353303 | <reponame>yxcxx/upass<gh_stars>0
__author__ = 'yxc'
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
from tornado.options import define, options
from url import HANDLER
from setting import setting
define("port", default=8000, help="app run in this port")
class Application(... | StarcoderdataPython |
1928945 | from tqdm import tqdm
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from torch.utils import data
import math
from .dataset import Dataset
def get_dataloaders(task, text_encoder, test_split, validation_split, batch_size, device, verbose, sequence_dim=None):
train_file = task[... | StarcoderdataPython |
3328979 |
def main(request, response):
def fmt(x):
return f'"{x.decode("utf-8")}"' if x is not None else "undefined"
purpose = request.headers.get("Purpose", b"").decode("utf-8")
sec_purpose = request.headers.get("Sec-Purpose", b"").decode("utf-8")
headers = [(b"Content-Type", b"text/html"), (b'WWW-Authenticate', ... | StarcoderdataPython |
11398312 | <filename>src/coop_assembly/help_functions/shared_const.py
# small number epsilon
EPS = 1e-8
# large number infinite
INF = 1e23
# TOL
TOL = 0.1
# vertex correction, deciding how low a new vertex can go for a three-bar group
NODE_CORRECTION_TOP_DISTANCE = 80 # millimter
NODE_CORRECTION_SINE_ANGLE = 0.4
| StarcoderdataPython |
8039331 | <gh_stars>0
__all__ = ['load', 'save', 'manhattan_distance', 'split_work', 'DEFAULT_TYPE']
import pickle
from pathlib import Path
from typing import Union
from typing import Any
from typing import List
from typing import Generator
import numpy as np
DEFAULT_TYPE = np.float32
def split_work(work: List[Any], num_ba... | StarcoderdataPython |
3212346 | <reponame>gradecam/keras_to_deeplearnjs
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input", help="keras model to convert in keras's h5py format")
parser.add_argument("output", help="output filename of javascript module")
parser.add_argument("--weights", help="output filename of weight file, ... | StarcoderdataPython |
397156 | #!/usr/bin/env python
import os
try:
marsyas_datadir = os.environ['MARSYAS_DATADIR']
except:
marsyas_datadir = "."
class MarCollection():
def __init__(self, mf_filename=None):
self.data = []
if mf_filename is not None:
try:
self.read_mf(mf_filename)
... | StarcoderdataPython |
3308686 | <filename>ttBotDemo/BotDemo.py
# -*- coding: UTF-8 -*-
import logging
import os
from TamTamBot.TamTamBot import TamTamBot
from TamTamBot.utils.lng import set_use_django
class BotDemo(TamTamBot):
@property
def description(self):
# type: () -> str
return 'Простейший бот на python. Исходный код... | StarcoderdataPython |
3462120 | # coding=utf-8
import mysql.connector.pooling
import random
class DbHandler(object):
def __init__(self, **db_config):
self.db_config = db_config
self.pool_size = self.db_config.get('pool_size', 1)
self.mysql_pool = mysql.connector.pooling.MySQLConnectionPool(
pool_name=self.db... | StarcoderdataPython |
6442441 | from flask import Flask, request, jsonify
from flask_basicauth import BasicAuth
from textblob import TextBlob
from sklearn.linear_model import LinearRegression
import pickle
import os
from googletrans import Translator
translator = Translator()
colunas = ['tamanho','ano','garagem']
modelo = pickle.load(open('../../mo... | StarcoderdataPython |
9697316 | <gh_stars>100-1000
#encoding:utf-8
subreddit = 'theydidthemath'
t_channel = '@TheyDidTheMath'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| StarcoderdataPython |
9699607 | from sympy import ratsimpmodprime, ratsimp, Rational, sqrt, pi, log, erf, GF
from sympy.abc import x, y, z, t, a, b, c, d, e
def test_ratsimp():
f, g = 1 / x + 1 / y, (x + y) / (x * y)
assert f != g and ratsimp(f) == g
f, g = 1 / (1 + 1 / x), 1 - 1 / (x + 1)
assert f != g and ratsimp(f) == g
... | StarcoderdataPython |
4928295 | <filename>edgeql_queries/queries.py
"""Definition for main collection for queries."""
from __future__ import annotations
from typing import Callable, Dict, List, Set, Union
from edgeql_queries.executors.async_executor import create_async_executor
from edgeql_queries.executors.sync_executor import create_sync_executo... | StarcoderdataPython |
3285587 | #!/usr/bin/python2.7
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | StarcoderdataPython |
11235097 | <reponame>croxis/SpaceDrive<filename>spacedrive/render_components.py
from panda3d.core import PerlinNoise2
class CelestialRenderComponent(object):
body = None
atmosphere = None
light = None
noise = PerlinNoise2(64, 64)
noise_texture = None
mesh = None
temperature = 0
| StarcoderdataPython |
4862496 | <filename>tests/operators/ci_gpu/test_all.py<gh_stars>0
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
... | StarcoderdataPython |
4890735 | <reponame>ilay09/neutron
# Copyright 2016 Hewlett Packard Enterprise Development Company, LP
# Copyright 2016 Red Hat Inc.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the Licens... | StarcoderdataPython |
4986145 | '''Test module docstring'''
import json
import pprint
def test_uno():
'''Test function uno docstring'''
json_str = '''{
"info": {
"author": "The Python Packaging Authority",
"author_email": "<EMAIL>",
"home_page": "https://github.com/pypa/sampleproject",
... | StarcoderdataPython |
3262845 | <filename>tor_starter.py<gh_stars>0
import os
import re
os.system("sudo /etc/init.d/tor restart")
os.system("sudo killall tor")
os.system("sudo killall tor")
f=open("/home/kc/.mozilla/firefox/profiles.ini","r")
file = f.read()
profile_list=re.findall(r'Path=[\w.]+',file)
profile = profile_list[0][5:]
f.close()
profi... | StarcoderdataPython |
9625586 | from setuptools import find_packages, setup
setup(
name="SchedSlackBot",
version='1.0.0',
author="<NAME> <<EMAIL>>",
description="Setup and manage Rotating Schedules in Slack",
packages=find_packages(include=["sched_slack_bot"]),
)
| StarcoderdataPython |
9673332 | <filename>test/test_download_models_class1.py
import logging
logging.getLogger('tensorflow').disabled = True
logging.getLogger('matplotlib').disabled = True
import numpy
numpy.random.seed(0)
import pickle
import tempfile
from numpy.testing import assert_equal
from mhcflurry import Class1AffinityPredictor, Class1Ne... | StarcoderdataPython |
265212 | import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Run3_cff import Run3
process = cms.Process('DUMP',Run3)
process.source = cms.Source('EmptySource')
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
)
process.load('Configuration.Geometry.GeometryExtended2021_cff')
pro... | StarcoderdataPython |
374709 | # -*- coding: utf-8 -*-
"""
wow_addon_manager.app
~~~~~~~~~~~~~~~~~~~~~
The main application.
:author: qwezarty
:date: 04:03 pm Nov 14 2017
:email: <EMAIL>
"""
import sys
from .config import Config
from .request import Request
import zipfile
from wow_addon_manager import helpers
from os impo... | StarcoderdataPython |
3322980 | <filename>generate-list-of-projects.py
#!/usr/bin/env python3
from collections import defaultdict
import csv
from datetime import datetime
from glob import glob
import os.path
import re
from urllib.request import urlopen
from jinja2 import Environment
from jinja2 import FileSystemLoader
import yaml
#
# Variables
#
... | StarcoderdataPython |
1708994 | <filename>youtube_podcast_gateway/config.py
class Key:
def __init__(self, name, type, default_value=None):
self.name = name
self.type = type
self.default_value = default_value
class Configuration:
def __init__(self, values: dict):
self._values = values
def get(self, key: K... | StarcoderdataPython |
4898032 | <reponame>nick66551/VectorSpace
from __future__ import division, unicode_literals
import math
from textblob import TextBlob as tb
def tf(word, blob):
return blob.count(word) / len(blob)
def n_containing(word, bloblist):
return sum(1 for blob in bloblist if word in blob)
def idf(word, bloblist):
return ma... | StarcoderdataPython |
36584 | from jobbergate import appform
def mainflow(data):
return [appform.Const("val", default=10)]
| StarcoderdataPython |
5077819 | """ Klei rowid communication
Methods:
* getRegionalLobbies(ip_list) : list
* getServerInfoStea(ip, steam_port) : dictionary
By: github.com/iamflea
Licence: who cares July 2019
"""
import http.client
import json
from config import *
import zlib
import re
import os.path as op # For checking when th... | StarcoderdataPython |
3210338 | <filename>pyusermanager/user_funcs.py
from email.utils import parseaddr
from pony.orm import *
import bcrypt
from . import custom_exceptions as PyUserExceptions
from .auth_type_enum import AUTH_TYPE
class user:
"""
A Class to manage Users in the Database
"""
def __str__(self):
if len(self.__d... | StarcoderdataPython |
3225656 | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2015 Metaswitch Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | StarcoderdataPython |
6617670 | from .sections import read_sections, read_dat_header, append_section
import struct
from collections import namedtuple
from ...text import decode_text, encode_text
import csv
ItemCategory = namedtuple('ItemCategory', ['name', 'recordSize'])
_ITEM_CATEGORIES = [
ItemCategory('Use', 0x4C),
ItemCategory('Weapon',... | StarcoderdataPython |
364094 | def minimum2(L):
min_1 = L[0]
min_2 = L[1]
if min_1 < min_2:
min_1, min_2 = min_2, min_1
i = 0
while i < len(L):
if L[i] < min_1:
min_2, min_1 = min_1, L[i]
elif L[i] < min_2 and L[i] > min_1:
min_2 = L[i]
i += 1
return min_2
print(minimum2([3,2,5,7,2]))
| StarcoderdataPython |
4866034 | <filename>venv/lib/python3.6/site-packages/ansible_collections/ansible/utils/plugins/test/in_one_network.py
# -*- coding: utf-8 -*-
# Copyright 2021 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
Test plugin file for netaddr tests: in_one_network
"""
from __... | StarcoderdataPython |
11398140 | <reponame>kyouko-taiga/tango
import unittest
from tango.builtin import Bool, Double, Int, Nothing, String, Type
from tango.errors import InferenceError
from tango.parser import parse
from tango.scope_binder import bind_scopes
from tango.type_builder import build_types
from tango.type_solver import TypeVariable, infer_... | StarcoderdataPython |
4856473 | <reponame>cluco91/Django_Farmacia
from unipath import Path
import os
BASE_DIR = Path(__file__).ancestor(3)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
SECRET_KEY = '<KEY>'
DJANGO_APPS = (
'suit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django... | StarcoderdataPython |
1865702 | from pytest import approx
import torch
from torch_geometric.transforms import RandomRotate
from torch_geometric.data import Data
def test_spherical():
assert RandomRotate(-180).__repr__() == 'RandomRotate((-180, 180))'
pos = torch.tensor([[1, 0], [0, 1]], dtype=torch.float)
data = Data(pos=pos)
out ... | StarcoderdataPython |
12818818 | # django imports
from django.db import models
from django.db.models.query import QuerySet
from django.conf import settings
from django.core.cache import cache
from django.http import Http404
from django.shortcuts import _get_queryset
def key_from_instance(instance):
opts = instance._meta
return '%s.%s:%s' % (... | StarcoderdataPython |
6459389 | import argparse
from datetime import datetime
from random import normalvariate, choice
import struct
import sys
import time
import traceback
from uuid import UUID
import pigpio
from nrf24 import *
#
# A simple NRF24L client that connects to a PIGPIO instance on a hostname and port, default "localhost" and 8888, and
#... | StarcoderdataPython |
1785677 | <filename>networking_cisco/plugins/cisco/db/device_manager/hosting_devices_db.py
# Copyright 2014 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the Licen... | StarcoderdataPython |
8192467 | <filename>myfaker/code/constants.py
# define all the constants used in this project
MAX_SAMPLE_SIZE = 1000
REPEAT_SAMPLE = True
| StarcoderdataPython |
335766 | #!/usr/bin/env python
import sys
import subprocess
import json
description = """
generate a json that contains UUID and path-to-data of the data set for all data sets.
print the json to stdout
"""
def get_irods_path_list(base_dir):
path_list = []
# list files inside base_dir
ls_output = subprocess.check_... | StarcoderdataPython |
12829443 | # -*- coding: utf-8 -*-
from .fields import ImportPathField
__all__ = ['ImportPathField']
| StarcoderdataPython |
3520173 | """
C/C++ integration
=================
NOTE: this module is deprecated and will be removed from Scipy before
the 1.0 release -- use the standalone weave package
(`https://github.com/scipy/weave`_) instead.
inline -- a function for including C/C++ code within Python
blitz -- a function for co... | StarcoderdataPython |
6676469 | from propsettings.setting import Setting
from propsettings_qt.input_handlers.input_handler import SettingDrawer
class ObjectHandler(SettingDrawer):
"""
InputHandler que se encarga de las configuraciones que sean de tipo object.
Estas solo se podrán modificar si tienen miembros de tipo Setting o si son de algún tip... | StarcoderdataPython |
3406154 | import re
def mem_to_bytes(mem):
if isinstance(mem, (float, int)):
return mem
m = re.match(r"^((?:0|[1-9]\d*)(?:\.\d+)?)\s*([A-Za-z]+)?$", mem)
if m is None:
raise Exception("Invalid memory format: {}".format(mem))
val = float(m.group(1))
unit = m.group(2)
if unit is None:
... | StarcoderdataPython |
333681 | <gh_stars>0
#!/usr/local/bin/python3
# MIT License
# Copyright (c) 2021 HLSAnalyzer.com
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#... | StarcoderdataPython |
11382822 | #Escreva um programa que faça o computador “pensar” em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.
#O programa deverá escrever na tela se o usuário venceu ou perdeu.
from numpy.random.mtrand import randint
chute = int(input("chuta um numero mlk de 1... | StarcoderdataPython |
8076357 | <reponame>harry-7/mycodes<gh_stars>1-10
"""
Author: <NAME>
Handle:harry7
"""
#!/usr/bin/python
n=input()
s=raw_input()
p=0
k=1
for i in xrange(n):
p=p+k*int(s[i])
k*=2
p+=1
f=""
for i in xrange(n):
f+=str(p%2)
p/=2
cnt=0
for i in xrange(n):
if(s[i]!=f[i]):cnt+=1
print cnt
| StarcoderdataPython |
9790578 | <filename>ark/opal/driver/execute_driver/bdcloud_execute_driver.py
# -*- coding: UTF-8 -*-
################################################################################
#
# Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
"... | StarcoderdataPython |
11260787 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'SupplementalFile'
db.create_table('collection_record_supplementalfile', (
('id... | StarcoderdataPython |
11203319 | # Copyright (c) 2021, <NAME> and/or its affiliates. All rights reserved.
#
# This software is licensed under the Apache License, Version 2.0 (the
# "License") as published by the Apache Software Foundation.
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at ht... | StarcoderdataPython |
1699769 | import cv2
import numpy as np
#Sketch generation function:
def sketch(image):
#Convert image to greyscale
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#Clean up image using Gaussian Blur
img_gray_blur = cv2.GaussianBlur(img_gray, (5,5), 0)
#Extract edges
canny_edges = cv2.Canny(img_gray... | StarcoderdataPython |
6670736 | <gh_stars>1-10
from . import RENAMES
from ..common.fix_strings import BaseFixStrings
class FixStrings(BaseFixStrings):
renames = RENAMES
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.