code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import numpy as np
import scipy.io.wavfile as wf
import matplotlib.pyplot as plt
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox as mb
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
Style().theme_use('default')
self.master = ma... | homework_1/main.py | import numpy as np
import scipy.io.wavfile as wf
import matplotlib.pyplot as plt
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox as mb
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
Style().theme_use('default')
self.master = ma... | 0.464173 | 0.181662 |
from __future__ import print_function, division
import unittest
import numpy
import matplotlib.pyplot as plt
import os
from maxr import flow
from maxr.flow.blink import blink, tick, tock
class TestBlink(unittest.TestCase):
""" Tests for Blink functions
"""
def setUp(self):
self.times = num... | tests/test_flow.py | from __future__ import print_function, division
import unittest
import numpy
import matplotlib.pyplot as plt
import os
from maxr import flow
from maxr.flow.blink import blink, tick, tock
class TestBlink(unittest.TestCase):
""" Tests for Blink functions
"""
def setUp(self):
self.times = num... | 0.644896 | 0.532668 |
import csv
from urllib.request import Request, urlopen
import urllib.error
import re
from sys import argv
from bs4 import BeautifulSoup
from dateutil import parser
import scrape_util
default_sale, base_url, prefix = scrape_util.get_market(argv)
base_url = base_url[:-1]
strip_char = ';,. \n\t$'
def get_sale_head(lin... | _30_scrape.py | import csv
from urllib.request import Request, urlopen
import urllib.error
import re
from sys import argv
from bs4 import BeautifulSoup
from dateutil import parser
import scrape_util
default_sale, base_url, prefix = scrape_util.get_market(argv)
base_url = base_url[:-1]
strip_char = ';,. \n\t$'
def get_sale_head(lin... | 0.203233 | 0.12711 |
from itertools import product, permutations, count
from warnings import catch_warnings, simplefilter as issue_warnings
import quick2wire.parts.mcp23x17 as mcp23x17
from quick2wire.parts.mcp23x17 import *
from quick2wire.parts.mcp23x17 import _banked_register
from factcheck import *
bits = from_range(2)
bank_ids = from... | hmc5883lStream/code/quick2wire/parts/test_mcp23x17.py | from itertools import product, permutations, count
from warnings import catch_warnings, simplefilter as issue_warnings
import quick2wire.parts.mcp23x17 as mcp23x17
from quick2wire.parts.mcp23x17 import *
from quick2wire.parts.mcp23x17 import _banked_register
from factcheck import *
bits = from_range(2)
bank_ids = from... | 0.504883 | 0.5752 |
import pyautogui
import requests
import time
from PIL import ImageGrab
import sys
import keyboard
def check_internet():
url = 'https://www.google.com'
timeout = 5
try:
requests.get(url, timeout=timeout)
return True
except requests.exceptions.ConnectionError:
return False
whil... | DinoWeb.py | import pyautogui
import requests
import time
from PIL import ImageGrab
import sys
import keyboard
def check_internet():
url = 'https://www.google.com'
timeout = 5
try:
requests.get(url, timeout=timeout)
return True
except requests.exceptions.ConnectionError:
return False
whil... | 0.092158 | 0.151059 |
import numpy as np
np.set_printoptions(suppress=True, formatter={'all':lambda x: str(x) + ','}, linewidth=9999)
import matplotlib.pyplot as plt
import glob, time
import sys
import os
import math
import operator
from helper import *
from scipy.stats import ttest_ind, ttest_rel
from sklearn import svm
from sklearn.linear... | classify.py | import numpy as np
np.set_printoptions(suppress=True, formatter={'all':lambda x: str(x) + ','}, linewidth=9999)
import matplotlib.pyplot as plt
import glob, time
import sys
import os
import math
import operator
from helper import *
from scipy.stats import ttest_ind, ttest_rel
from sklearn import svm
from sklearn.linear... | 0.248079 | 0.456531 |
import cv2
from PIL import Image
import argparse
from pathlib import Path
from multiprocessing import Process, Pipe, Value, Array
import torch
from config import get_config
from mtcnn import MTCNN
from Learner import face_learner
from utils import load_facebank, draw_box_name, prepare_facebank
import numpy
if __name__... | test_image.py | import cv2
from PIL import Image
import argparse
from pathlib import Path
from multiprocessing import Process, Pipe, Value, Array
import torch
from config import get_config
from mtcnn import MTCNN
from Learner import face_learner
from utils import load_facebank, draw_box_name, prepare_facebank
import numpy
if __name__... | 0.391173 | 0.1126 |
from enum import IntEnum
import mindspore._c_dataengine as cde
import numpy as np
from .validators import check_from_file, check_from_list, check_from_dict
class Vocab(cde.Vocab):
"""
Vocab object that is used for lookup word
Args:
"""
def __init__(self):
pass
@classmethod
... | mindspore/dataset/text/utils.py | from enum import IntEnum
import mindspore._c_dataengine as cde
import numpy as np
from .validators import check_from_file, check_from_list, check_from_dict
class Vocab(cde.Vocab):
"""
Vocab object that is used for lookup word
Args:
"""
def __init__(self):
pass
@classmethod
... | 0.911891 | 0.361503 |
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com <EMAIL>
from thumbor.config import Config
from thumbor.context import Context, RequestParameters
from thumbor.optimizers.jpegtran impor... | source/thumbor-6.4.2/tests/optimizers/test_jpegtran.py |
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com <EMAIL>
from thumbor.config import Config
from thumbor.context import Context, RequestParameters
from thumbor.optimizers.jpegtran impor... | 0.850344 | 0.362292 |
import os
from pathlib import Path
from unittest import TestCase
from pydbml import PyDBML
from pydbml.exceptions import ColumnNotFoundError
from pydbml.exceptions import TableNotFoundError
TEST_DOCS_PATH = Path(os.path.abspath(__file__)).parent / 'test_data/docs'
class TestDocs(TestCase):
def test_example(se... | test/test_docs.py | import os
from pathlib import Path
from unittest import TestCase
from pydbml import PyDBML
from pydbml.exceptions import ColumnNotFoundError
from pydbml.exceptions import TableNotFoundError
TEST_DOCS_PATH = Path(os.path.abspath(__file__)).parent / 'test_data/docs'
class TestDocs(TestCase):
def test_example(se... | 0.57069 | 0.494751 |
"""Unit test for the stationdata module"""
import datetime
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.stationdata import build_station_list, update_water_levels
def test_build_station_list():
# Build list of stations
stations = build_station_list()
# Find station 'Cam'
... | test_datafetcher.py | """Unit test for the stationdata module"""
import datetime
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.stationdata import build_station_list, update_water_levels
def test_build_station_list():
# Build list of stations
stations = build_station_list()
# Find station 'Cam'
... | 0.408277 | 0.524577 |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, RadioField, EmailField, SubmitField, BooleanField, DateField
from wtforms.validators import InputRequired, EqualTo, Email, ValidationError, Optional
from app_folder.blueprints.users.model import User
from flask_login import current_user
d... | app_folder/blueprints/auth/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, RadioField, EmailField, SubmitField, BooleanField, DateField
from wtforms.validators import InputRequired, EqualTo, Email, ValidationError, Optional
from app_folder.blueprints.users.model import User
from flask_login import current_user
d... | 0.628749 | 0.170456 |
from unittest import TestCase
from maintain_frontend import main
from unit_tests.utilities import Utilities
from unittest.mock import patch, MagicMock
from flask import g
from maintain_frontend.dependencies.search_api.local_land_charge_service import LocalLandChargeService
BASE64_BOUNDING_BOX = "<KEY>"
class TestLoc... | unit_tests/dependencies/search_api/test_local_land_charge_service.py | from unittest import TestCase
from maintain_frontend import main
from unit_tests.utilities import Utilities
from unittest.mock import patch, MagicMock
from flask import g
from maintain_frontend.dependencies.search_api.local_land_charge_service import LocalLandChargeService
BASE64_BOUNDING_BOX = "<KEY>"
class TestLoc... | 0.756178 | 0.280524 |
import sqlite3
from cliboa.util.lisboa_log import LisboaLog
class SqliteAdapter(object):
"""
Adapter class of sqlite3
"""
def __init__(self):
self._logger = LisboaLog.get_logger(__name__)
self.__cur = None
self.__con = None
def connect(self, dbname):
"""
... | cliboa/util/sqlite.py | import sqlite3
from cliboa.util.lisboa_log import LisboaLog
class SqliteAdapter(object):
"""
Adapter class of sqlite3
"""
def __init__(self):
self._logger = LisboaLog.get_logger(__name__)
self.__cur = None
self.__con = None
def connect(self, dbname):
"""
... | 0.615781 | 0.161783 |
import os
import logging
from tornado.log import LogFormatter
from tornado.options import define, options
from modules.base.util import functions
class MavLogging(object):
def __init__(self):
self.create_logdirs()
self.setup_logging()
def create_logdirs(self):
functions.mkdirs(optio... | maverick_api/modules/base/setup/logging.py | import os
import logging
from tornado.log import LogFormatter
from tornado.options import define, options
from modules.base.util import functions
class MavLogging(object):
def __init__(self):
self.create_logdirs()
self.setup_logging()
def create_logdirs(self):
functions.mkdirs(optio... | 0.30054 | 0.06165 |
def _define_alt_model_checkpoint(parent_cls):
"""
:param parent_cls: The ModelCheckpoint class from Keras, or from the Keras bundled with Tensorflow
:return:
"""
class AltModelCheckpoint(parent_cls):
def __init__(self, filepath, alternate_model, inherit_optimizer: bool = True, **kwargs):
... | alt_model_checkpoint/__init__.py | def _define_alt_model_checkpoint(parent_cls):
"""
:param parent_cls: The ModelCheckpoint class from Keras, or from the Keras bundled with Tensorflow
:return:
"""
class AltModelCheckpoint(parent_cls):
def __init__(self, filepath, alternate_model, inherit_optimizer: bool = True, **kwargs):
... | 0.828904 | 0.41561 |
import sys
import requests
import os
import json
import re
import ffmpeg
import time
# 下载功能实现
def download(link, link_headers, save_title):
print("Downloading Video from " + link)
response = requests.get(link, headers=link_headers)
html_data = re.findall('<script>window.__playinfo__=(.*?)</script>', resp... | BDownloader.py | import sys
import requests
import os
import json
import re
import ffmpeg
import time
# 下载功能实现
def download(link, link_headers, save_title):
print("Downloading Video from " + link)
response = requests.get(link, headers=link_headers)
html_data = re.findall('<script>window.__playinfo__=(.*?)</script>', resp... | 0.041433 | 0.058615 |
import redis
import os
import telebot
import math
import random
import threading
from telebot import types
from emoji import emojize
from pymongo import MongoClient
token = os.environ['TELEGRAM_TOKEN']
bot = telebot.TeleBot(token)
admins=[713258449]
games={-1001445331185}
client1=os.environ['database']
client=MongoCl... | bot.py | import redis
import os
import telebot
import math
import random
import threading
from telebot import types
from emoji import emojize
from pymongo import MongoClient
token = os.environ['TELEGRAM_TOKEN']
bot = telebot.TeleBot(token)
admins=[713258449]
games={-1001445331185}
client1=os.environ['database']
client=MongoCl... | 0.138491 | 0.0745 |
import uqra, unittest,warnings,os, sys
from tqdm import tqdm
import numpy as np, scipy as sp
from uqra.solver.PowerSpectrum import PowerSpectrum
from uqra.environment import Kvitebjorn as Kvitebjorn
from sklearn import datasets
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFo... | tests/test_Spectrum.py |
import uqra, unittest,warnings,os, sys
from tqdm import tqdm
import numpy as np, scipy as sp
from uqra.solver.PowerSpectrum import PowerSpectrum
from uqra.environment import Kvitebjorn as Kvitebjorn
from sklearn import datasets
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFo... | 0.343562 | 0.300309 |
# Standard library imports
import collections as c
from copy import deepcopy
import json
from pathlib import Path
import warnings
# Third party imports
import numpy as np
import pandas as pd
from numba import jit, njit
import numba as nb
# Local imports
from p4.preprocessing import Preprocessor
from p4.perceptrons.re... | tests/test_regression_perceptron.py | # Standard library imports
import collections as c
from copy import deepcopy
import json
from pathlib import Path
import warnings
# Third party imports
import numpy as np
import pandas as pd
from numba import jit, njit
import numba as nb
# Local imports
from p4.preprocessing import Preprocessor
from p4.perceptrons.re... | 0.585575 | 0.403156 |
import argparse
import torch
import wandb
import torchmetrics.functional as metrics
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay
from models import GAT
from utils import load_graph
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def train(model, criterion,... | gat_experiment.py | import argparse
import torch
import wandb
import torchmetrics.functional as metrics
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay
from models import GAT
from utils import load_graph
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def train(model, criterion,... | 0.869146 | 0.511534 |
import logging
try:
import json
except ImportError:
import simplejson as json
from horizon_hpe_storage.api.common import exceptions
from horizon_hpe_storage.api.common import http
LOG = logging.getLogger(__name__)
class HTTPJSONRESTClient(http.HTTPJSONRESTClient):
"""
HTTP/REST client to access SS... | horizon_hpe_storage/api/hpSSMCclient/http.py |
import logging
try:
import json
except ImportError:
import simplejson as json
from horizon_hpe_storage.api.common import exceptions
from horizon_hpe_storage.api.common import http
LOG = logging.getLogger(__name__)
class HTTPJSONRESTClient(http.HTTPJSONRESTClient):
"""
HTTP/REST client to access SS... | 0.548432 | 0.067424 |
def sensors() :
'''
https://github.com/HackBulgaria/Programming-101-Python-2020-Spring/tree/master/Application/1.Sensors
'''
try:
file_name = input("Filename: ")
sensors_file = open(file_name, 'r')
except FileNotFoundError as e :
print(f"{e.filename} - Not Found")
re... | main.py | def sensors() :
'''
https://github.com/HackBulgaria/Programming-101-Python-2020-Spring/tree/master/Application/1.Sensors
'''
try:
file_name = input("Filename: ")
sensors_file = open(file_name, 'r')
except FileNotFoundError as e :
print(f"{e.filename} - Not Found")
re... | 0.387111 | 0.497925 |
from typing import List
import numpy as np
from pyrep.objects.proximity_sensor import ProximitySensor
from pyrep.objects.shape import Shape
from pyrep.objects.dummy import Dummy
from rlbench.backend.task import Task
from rlbench.backend.conditions import DetectedCondition, NothingGrasped
MAX_CHECKERS_TO_SETUP = 3
cl... | rlbench/tasks/setup_checkers.py | from typing import List
import numpy as np
from pyrep.objects.proximity_sensor import ProximitySensor
from pyrep.objects.shape import Shape
from pyrep.objects.dummy import Dummy
from rlbench.backend.task import Task
from rlbench.backend.conditions import DetectedCondition, NothingGrasped
MAX_CHECKERS_TO_SETUP = 3
cl... | 0.657978 | 0.3415 |
from simspark_server import SimSparkServer
import effectors as ef
# TODO(LOGGING) Figure out how to use the logging library
class BaseAgent(SimSparkServer):
model_path = "rsg/agent/nao/nao.rsg" # Defaults to Nao model
def __init__(self, teamname: str, player_number: int=0, host: str="localhost", port: int=... | py-simspark/agent.py | from simspark_server import SimSparkServer
import effectors as ef
# TODO(LOGGING) Figure out how to use the logging library
class BaseAgent(SimSparkServer):
model_path = "rsg/agent/nao/nao.rsg" # Defaults to Nao model
def __init__(self, teamname: str, player_number: int=0, host: str="localhost", port: int=... | 0.476823 | 0.42925 |
from __future__ import print_function
import base64
import json
from boto3 import resource
from datetime import datetime
from collections import defaultdict
from time import time
class KinesisEvent:
def __init__(self):
self.event_name = ''
self.page_id = ''
self.action = 'skip'
class Dyn... | _src/implementing-serverless-microservice-architecture-patterns/serverless-microservice-architecture-patterns/lambda_kinesis_visits_metrics/lambda_kinesis_visits_metrics.py | from __future__ import print_function
import base64
import json
from boto3 import resource
from datetime import datetime
from collections import defaultdict
from time import time
class KinesisEvent:
def __init__(self):
self.event_name = ''
self.page_id = ''
self.action = 'skip'
class Dyn... | 0.391871 | 0.13852 |
import tensorflow as tf
import scipy.io as scio
import pylab
import numpy as np
import os
import time
import utils.preprocess as preproc
import modules.base_modules as basic_blocks
from utils.model_utils import l1_loss
from utils.feat_utils import shuffle_feats_label
def classifier_model(input_mfc, reuse=False, sco... | obsolete_main/latent_features.py | import tensorflow as tf
import scipy.io as scio
import pylab
import numpy as np
import os
import time
import utils.preprocess as preproc
import modules.base_modules as basic_blocks
from utils.model_utils import l1_loss
from utils.feat_utils import shuffle_feats_label
def classifier_model(input_mfc, reuse=False, sco... | 0.720663 | 0.289337 |
import time
import random
import pandas as pd
from glob import glob
import pprint
import argparse
import json
import subprocess
import sys
import os
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'scikit-learn==0.23.1'])
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'sagemaker-tensorfl... | 02_usecases/sagemaker_recommendations/wip/train_basic.py | import time
import random
import pandas as pd
from glob import glob
import pprint
import argparse
import json
import subprocess
import sys
import os
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'scikit-learn==0.23.1'])
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'sagemaker-tensorfl... | 0.675765 | 0.159185 |
from ..utils import user_has_rights_on_share
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers, exceptions
from ..fields import UUIDField, BooleanField
from ..models import User, Group, User_Share_Right, Group_Share_Right, User_Group_Membership
class CreateShareRightSeri... | psono/restapi/serializers/create_share_right.py | from ..utils import user_has_rights_on_share
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers, exceptions
from ..fields import UUIDField, BooleanField
from ..models import User, Group, User_Share_Right, Group_Share_Right, User_Group_Membership
class CreateShareRightSeri... | 0.396185 | 0.064447 |
import numpy as np
from psychopy.visual import TextStim, Line, RadialStim, Circle
from psychopy import tools
class FixationLines(object):
def __init__(self, win, circle_radius, color, linewidth=1.5, *args, **kwargs):
self.color = color
self.linewidth = linewidth
self.line1 = Line(win,
... | checkerboard_event/stimuli.py | import numpy as np
from psychopy.visual import TextStim, Line, RadialStim, Circle
from psychopy import tools
class FixationLines(object):
def __init__(self, win, circle_radius, color, linewidth=1.5, *args, **kwargs):
self.color = color
self.linewidth = linewidth
self.line1 = Line(win,
... | 0.632957 | 0.198006 |
import numpy as np
import inspect
from copy import deepcopy
from .sequence import SeqIntervalDl, StringSeqIntervalDl
from .normalization import Weights
from .utils import ArgumentsDict, get_default_args
class Generator(object):
"""
info:
doc: >
Generator for keras model able to yield inp... | keras_dna/generators.py | import numpy as np
import inspect
from copy import deepcopy
from .sequence import SeqIntervalDl, StringSeqIntervalDl
from .normalization import Weights
from .utils import ArgumentsDict, get_default_args
class Generator(object):
"""
info:
doc: >
Generator for keras model able to yield inp... | 0.81257 | 0.423577 |
from locale import LC_TIME, setlocale
from logging import basicConfig, getLogger
EXPAND_FORMAT = {
'singular': {'a': 'acte', 'tabl': 'tableau'},
'plural': {'a': 'actes', 'tabl': 'tableaux'}
}
BASIC_TEMPLATE = '{title},{author_string}{genre_phrase}{music_string} a\
débuté{ce_jour_la} {date_string} {theater_st... | spectacles_xix/play.py | from locale import LC_TIME, setlocale
from logging import basicConfig, getLogger
EXPAND_FORMAT = {
'singular': {'a': 'acte', 'tabl': 'tableau'},
'plural': {'a': 'actes', 'tabl': 'tableaux'}
}
BASIC_TEMPLATE = '{title},{author_string}{genre_phrase}{music_string} a\
débuté{ce_jour_la} {date_string} {theater_st... | 0.580233 | 0.136436 |
# COMMAND ----------
# MAGIC %run /Workspaces/dars_nic_391419_j3w9t_collab/CCU013/COVID-19-SEVERITY-PHENOTYPING/CCU013_00_helper_functions
# COMMAND ----------
# Params
# Use the latest ProductionDate
production_date = spark.sql("SELECT MAX(ProductionDate) FROM dars_nic_391419_j3w9t_collab.wrang002b_data_version_ba... | code/00_covariates/2-2_CALIBER_skinny.py |
# COMMAND ----------
# MAGIC %run /Workspaces/dars_nic_391419_j3w9t_collab/CCU013/COVID-19-SEVERITY-PHENOTYPING/CCU013_00_helper_functions
# COMMAND ----------
# Params
# Use the latest ProductionDate
production_date = spark.sql("SELECT MAX(ProductionDate) FROM dars_nic_391419_j3w9t_collab.wrang002b_data_version_ba... | 0.579638 | 0.366023 |
from rest_framework import serializers
from django.contrib.auth import authenticate
from django.conf import settings
from .models import Entry, User
import logging
class EntrySerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Entry
... | vishnu/serializers.py | from rest_framework import serializers
from django.contrib.auth import authenticate
from django.conf import settings
from .models import Entry, User
import logging
class EntrySerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Entry
... | 0.601125 | 0.141222 |
# -*- coding: utf-8 -*-
# @Author: AnthonyKenny98
# @Date: 2020-01-05 11:05:27
# @Last Modified by: AnthonyKenny98
# @Last Modified time: 2020-03-20 11:48:15
import csv
import os
from termcolor import colored
import sys
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
def rrt_config():
"""Get configur... | src/setup.py | # -*- coding: utf-8 -*-
# @Author: AnthonyKenny98
# @Date: 2020-01-05 11:05:27
# @Last Modified by: AnthonyKenny98
# @Last Modified time: 2020-03-20 11:48:15
import csv
import os
from termcolor import colored
import sys
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
def rrt_config():
"""Get configur... | 0.412767 | 0.199152 |
import numpy as np
import numpy.testing as npt
import pandas as pd
from handyspark import *
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.pipeline import Pipeline
from pyspark.mllib.evaluation import BinaryClassificationMetrics
from sklearn.m... | tests/handyspark/extensions/test_evaluation.py | import numpy as np
import numpy.testing as npt
import pandas as pd
from handyspark import *
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.pipeline import Pipeline
from pyspark.mllib.evaluation import BinaryClassificationMetrics
from sklearn.m... | 0.796728 | 0.584123 |
from __future__ import print_function
import datetime
import os
import sys
import time
import _thread
import http.client
import socket
import json
client_influxdb = None
if os.getenv("INFLUXDB_ENABLED", "0") == "1":
from influxdb import InfluxDBClient
influxdb_host = os.getenv("INFLUXDB_HOST", "localhost")
... | pieq.py |
from __future__ import print_function
import datetime
import os
import sys
import time
import _thread
import http.client
import socket
import json
client_influxdb = None
if os.getenv("INFLUXDB_ENABLED", "0") == "1":
from influxdb import InfluxDBClient
influxdb_host = os.getenv("INFLUXDB_HOST", "localhost")
... | 0.328853 | 0.042245 |
import tensorflow as tf
def get_train_ops(loss, tf_variables, train_step, clip_mode=None, grad_bound=None, l2_reg=1e-4, lr_warmup_val=None, lr_warmup_steps=100, lr_init=0.1, lr_dec_start=0, lr_dec_every=10000, lr_dec_rate=0.1, lr_dec_min=None, lr_cosine=False, lr_max=None, lr_min=None, lr_T_0=None, lr_T_mul=None, num_t... | pkg/suggestion/v1alpha2/NAS_Reinforcement_Learning/Trainer.py | import tensorflow as tf
def get_train_ops(loss, tf_variables, train_step, clip_mode=None, grad_bound=None, l2_reg=1e-4, lr_warmup_val=None, lr_warmup_steps=100, lr_init=0.1, lr_dec_start=0, lr_dec_every=10000, lr_dec_rate=0.1, lr_dec_min=None, lr_cosine=False, lr_max=None, lr_min=None, lr_T_0=None, lr_T_mul=None, num_t... | 0.547948 | 0.286862 |
import argparse
import array
from collections import deque
import functools
import random
import sys
import time
import phue
import pyaudio
import secrets
SAMPLE_WIDTH_BYTES = 2
CHANNELS = 2
SAMPLE_RATE_HZ = 44100
LIGHT_DIM = 5
LIGHT_SPOT = 255
PER_FRAME_SHIFT = 16 # complete rotation every 4 seconds
class table(dic... | prettylights.py | import argparse
import array
from collections import deque
import functools
import random
import sys
import time
import phue
import pyaudio
import secrets
SAMPLE_WIDTH_BYTES = 2
CHANNELS = 2
SAMPLE_RATE_HZ = 44100
LIGHT_DIM = 5
LIGHT_SPOT = 255
PER_FRAME_SHIFT = 16 # complete rotation every 4 seconds
class table(dic... | 0.270673 | 0.208421 |
import os
import requests
import codecs
from spilleliste.core import Playlist
from spilleliste.core import Artist
from spilleliste.core import Album
from spilleliste.core import Track
from spilleliste.externals import googleimage
from spilleliste.externals import spotify
from spilleliste.externals import youtube
fr... | spilleliste/generator.py |
import os
import requests
import codecs
from spilleliste.core import Playlist
from spilleliste.core import Artist
from spilleliste.core import Album
from spilleliste.core import Track
from spilleliste.externals import googleimage
from spilleliste.externals import spotify
from spilleliste.externals import youtube
fr... | 0.113653 | 0.052912 |
from abc import ABC, abstractmethod
class UnionFind(ABC):
"""
Determines if sites are connected, and if not, connects them.
"""
def __init__(self, n: int) -> None:
"""initializes an array (list) where each value is equal to its index
:param n: int, the number of sites
"""
... | congeries/src/unionfind.py | from abc import ABC, abstractmethod
class UnionFind(ABC):
"""
Determines if sites are connected, and if not, connects them.
"""
def __init__(self, n: int) -> None:
"""initializes an array (list) where each value is equal to its index
:param n: int, the number of sites
"""
... | 0.860325 | 0.732221 |
import tomviz.operators
class OtsuMultipleThreshold(tomviz.operators.CancelableOperator):
def transform_scalars(self, dataset, number_of_thresholds=1,
enable_valley_emphasis=False):
"""This filter performs semi-automatic multithresholding of a data set.
Voxels are automa... | tomviz/python/OtsuMultipleThreshold.py | import tomviz.operators
class OtsuMultipleThreshold(tomviz.operators.CancelableOperator):
def transform_scalars(self, dataset, number_of_thresholds=1,
enable_valley_emphasis=False):
"""This filter performs semi-automatic multithresholding of a data set.
Voxels are automa... | 0.675978 | 0.484136 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='GoodsCategory',
fields=[
('id', models.AutoField(auto_crea... | apps/goods/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='GoodsCategory',
fields=[
('id', models.AutoField(auto_crea... | 0.461259 | 0.167695 |
from typing import List
from dialog_api import messaging_pb2
from dialog_bot_sdk.entities.media.AudioMedia import AudioMedia
from dialog_bot_sdk.entities.media.ImageMedia import ImageMedia
from dialog_bot_sdk.entities.media.InteractiveMediaGroup import InteractiveMediaGroup
from dialog_bot_sdk.entities.media.WebpageM... | dialog_bot_sdk/entities/message/TextMessage.py | from typing import List
from dialog_api import messaging_pb2
from dialog_bot_sdk.entities.media.AudioMedia import AudioMedia
from dialog_bot_sdk.entities.media.ImageMedia import ImageMedia
from dialog_bot_sdk.entities.media.InteractiveMediaGroup import InteractiveMediaGroup
from dialog_bot_sdk.entities.media.WebpageM... | 0.800809 | 0.12603 |
from optparse import OptionParser
from struct import unpack
from sys import stderr, stdout, stdin
from io import open
XML_HEADER = '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE MedlineCitationSet PUBLIC "-//NLM//DTD Medline Citation, 1st January, 2009//EN"
"http://teamsite.nl... | pubmed-fast-filter.py |
from optparse import OptionParser
from struct import unpack
from sys import stderr, stdout, stdin
from io import open
XML_HEADER = '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE MedlineCitationSet PUBLIC "-//NLM//DTD Medline Citation, 1st January, 2009//EN"
"http://teamsite.nl... | 0.203351 | 0.059592 |
import numpy as np
class FlexNode:
def __init__(self, onnx_node, inputs, outputs):
self._onnx_node = onnx_node
self._inputs = inputs
self._outputs = outputs
def get_op_name(self):
return self._onnx_node.name
def get_op_type(self):
return self._onnx_node.op_type
... | operators/flexnode.py | import numpy as np
class FlexNode:
def __init__(self, onnx_node, inputs, outputs):
self._onnx_node = onnx_node
self._inputs = inputs
self._outputs = outputs
def get_op_name(self):
return self._onnx_node.name
def get_op_type(self):
return self._onnx_node.op_type
... | 0.76476 | 0.464112 |
from config.constants import (API_TIME_FORMAT, VOICE_RECORDING, ALL_DATA_STREAMS, DEFAULT_S3_RETRIES,
SURVEY_ANSWERS, SURVEY_TIMINGS, IMAGE_FILE)
from config.settings import (S3_BUCKET, BEIWE_SERVER_AWS_ACCESS_KEY_ID,
BEIWE_SERVER_AWS_SECRET_ACCESS_KEY, S3_REGION_NAME)
import config.load_django
from database.da... | scripts/run_chunker.py | from config.constants import (API_TIME_FORMAT, VOICE_RECORDING, ALL_DATA_STREAMS, DEFAULT_S3_RETRIES,
SURVEY_ANSWERS, SURVEY_TIMINGS, IMAGE_FILE)
from config.settings import (S3_BUCKET, BEIWE_SERVER_AWS_ACCESS_KEY_ID,
BEIWE_SERVER_AWS_SECRET_ACCESS_KEY, S3_REGION_NAME)
import config.load_django
from database.da... | 0.498047 | 0.108425 |
from collections import namedtuple
from typing import Optional
import common_helpers
RESERVED_WORDS = [
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate"... | source/codegen/metadata_mutation.py |
from collections import namedtuple
from typing import Optional
import common_helpers
RESERVED_WORDS = [
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate"... | 0.808786 | 0.241277 |
from flask import request, Blueprint, session, flash, g
from werkzeug.security import generate_password_hash, check_password_hash
from app import db
from models import admin
adminRoute = Blueprint("adminRoute", __name__)
@adminRoute.before_request
def before_request_user():
if "logged" in session:
name =... | routes/admin_route.py | from flask import request, Blueprint, session, flash, g
from werkzeug.security import generate_password_hash, check_password_hash
from app import db
from models import admin
adminRoute = Blueprint("adminRoute", __name__)
@adminRoute.before_request
def before_request_user():
if "logged" in session:
name =... | 0.272025 | 0.034004 |
from __future__ import division, print_function
# STDLIB
import logging
# THIRD-PARTY
import numpy as np
import scipy
from scipy import optimize
__organization__ = 'Space Telescope Science Institute'
module_logger = logging.getLogger('skyfit')
def robust_sigma(in_y, zero=0):
"""
Calculate a resistant est... | skyfit.py | from __future__ import division, print_function
# STDLIB
import logging
# THIRD-PARTY
import numpy as np
import scipy
from scipy import optimize
__organization__ = 'Space Telescope Science Institute'
module_logger = logging.getLogger('skyfit')
def robust_sigma(in_y, zero=0):
"""
Calculate a resistant est... | 0.887497 | 0.603786 |
import pygame
import sys
class End:
def __init__(self, game):
self.game = game
self.state = 'Restart'
self.run_end = True
self.mid_w, self.mid_h = self.game.width//2, self.game.height//2
self.offset = -100
self.restart_x, self.restart_y = self.mid... | end.py | import pygame
import sys
class End:
def __init__(self, game):
self.game = game
self.state = 'Restart'
self.run_end = True
self.mid_w, self.mid_h = self.game.width//2, self.game.height//2
self.offset = -100
self.restart_x, self.restart_y = self.mid... | 0.093156 | 0.085595 |
import os
import click
import flask_admin
from flask import Flask, url_for
from flask.cli import with_appcontext
from flask_security import SQLAlchemyUserDatastore, Security, LoginForm, RegisterForm
from flask_sqlalchemy import SQLAlchemy
from flask_admin import helpers as admin_helpers
from wtforms import StringField
... | slr_label/__init__.py | import os
import click
import flask_admin
from flask import Flask, url_for
from flask.cli import with_appcontext
from flask_security import SQLAlchemyUserDatastore, Security, LoginForm, RegisterForm
from flask_sqlalchemy import SQLAlchemy
from flask_admin import helpers as admin_helpers
from wtforms import StringField
... | 0.53437 | 0.054324 |
# Examples of different implementations of logger.
# Each example is contained withing a function to provide a different namespace
def logger_class():
# Simple logger class that isn't a singleton
class Logger():
# This isn't really needed, just illustrates default __new__
def __new__(cls, *a... | programming-techniques/design-patterns/singleton.py |
# Examples of different implementations of logger.
# Each example is contained withing a function to provide a different namespace
def logger_class():
# Simple logger class that isn't a singleton
class Logger():
# This isn't really needed, just illustrates default __new__
def __new__(cls, *a... | 0.73412 | 0.266286 |
from __future__ import annotations
import os
from typing import ClassVar
from typing import List
from typing import Tuple
import cfg.glob
import db.cls_db_core
import db.cls_run
import sqlalchemy
import utils
# pylint: disable=R0801
# pylint: disable=R0902
# pylint: disable=R0903
class Document:
"""Managing the... | src/dcr/db/cls_document.py | from __future__ import annotations
import os
from typing import ClassVar
from typing import List
from typing import Tuple
import cfg.glob
import db.cls_db_core
import db.cls_run
import sqlalchemy
import utils
# pylint: disable=R0801
# pylint: disable=R0902
# pylint: disable=R0903
class Document:
"""Managing the... | 0.654453 | 0.097734 |
import pytest
import pytablereader as ptr
class Test_TableFileLoaderFactory:
@pytest.mark.parametrize(["value", "expected"], [[None, ValueError]])
def test_exception(self, value, expected):
with pytest.raises(expected):
ptr.factory.TableFileLoaderFactory(value)
class Test_TableFileLoade... | test/factory/test_file_loader_factory.py | import pytest
import pytablereader as ptr
class Test_TableFileLoaderFactory:
@pytest.mark.parametrize(["value", "expected"], [[None, ValueError]])
def test_exception(self, value, expected):
with pytest.raises(expected):
ptr.factory.TableFileLoaderFactory(value)
class Test_TableFileLoade... | 0.403449 | 0.382286 |
from tern.classes.origins import Origins
from tern.utils.general import prop_names
class Package:
'''A package installed within a Docker image layer
attributes:
name: package name
version: package version
pkg_license: package license
src_url: package source url
origins... | tern/classes/package.py |
from tern.classes.origins import Origins
from tern.utils.general import prop_names
class Package:
'''A package installed within a Docker image layer
attributes:
name: package name
version: package version
pkg_license: package license
src_url: package source url
origins... | 0.837121 | 0.352425 |
import os
import os.path
from nose.tools import with_setup
from .utils import check_fusion
from circ2.parse import parse
def setup_function():
'''
Enter data directory
'''
print('#%s: Moving to data directory' % __name__)
os.chdir('data')
def teardown_function():
'''
Delete circ_out dire... | test/test_parse.py | import os
import os.path
from nose.tools import with_setup
from .utils import check_fusion
from circ2.parse import parse
def setup_function():
'''
Enter data directory
'''
print('#%s: Moving to data directory' % __name__)
os.chdir('data')
def teardown_function():
'''
Delete circ_out dire... | 0.24963 | 0.164081 |
from optparse import make_option
from pprint import pformat
from django.core.management.base import CommandError
from go.base.command_utils import BaseGoAccountCommand, make_command_option
class Command(BaseGoAccountCommand):
help = "Manage routers."
option_list = BaseGoAccountCommand.option_list + (
... | go/base/management/commands/go_manage_router.py | from optparse import make_option
from pprint import pformat
from django.core.management.base import CommandError
from go.base.command_utils import BaseGoAccountCommand, make_command_option
class Command(BaseGoAccountCommand):
help = "Manage routers."
option_list = BaseGoAccountCommand.option_list + (
... | 0.403097 | 0.054777 |
import functools
import operator
from chainer import initializers
from chainer import link
from chainer import variable
import chainer.functions as F
from persistent_memory_function import persistent_memory
class PersistentMemory(link.Chain):
def __init__(self, in_size, slot_size, memory_size, ini... | persistent_memory_link.py | import functools
import operator
from chainer import initializers
from chainer import link
from chainer import variable
import chainer.functions as F
from persistent_memory_function import persistent_memory
class PersistentMemory(link.Chain):
def __init__(self, in_size, slot_size, memory_size, ini... | 0.40251 | 0.184639 |
# (c) <NAME>
# http://stackoverflow.com/a/4923529
from os import path
import urllib2
class TldMatcher(object):
# use class vars for lazy loading
MASTERURL = "http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1"
MASTERFILE = 'data/effective_tld_names.dat'
TLDS = Non... | pydnsmap/TldMatcher.py |
# (c) <NAME>
# http://stackoverflow.com/a/4923529
from os import path
import urllib2
class TldMatcher(object):
# use class vars for lazy loading
MASTERURL = "http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1"
MASTERFILE = 'data/effective_tld_names.dat'
TLDS = Non... | 0.327883 | 0.160003 |
import time
def_chars = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"A",
"B",
"C",
"D",
"E",
"F",
"... | python3/iw.py | import time
def_chars = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"A",
"B",
"C",
"D",
"E",
"F",
"... | 0.372049 | 0.427158 |
import os
from ansible import constants as C
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.parsing.splitter import parse_kv
from ansible.playbook.play import Play
from ansible.plugins import get_all_plugin_loaders
from library.connecter.ansible.callback.write import Write_Storage
from l... | library/connecter/ansible/v2_3/adhoc.py | import os
from ansible import constants as C
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.parsing.splitter import parse_kv
from ansible.playbook.play import Play
from ansible.plugins import get_all_plugin_loaders
from library.connecter.ansible.callback.write import Write_Storage
from l... | 0.238018 | 0.086246 |
from serif.theory.enumerated_type import Genericity, Polarity, Tense, Modality, DirectionOfChange
from serif.theory.event_mention_anchor import EventMentionAnchor
from serif.theory.event_mention_factor_type import EventMentionFactorType
from serif.theory.event_mention_type import EventMentionType
from serif.theory.ment... | src/python/serif/theory/event_mention.py | from serif.theory.enumerated_type import Genericity, Polarity, Tense, Modality, DirectionOfChange
from serif.theory.event_mention_anchor import EventMentionAnchor
from serif.theory.event_mention_factor_type import EventMentionFactorType
from serif.theory.event_mention_type import EventMentionType
from serif.theory.ment... | 0.521227 | 0.126299 |
from random import randint
from tkinter import *
from tkinter import ttk
import os, sys
def onAlphabetPress(event):
global char_indicator, row_indicator, char_count, row_count, guess, freeze_status
if char_indicator < char_count and not freeze_status:
labels[row_indicator][char_indicator]['text'] = eve... | stringle/stringle.py | from random import randint
from tkinter import *
from tkinter import ttk
import os, sys
def onAlphabetPress(event):
global char_indicator, row_indicator, char_count, row_count, guess, freeze_status
if char_indicator < char_count and not freeze_status:
labels[row_indicator][char_indicator]['text'] = eve... | 0.091781 | 0.095349 |
import warnings
import inspect
from functools import wraps
from os import devnull, environ
from subprocess import Popen
from diot import Diot
import executing
import curio
STDIN = -7
STDOUT = -2
STDERR = -8
DEVNULL = devnull
# Sometimes we may occasionally use envs instead env
POPEN_ARG_KEYS = inspect.getfullargspec(... | cmdy/cmdy_util.py | import warnings
import inspect
from functools import wraps
from os import devnull, environ
from subprocess import Popen
from diot import Diot
import executing
import curio
STDIN = -7
STDOUT = -2
STDERR = -8
DEVNULL = devnull
# Sometimes we may occasionally use envs instead env
POPEN_ARG_KEYS = inspect.getfullargspec(... | 0.513425 | 0.126623 |
from pathlib import Path, PurePath
from typing import Any, Dict, List, Optional, Union
import numpy as np
import torch
from PIL import Image # TODO use image utils
import inc.python_image_utilities.image_util as iutil
import preprocessing as pre
PathLike = Union[str, Path, PurePath]
class ImageFolderDataset(torch... | data.py | from pathlib import Path, PurePath
from typing import Any, Dict, List, Optional, Union
import numpy as np
import torch
from PIL import Image # TODO use image utils
import inc.python_image_utilities.image_util as iutil
import preprocessing as pre
PathLike = Union[str, Path, PurePath]
class ImageFolderDataset(torch... | 0.730674 | 0.521106 |
import pytest
import logging as logging
import ckan.model as model
import ckan.plugins.toolkit as tk
import ckan.logic as logic
import unicodedata
import ckan.lib.helpers as h
import ckanext.hdx_theme.tests.hdx_test_base as hdx_test_base
import ckanext.hdx_theme.tests.hdx_test_with_inds_and_orgs as hdx_test_with_inds... | ckanext-hdx_users/ckanext/hdx_users/tests/test_permissions_controller.py | import pytest
import logging as logging
import ckan.model as model
import ckan.plugins.toolkit as tk
import ckan.logic as logic
import unicodedata
import ckan.lib.helpers as h
import ckanext.hdx_theme.tests.hdx_test_base as hdx_test_base
import ckanext.hdx_theme.tests.hdx_test_with_inds_and_orgs as hdx_test_with_inds... | 0.372277 | 0.28005 |
import logging
import re
from typing import TYPE_CHECKING, cast, no_type_check
from urllib.parse import quote as urlquote
from urllib.parse import urlparse, urlunparse
from optimade.models import (
EntryInfoResponse,
EntryResponseMany,
EntryResponseOne,
InfoResponse,
LinksResponse,
ReferenceRes... | oteapi_optimade/models/custom_types.py | import logging
import re
from typing import TYPE_CHECKING, cast, no_type_check
from urllib.parse import quote as urlquote
from urllib.parse import urlparse, urlunparse
from optimade.models import (
EntryInfoResponse,
EntryResponseMany,
EntryResponseOne,
InfoResponse,
LinksResponse,
ReferenceRes... | 0.835181 | 0.132571 |
import renderapi
import requests
from asap.module.render_module import (
RenderModule, RenderModuleException)
from asap.stack.schemas import SwapZsParameters, SwapZsOutput
example = {
"render": {
"host": "em-131db",
"port": 8080,
"owner": "gayathrim",
"project": "17797_1R",
... | asap/stack/swap_zs.py | import renderapi
import requests
from asap.module.render_module import (
RenderModule, RenderModuleException)
from asap.stack.schemas import SwapZsParameters, SwapZsOutput
example = {
"render": {
"host": "em-131db",
"port": 8080,
"owner": "gayathrim",
"project": "17797_1R",
... | 0.29972 | 0.413181 |
import os
from datetime import datetime
import pandas as pd
import logging
from helpers.date_tools import unixtime_to_datetime
import os
from datetime import datetime
import pandas as pd
LOG = logging.getLogger(__name__)
def rm_col_names(_df, exclude_list):
"""Take dataframe column names and remove those in sup... | helpers/dateframe_tools.py |
import os
from datetime import datetime
import pandas as pd
import logging
from helpers.date_tools import unixtime_to_datetime
import os
from datetime import datetime
import pandas as pd
LOG = logging.getLogger(__name__)
def rm_col_names(_df, exclude_list):
"""Take dataframe column names and remove those in sup... | 0.366703 | 0.191536 |
import time
from virtman.drivers import connector
from virtman.drivers import dmsetup
from virtman.openstack.common import log as logging
LOG = logging.getLogger(__name__)
iscsi_disk_format = "ip-%s-iscsi-%s-lun-%s"
class Path(object):
def __init__(self, connection):
self.connection = connection
... | virtman/path.py | import time
from virtman.drivers import connector
from virtman.drivers import dmsetup
from virtman.openstack.common import log as logging
LOG = logging.getLogger(__name__)
iscsi_disk_format = "ip-%s-iscsi-%s-lun-%s"
class Path(object):
def __init__(self, connection):
self.connection = connection
... | 0.395718 | 0.102754 |
__author__ = 'Ethan'
import keras.backend as K
import keras.layers
from keras.layers import Activation, Lambda, Multiply, Add
from keras.layers import Conv1D, Dropout
from keras.models import Input, Model
def process_dilations(dilations):
""" helper function to validate and process the dilation rate of
the ... | model.py | __author__ = 'Ethan'
import keras.backend as K
import keras.layers
from keras.layers import Activation, Lambda, Multiply, Add
from keras.layers import Conv1D, Dropout
from keras.models import Input, Model
def process_dilations(dilations):
""" helper function to validate and process the dilation rate of
the ... | 0.948799 | 0.570002 |
from re import compile, escape
FILL_NONE_VALUES = '[параметр]'
DEFAULT_ERROR_GENERATION_PREFIX = 'Произошла ошибка,' \
' возможно вы имели ввиду: '
class RegularExpression:
def __init__(self, expr, match_type="match",
flags=0):
self.regex = compile(expr... | awtg/filtering/stdfilters/std.py | from re import compile, escape
FILL_NONE_VALUES = '[параметр]'
DEFAULT_ERROR_GENERATION_PREFIX = 'Произошла ошибка,' \
' возможно вы имели ввиду: '
class RegularExpression:
def __init__(self, expr, match_type="match",
flags=0):
self.regex = compile(expr... | 0.447219 | 0.093802 |
import unittest
import mock
import data.data_collection
from data.data_collection import *
from data.test_constants import *
import data.utils
class DataCollectionTest(unittest.TestCase):
"""
Class that tests the functions in the data_collection.py.
"""
def get_commit_info_side_effect(self, repo_name... | data/data_collection_test.py |
import unittest
import mock
import data.data_collection
from data.data_collection import *
from data.test_constants import *
import data.utils
class DataCollectionTest(unittest.TestCase):
"""
Class that tests the functions in the data_collection.py.
"""
def get_commit_info_side_effect(self, repo_name... | 0.674801 | 0.606411 |
def __virtual__():
'''
Load if the module win_dns_client is loaded
'''
return 'win_dns_client' if 'win_dns_client.add_dns' in __salt__ else False
def dns_exists(name, servers=None, interface='Local Area Connection'):
'''
Configure the DNS server list in the specified interface
Example... | salt/states/win_dns_client.py | def __virtual__():
'''
Load if the module win_dns_client is loaded
'''
return 'win_dns_client' if 'win_dns_client.add_dns' in __salt__ else False
def dns_exists(name, servers=None, interface='Local Area Connection'):
'''
Configure the DNS server list in the specified interface
Example... | 0.495117 | 0.096408 |
__all__ = ['ewsum', 'ewsum_back', 'softmax_back', 'rectify_back']
import os
import math
import numpy
import pycuda.gpuarray as gpuarray
import pycuda.autoinit
from pycuda.compiler import SourceModule
from .matrix import matrix_addition
from .utils import gpu_func
from .enums import MAX_BLOCK_SIZE, CUR_DIR, CACHE_DIR
... | sciguppy/misc.py | __all__ = ['ewsum', 'ewsum_back', 'softmax_back', 'rectify_back']
import os
import math
import numpy
import pycuda.gpuarray as gpuarray
import pycuda.autoinit
from pycuda.compiler import SourceModule
from .matrix import matrix_addition
from .utils import gpu_func
from .enums import MAX_BLOCK_SIZE, CUR_DIR, CACHE_DIR
... | 0.309545 | 0.181408 |
import sys
sys.path.append("../")
import unittest
from python_dict_wrapper import wrap
from models import get_dataset, preprocess_data, get_feature_model, get_aggregator
from modelzoo import slowfast_wrapper
import torch
class TestSlowFast(unittest.TestCase):
@unittest.skip("Slow")
def test_each(self):
... | tests/test_slowfast.py | import sys
sys.path.append("../")
import unittest
from python_dict_wrapper import wrap
from models import get_dataset, preprocess_data, get_feature_model, get_aggregator
from modelzoo import slowfast_wrapper
import torch
class TestSlowFast(unittest.TestCase):
@unittest.skip("Slow")
def test_each(self):
... | 0.505127 | 0.397763 |
import mtcnn_detect_face
import tensorflow as tf
from keras import backend as K
import numpy as np
import cv2
import os
class MTCNNFaceDetector():
"""
This class load the MTCNN network and perform face detection.
Attributes:
model_path: path to the MTCNN weights files
"""
def __init__(... | detector/face_detector.py | import mtcnn_detect_face
import tensorflow as tf
from keras import backend as K
import numpy as np
import cv2
import os
class MTCNNFaceDetector():
"""
This class load the MTCNN network and perform face detection.
Attributes:
model_path: path to the MTCNN weights files
"""
def __init__(... | 0.654343 | 0.265767 |
import numpy as np
import torch
from torch.utils.data import Dataset
class RenderDataset(Dataset):
"""Render dataset for smpl renderer."""
def __init__(self, vertices, **kwargs):
"""Prepare the render dataset as for function `render_smpl`.
Args:
vertices (Union[np.ndarray, torch.... | mmhuman3d/core/visualization/renderer/torch3d_renderer/render_datasets.py | import numpy as np
import torch
from torch.utils.data import Dataset
class RenderDataset(Dataset):
"""Render dataset for smpl renderer."""
def __init__(self, vertices, **kwargs):
"""Prepare the render dataset as for function `render_smpl`.
Args:
vertices (Union[np.ndarray, torch.... | 0.923627 | 0.79162 |
import pytest
import os
from unittest.mock import patch
from slack_notiphier import config, logger
@pytest.fixture(scope='session', autouse=True)
def setup_once():
with patch.dict(os.environ, {'NOTIPHIER_CONFIG_FILE': '../tests/resources/slack-notiphier.cfg'}):
config.reload()
logger.reload()
... | tests/conftest.py | import pytest
import os
from unittest.mock import patch
from slack_notiphier import config, logger
@pytest.fixture(scope='session', autouse=True)
def setup_once():
with patch.dict(os.environ, {'NOTIPHIER_CONFIG_FILE': '../tests/resources/slack-notiphier.cfg'}):
config.reload()
logger.reload()
... | 0.326916 | 0.280656 |
import pypush2.ui
import pypush2.colors as colors
from pypush2.encoders import EncoderAction
def dialChanged(sender, action):
if action == EncoderAction.down:
newValue = sender.value - 0.1
if newValue >= sender.min_value:
sender.value = newValue
else:
sender.value = sender.min_value
elif ... | examples/uidemo.py |
import pypush2.ui
import pypush2.colors as colors
from pypush2.encoders import EncoderAction
def dialChanged(sender, action):
if action == EncoderAction.down:
newValue = sender.value - 0.1
if newValue >= sender.min_value:
sender.value = newValue
else:
sender.value = sender.min_value
elif ... | 0.261614 | 0.182407 |
import os
import sys
from pathlib import Path
from textwrap import dedent
from typing import Dict, List, Set
import lxml.html
from _pytest.fixtures import FixtureRequest
from lxml.etree import _Element
from pytest import fixture
from nikola import Nikola
from nikola.post import Post
from nikola.utils import LocaleBor... | tests/conftest.py | import os
import sys
from pathlib import Path
from textwrap import dedent
from typing import Dict, List, Set
import lxml.html
from _pytest.fixtures import FixtureRequest
from lxml.etree import _Element
from pytest import fixture
from nikola import Nikola
from nikola.post import Post
from nikola.utils import LocaleBor... | 0.449151 | 0.241009 |
from hashlib import sha1, sha224, sha256, sha512, md5
from math import ceil
from random import randint
from struct import pack
import M2Crypto
_curves = {u'very-low': M2Crypto.EC.NID_sect163k1,
u'low': M2Crypto.EC.NID_sect233k1,
u'medium': M2Crypto.EC.NID_sect409k1,
u'high': M2Crypto.EC.NID_sect571r1}
def _progress... | acestream/ACEStream/Core/dispersy/crypto.py | from hashlib import sha1, sha224, sha256, sha512, md5
from math import ceil
from random import randint
from struct import pack
import M2Crypto
_curves = {u'very-low': M2Crypto.EC.NID_sect163k1,
u'low': M2Crypto.EC.NID_sect233k1,
u'medium': M2Crypto.EC.NID_sect409k1,
u'high': M2Crypto.EC.NID_sect571r1}
def _progress... | 0.520009 | 0.140985 |
import logging
from pathlib import Path
import mediafile
import pluggy
import moe
from moe.config import Config, MoeSession
from moe.library.album import Album
from moe.library.extra import Extra
from moe.library.lib_item import LibItem
from moe.library.track import Track, TrackError
__all__ = ["add_item", "AddError... | moe/plugins/add/add_core/add.py | import logging
from pathlib import Path
import mediafile
import pluggy
import moe
from moe.config import Config, MoeSession
from moe.library.album import Album
from moe.library.extra import Extra
from moe.library.lib_item import LibItem
from moe.library.track import Track, TrackError
__all__ = ["add_item", "AddError... | 0.828141 | 0.199522 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | Adventures/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | 0.573678 | 0.194731 |
import api_utils.test as tu
from core_api import constants
# NZS1170p5 Tests
def test_get_nzs1170p5_ensemble_hazard(config):
""" Tests the successful get request of a NZS1170p5 ensemble hazard"""
response = tu.send_test_request(
constants.NZS1170p5_HAZARD_ENDPOINT,
config["general"],
)
... | apis/core_api/core_api/test/test_core_nzs1170p5.py | import api_utils.test as tu
from core_api import constants
# NZS1170p5 Tests
def test_get_nzs1170p5_ensemble_hazard(config):
""" Tests the successful get request of a NZS1170p5 ensemble hazard"""
response = tu.send_test_request(
constants.NZS1170p5_HAZARD_ENDPOINT,
config["general"],
)
... | 0.437824 | 0.291529 |
from typing import Optional
from typing import Union
import numpy as np
from scipy.sparse.coo import coo_matrix
from ._typing_utils import Float
from ._typing_utils import Matrix
from ._utils import coo_matrix_builder
def build_frame_cost_matrix(
dist_matrix: coo_matrix_builder,
*,
track_start_cost: Opt... | src/laptrack/_cost_matrix.py | from typing import Optional
from typing import Union
import numpy as np
from scipy.sparse.coo import coo_matrix
from ._typing_utils import Float
from ._typing_utils import Matrix
from ._utils import coo_matrix_builder
def build_frame_cost_matrix(
dist_matrix: coo_matrix_builder,
*,
track_start_cost: Opt... | 0.9363 | 0.571946 |
import os
import io
import json
import hashlib
from PIL import Image
from http import HTTPStatus
from pathlib import Path
from starlette.responses import JSONResponse
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware
import uvicorn
from fastai.vision import load_learner, ... | backend/src/main.py | import os
import io
import json
import hashlib
from PIL import Image
from http import HTTPStatus
from pathlib import Path
from starlette.responses import JSONResponse
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware
import uvicorn
from fastai.vision import load_learner, ... | 0.707 | 0.176778 |
import datetime
from enum import Enum
from typing import Iterable
from parentopticon import ui
from parentopticon.db import queries
from parentopticon.db.connection import Connection
from parentopticon.db.tables import Program, ProgramSession
class ActionType(Enum):
# Kill a program
kill = "kill"
# Show a warning
... | parentopticon/enforcement.py | import datetime
from enum import Enum
from typing import Iterable
from parentopticon import ui
from parentopticon.db import queries
from parentopticon.db.connection import Connection
from parentopticon.db.tables import Program, ProgramSession
class ActionType(Enum):
# Kill a program
kill = "kill"
# Show a warning
... | 0.542621 | 0.195652 |
import requests
import os
import json
import tempfile
import pandas as pd
import sys
from fasp.workflow import WESClient
from fasp.loc import DRSMetaResolver
class sbWESClient(WESClient):
def __init__(self, api_url_base, project, access_token_path, instance=None, debug=False):
# instance is now redundant - use... | fasp/workflow/sb_wes_client.py | import requests
import os
import json
import tempfile
import pandas as pd
import sys
from fasp.workflow import WESClient
from fasp.loc import DRSMetaResolver
class sbWESClient(WESClient):
def __init__(self, api_url_base, project, access_token_path, instance=None, debug=False):
# instance is now redundant - use... | 0.10885 | 0.078819 |
import itertools
import fileinput
nucleotides = ['A', 'C', 'G', 'T']
def hamming_distance(str1, str2):
assert len(str1) == len(str2)
count = 0
for c1, c2 in zip(str1, str2):
if c1 != c2:
count += 1
return count
def filter(input, combo, index, data, key, strs):
... | HW-3/answer1.py |
import itertools
import fileinput
nucleotides = ['A', 'C', 'G', 'T']
def hamming_distance(str1, str2):
assert len(str1) == len(str2)
count = 0
for c1, c2 in zip(str1, str2):
if c1 != c2:
count += 1
return count
def filter(input, combo, index, data, key, strs):
... | 0.233881 | 0.389721 |
Caveats:
Python Image Library uses the inverted coordinate frame to represent pixels - so (width, height) ~ (x, y)
Numpy uses the matrix representation (x, y) ~ (height, width)
Hence be careful when using Image.fromarray -
"""
from matplotlib.path import Path
from PIL import Image
import csv
import n... | Homography/homography.py | Caveats:
Python Image Library uses the inverted coordinate frame to represent pixels - so (width, height) ~ (x, y)
Numpy uses the matrix representation (x, y) ~ (height, width)
Hence be careful when using Image.fromarray -
"""
from matplotlib.path import Path
from PIL import Image
import csv
import n... | 0.747708 | 0.758018 |
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import Node, OVSKernelSwitch
from mininet.log import setLogLevel, info
from mininet.cli import CLI
import time
import os
workdir = os.path.dirname(os.path.realpath(__file__))
class LinuxRouter( Node ):
"A Node with IP forwarding enab... | mininet/bgp-lab1/topo.py |
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import Node, OVSKernelSwitch
from mininet.log import setLogLevel, info
from mininet.cli import CLI
import time
import os
workdir = os.path.dirname(os.path.realpath(__file__))
class LinuxRouter( Node ):
"A Node with IP forwarding enab... | 0.317109 | 0.080574 |
from utils import create_path
from sales import sales
import json
def create_account():
name = input("\nEscribe tu nombre: ")
if name == "":
print("Cancelado\n")
else:
with open("./users.db") as us:
users = json.load(us)
if name in users:
print(
... | src/accounts.py | from utils import create_path
from sales import sales
import json
def create_account():
name = input("\nEscribe tu nombre: ")
if name == "":
print("Cancelado\n")
else:
with open("./users.db") as us:
users = json.load(us)
if name in users:
print(
... | 0.145358 | 0.134066 |
import torch
import torchbearer
from torchbearer import cite
from torchbearer.callbacks import Callback, only_if, once_per_epoch
bibtex = """
@article{inoue2018data,
title={Data augmentation by pairing samples for images classification},
author={<NAME>},
journal={arXiv preprint arXiv:1801.02929},
year={2018}... | torchbearer/callbacks/sample_pairing.py | import torch
import torchbearer
from torchbearer import cite
from torchbearer.callbacks import Callback, only_if, once_per_epoch
bibtex = """
@article{inoue2018data,
title={Data augmentation by pairing samples for images classification},
author={<NAME>},
journal={arXiv preprint arXiv:1801.02929},
year={2018}... | 0.932476 | 0.429609 |
from kv1_811 import *
from inserter import insert,version_imported,reject
from bs4 import BeautifulSoup
import urllib2
from datetime import datetime,timedelta
from htm import setLineColors,cleanDest,generatePool
import logging
from settings.const import *
logger = logging.getLogger("importer")
def getDataSource():
... | importers/htmbuzz.py | from kv1_811 import *
from inserter import insert,version_imported,reject
from bs4 import BeautifulSoup
import urllib2
from datetime import datetime,timedelta
from htm import setLineColors,cleanDest,generatePool
import logging
from settings.const import *
logger = logging.getLogger("importer")
def getDataSource():
... | 0.144903 | 0.076132 |
from __future__ import print_function
import math
import threading
import time
class PoseSphere:
def __init__(self, name, priority=1):
self.position = (0.0, 0.0, 0.0)
self.p2 = (0.0, 0.0, 0.0)
self.type = 'sphere'
self.angle = 0.0
self.radius = 1.0
self.tolerance =... | libs/pose_sphere.py | from __future__ import print_function
import math
import threading
import time
class PoseSphere:
def __init__(self, name, priority=1):
self.position = (0.0, 0.0, 0.0)
self.p2 = (0.0, 0.0, 0.0)
self.type = 'sphere'
self.angle = 0.0
self.radius = 1.0
self.tolerance =... | 0.650689 | 0.315894 |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import six
from six.moves import urllib_parse
from repoze.lru import lru_cache
try:
from pyramid.traversal import _segment_cache
except ImportError: # pragma: no cover
_segment_cache = {}
PATH_SEGM... | src/nti/traversal/compat.py | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import six
from six.moves import urllib_parse
from repoze.lru import lru_cache
try:
from pyramid.traversal import _segment_cache
except ImportError: # pragma: no cover
_segment_cache = {}
PATH_SEGM... | 0.585694 | 0.07333 |
# author: BrikerMan
# contact: <EMAIL>
# blog: https://eliyar.biz
# file: test_processor.py
# time: 2019-05-23 17:02
import os
import time
import logging
import tempfile
import unittest
import numpy as np
import random
from kashgari import utils
from kashgari.processors import ClassificationProcessor, LabelingProcess... | tests/test_processor.py |
# author: BrikerMan
# contact: <EMAIL>
# blog: https://eliyar.biz
# file: test_processor.py
# time: 2019-05-23 17:02
import os
import time
import logging
import tempfile
import unittest
import numpy as np
import random
from kashgari import utils
from kashgari.processors import ClassificationProcessor, LabelingProcess... | 0.476092 | 0.407746 |
import os
from exporting.export_objects import get_objects, \
get_query_rulebase_data, format_and_merge_data, \
clean_objects, singular_to_plural_dictionary, format_and_merge_unexportable_objects, \
replace_rule_field_uids_by_name, cleanse_object_dictionary, export_general_objects
from utils import debug_l... | exporting/export_https_rulebase.py | import os
from exporting.export_objects import get_objects, \
get_query_rulebase_data, format_and_merge_data, \
clean_objects, singular_to_plural_dictionary, format_and_merge_unexportable_objects, \
replace_rule_field_uids_by_name, cleanse_object_dictionary, export_general_objects
from utils import debug_l... | 0.241668 | 0.174797 |