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 os import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec import numpy as np import urllib.request import matplotlib.patches as patches import matplotlib.transforms as transforms # print message after packages imported successfully print("import of packages successful") def cm2inch(*tupl): ...
src/tools/matplotlib/mgntPhiFFT.py
import os import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec import numpy as np import urllib.request import matplotlib.patches as patches import matplotlib.transforms as transforms # print message after packages imported successfully print("import of packages successful") def cm2inch(*tupl): ...
0.270673
0.643525
import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as func import pydot from .commons import Identity class GraphSequential(nn.Module): def __init__(self, node_embedding, *args): """ :param node_embedding: embedding extracted from text, either nu...
plasma/modules/graph.py
import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as func import pydot from .commons import Identity class GraphSequential(nn.Module): def __init__(self, node_embedding, *args): """ :param node_embedding: embedding extracted from text, either nu...
0.961938
0.646725
import json import facilities import pandas as pd import projects import users_and_facilities import users_and_projects # Todo: address pandas warning w/out silencing pd.options.mode.chained_assignment = None # Define years over which compliance data will be considered and where to find it reporting_periods = ['2013...
scripts/build_users_data.py
import json import facilities import pandas as pd import projects import users_and_facilities import users_and_projects # Todo: address pandas warning w/out silencing pd.options.mode.chained_assignment = None # Define years over which compliance data will be considered and where to find it reporting_periods = ['2013...
0.218003
0.339526
from codegen_sources.preprocessing.lang_processors.tokenization_utils import ( process_string, ) from codegen_sources.preprocessing.lang_processors.lang_processor import LangProcessor from codegen_sources.preprocessing.obfuscation.bobskater_obfuscator import ( obfuscateString, ) from codegen_sources.preprocessi...
codegen_sources/preprocessing/lang_processors/python_processor.py
from codegen_sources.preprocessing.lang_processors.tokenization_utils import ( process_string, ) from codegen_sources.preprocessing.lang_processors.lang_processor import LangProcessor from codegen_sources.preprocessing.obfuscation.bobskater_obfuscator import ( obfuscateString, ) from codegen_sources.preprocessi...
0.375477
0.297572
"""Message ID tests. """ import sys import unittest from zope.i18nmessageid import message as messageid class PyMessageTests(unittest.TestCase): _TEST_READONLY = True def _getTargetClass(self): return messageid.pyMessage def _makeOne(self, *args, **kw): return self._getTargetClass()(*ar...
ven2/lib/python2.7/site-packages/zope/i18nmessageid/tests.py
"""Message ID tests. """ import sys import unittest from zope.i18nmessageid import message as messageid class PyMessageTests(unittest.TestCase): _TEST_READONLY = True def _getTargetClass(self): return messageid.pyMessage def _makeOne(self, *args, **kw): return self._getTargetClass()(*ar...
0.478041
0.386821
import pytest from unittest import mock from django.http import HttpRequest from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from mixer.backend.django import mixer from posts.models import Post from posts.permissions import PostPermission User = get_user_model() ...
backend/spacenews/posts/tests/test_permissions.py
import pytest from unittest import mock from django.http import HttpRequest from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from mixer.backend.django import mixer from posts.models import Post from posts.permissions import PostPermission User = get_user_model() ...
0.478041
0.251343
import url_manager, html_downloader, baidu_parser, baidu_outputer from bs4 import BeautifulSoup import urllib from urllib.parse import urljoin import pandas class SpiderMain(object): def __init__(self): self.urls = url_manager.UrlManager() self.downloader = html_downloader.HtmlDownloader() ...
baidu_crawl.py
import url_manager, html_downloader, baidu_parser, baidu_outputer from bs4 import BeautifulSoup import urllib from urllib.parse import urljoin import pandas class SpiderMain(object): def __init__(self): self.urls = url_manager.UrlManager() self.downloader = html_downloader.HtmlDownloader() ...
0.093287
0.041852
import os from ff_presets.config import read_yaml from ff_presets.preset_base import _Preset import copy class PAudio(_Preset): def __init__(self, name: str = None, src: dict = None, stream_number: str = None, stream_preset: _Preset = None): ''' name - если не указана переменная preset - путь к фа...
ff_presets/preset_audio.py
import os from ff_presets.config import read_yaml from ff_presets.preset_base import _Preset import copy class PAudio(_Preset): def __init__(self, name: str = None, src: dict = None, stream_number: str = None, stream_preset: _Preset = None): ''' name - если не указана переменная preset - путь к фа...
0.424412
0.154312
Core = [ "You suffered a tragedy: ", "You gained a bit of good fortune: ", "You fell in love, got married, or had a child.", "You made an enemy of an adventurer. You may or may not be to blame.", "You made a friend of an adventurer.", "You spent time working in a job related to your background. Start the game with +2d6...
tabs/events.py
Core = [ "You suffered a tragedy: ", "You gained a bit of good fortune: ", "You fell in love, got married, or had a child.", "You made an enemy of an adventurer. You may or may not be to blame.", "You made a friend of an adventurer.", "You spent time working in a job related to your background. Start the game with +2d6...
0.333503
0.61464
import os import numpy as np import pytest from astropy.coordinates import Angle import astropy.units as units from astropy.time import Time from pyradiosky import SkyModel import pyradiosky.utils as skyutils def test_tee_ra_loop(): time = Time(2457458.1739, scale="utc", format="jd") tee_ra = Angle(np.pi / ...
pyradiosky/tests/test_utils.py
import os import numpy as np import pytest from astropy.coordinates import Angle import astropy.units as units from astropy.time import Time from pyradiosky import SkyModel import pyradiosky.utils as skyutils def test_tee_ra_loop(): time = Time(2457458.1739, scale="utc", format="jd") tee_ra = Angle(np.pi / ...
0.741393
0.560132
import requests from bs4 import BeautifulSoup as bs from random import choice from django.views import View from django.http import JsonResponse from django.views.generic.detail import SingleObjectMixin import json from selenium import webdriver from time import sleep import urllib3 urllib3.disable_warnings(urllib3.ex...
backend/src/leads/views.py
import requests from bs4 import BeautifulSoup as bs from random import choice from django.views import View from django.http import JsonResponse from django.views.generic.detail import SingleObjectMixin import json from selenium import webdriver from time import sleep import urllib3 urllib3.disable_warnings(urllib3.ex...
0.244273
0.099865
from scion.SCXML import urlToModel,createInterpreter from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler import json import sys import traceback import pdb sessionCounter = 0 sessions = {} timeouts = {} timeoutMs = 5000 class SCIONTestHandler(BaseHTTPRequestHandler): def do_POST(self): global se...
test/test-server.py
from scion.SCXML import urlToModel,createInterpreter from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler import json import sys import traceback import pdb sessionCounter = 0 sessions = {} timeouts = {} timeoutMs = 5000 class SCIONTestHandler(BaseHTTPRequestHandler): def do_POST(self): global se...
0.11016
0.049405
import numpy from amuse.lab import * from amuse.couple import bridge from amuse import datamodel from amuse.ext.evrard_test import uniform_unit_sphere def new_sph_particles_from_stellar_wind(stars, mgas): new_sph=datamodel.Particles(0) for si in stars: p = si.position v = si.velocity N...
examples/syllabus/stellar_gravity_hydro.py
import numpy from amuse.lab import * from amuse.couple import bridge from amuse import datamodel from amuse.ext.evrard_test import uniform_unit_sphere def new_sph_particles_from_stellar_wind(stars, mgas): new_sph=datamodel.Particles(0) for si in stars: p = si.position v = si.velocity N...
0.338186
0.335732
"""Entrypoint and CLI handler.""" import argparse import json import shutil import signal import tempfile from time import sleep from prometheus_client import start_http_server import prometheuspvesd.exception from prometheuspvesd import __version__ from prometheuspvesd.config import SingleConfig from prometheuspves...
prometheuspvesd/cli.py
"""Entrypoint and CLI handler.""" import argparse import json import shutil import signal import tempfile from time import sleep from prometheus_client import start_http_server import prometheuspvesd.exception from prometheuspvesd import __version__ from prometheuspvesd.config import SingleConfig from prometheuspves...
0.517327
0.089733
import allure import pytest import os from antiphishme.tests.test_helpers import ( assert_true, assert_equal, assert_none, assert_type, assert_exception, assert_no_exception, assert_false, assert_dict_contains_key, assert_not_empty, assert_empty, info ) from antiphishme.src...
antiphishme/tests/unit/api_modules/whois_test.py
import allure import pytest import os from antiphishme.tests.test_helpers import ( assert_true, assert_equal, assert_none, assert_type, assert_exception, assert_no_exception, assert_false, assert_dict_contains_key, assert_not_empty, assert_empty, info ) from antiphishme.src...
0.461502
0.426441
class BaseError(Exception): """SmartFile Sync base Exception. """ pass class UploadError(BaseError): """ Exception for general upload errors. """ def __init__(self, exc, *args, **kwargs): self.exc = exc self.detail = str(exc) super(UploadError, self).__init__(*args, **kwargs) ...
app/sync/errors.py
class BaseError(Exception): """SmartFile Sync base Exception. """ pass class UploadError(BaseError): """ Exception for general upload errors. """ def __init__(self, exc, *args, **kwargs): self.exc = exc self.detail = str(exc) super(UploadError, self).__init__(*args, **kwargs) ...
0.688992
0.105211
import os import vcf import pandas as pd # Creation of profiles def profile_sort_order(string): "Sort order specification." s = string.split('\t') return [s[0].upper().replace('_', ' '), int(s[1]), s[3].upper(), s[4].upper(), s[5].upper().replace('.', ':'...
varclust/profiles.py
import os import vcf import pandas as pd # Creation of profiles def profile_sort_order(string): "Sort order specification." s = string.split('\t') return [s[0].upper().replace('_', ' '), int(s[1]), s[3].upper(), s[4].upper(), s[5].upper().replace('.', ':'...
0.398758
0.300527
import json class Contact(object): """ Contact object to provide validation of form data. """ def __init__(self, form): """ Initialize contact and populate fields using form data. """ self.data = {} self.update(form) def __str__(self): """ ...
contact.py
import json class Contact(object): """ Contact object to provide validation of form data. """ def __init__(self, form): """ Initialize contact and populate fields using form data. """ self.data = {} self.update(form) def __str__(self): """ ...
0.226313
0.25182
from typing import TYPE_CHECKING, List, Tuple, Dict, Any, Sequence, Optional import numpy as np import scipy.interpolate as interp import scipy.optimize as sciopt from bag.simulation.core import TestbenchManager if TYPE_CHECKING: from bag.core import Testbench class ACTB(TestbenchManager): """This class se...
bag_testbenches_ec/verification_ec/ac/core.py
from typing import TYPE_CHECKING, List, Tuple, Dict, Any, Sequence, Optional import numpy as np import scipy.interpolate as interp import scipy.optimize as sciopt from bag.simulation.core import TestbenchManager if TYPE_CHECKING: from bag.core import Testbench class ACTB(TestbenchManager): """This class se...
0.920478
0.283093
import traceback from time import sleep from algotip_bot.clients import console, reddit from algotip_bot.errors import (InvalidCommandError, InvalidSubredditError, InvalidUserError, NotModeratorError) from algotip_bot.handlers import EventHandler from algotip_bot.templates import ...
algotip_bot/main.py
import traceback from time import sleep from algotip_bot.clients import console, reddit from algotip_bot.errors import (InvalidCommandError, InvalidSubredditError, InvalidUserError, NotModeratorError) from algotip_bot.handlers import EventHandler from algotip_bot.templates import ...
0.145176
0.045564
import matplotlib matplotlib.use('Agg') # scientific computing library import numpy as np # visualization tools import matplotlib.pyplot as plt import seaborn as sns # prettify plots plt.rcParams['figure.figsize'] = [12.0, 9.0] sns.set_palette(sns.color_palette("muted")) sns.set_style("ticks") # helper data preproc...
src/eig_b.py
import matplotlib matplotlib.use('Agg') # scientific computing library import numpy as np # visualization tools import matplotlib.pyplot as plt import seaborn as sns # prettify plots plt.rcParams['figure.figsize'] = [12.0, 9.0] sns.set_palette(sns.color_palette("muted")) sns.set_style("ticks") # helper data preproc...
0.444324
0.38168
from django.shortcuts import render from admin_resign.form import resign_form import MySQLdb import time import gettext from django.http.response import HttpResponse # Create your views here. def index(request): print request.method message = '' if request.method == 'POST': print 'getPost' ...
ProjectSystem/admin_resign/views.py
from django.shortcuts import render from admin_resign.form import resign_form import MySQLdb import time import gettext from django.http.response import HttpResponse # Create your views here. def index(request): print request.method message = '' if request.method == 'POST': print 'getPost' ...
0.139954
0.049843
import hostapd def test_he_open(dev, apdev): """HE AP with open mode configuration""" params = {"ssid": "he", "ieee80211ax": "1", "he_bss_color": "42", "he_mu_edca_ac_be_ecwmin": "7", "he_mu_edca_ac_be_ecwmax": "15"} hapd = hostapd.add_ap(apdev[0], p...
tests/hwsim/test_he.py
import hostapd def test_he_open(dev, apdev): """HE AP with open mode configuration""" params = {"ssid": "he", "ieee80211ax": "1", "he_bss_color": "42", "he_mu_edca_ac_be_ecwmin": "7", "he_mu_edca_ac_be_ecwmax": "15"} hapd = hostapd.add_ap(apdev[0], p...
0.319334
0.225278
import datetime import random import sys import math import praw import thoughts try: from secrets import SECRETS except ImportError as ex: print("secrets.py file can't be accessed\n") print(ex) sys.exit() except SyntaxError as ex: print("There is a syntax error in the secrets.py\n") print(ex) ...
core.py
import datetime import random import sys import math import praw import thoughts try: from secrets import SECRETS except ImportError as ex: print("secrets.py file can't be accessed\n") print(ex) sys.exit() except SyntaxError as ex: print("There is a syntax error in the secrets.py\n") print(ex) ...
0.209631
0.069321
# If you want this, it has to happen before importing git, as silly as that is: #os.environ.update({'GIT_PYTHON_TRACE': 'full'}) import git import gitdb import os from twitter.common import app from twitter.common import log from butcher import address app.add_option('--repo_baseurl', dest='repo_baseurl', ...
butcher/gitrepo.py
# If you want this, it has to happen before importing git, as silly as that is: #os.environ.update({'GIT_PYTHON_TRACE': 'full'}) import git import gitdb import os from twitter.common import app from twitter.common import log from butcher import address app.add_option('--repo_baseurl', dest='repo_baseurl', ...
0.416322
0.107578
from __future__ import absolute_import import logging try: from logging import NullHandler except ImportError: # Create a NullHandler class in logging for python 2.6 class NullHandler(logging.Handler): def emit(self, record): pass import socket try: from threading import RLock ...
riemann_client/client.py
from __future__ import absolute_import import logging try: from logging import NullHandler except ImportError: # Create a NullHandler class in logging for python 2.6 class NullHandler(logging.Handler): def emit(self, record): pass import socket try: from threading import RLock ...
0.869521
0.295251
from models.dense_net import DenseNetConfig, DenseNet from models.convnet import SimpleConvnetConfig, SimpleConvnet import numpy as np def get_model_config_by_name(name): if name == 'DenseNet': return DenseNetConfig elif name == 'SimpleConvnet': return SimpleConvnetConfig else: raise ValueError('Unknown mode...
code/models/utils.py
from models.dense_net import DenseNetConfig, DenseNet from models.convnet import SimpleConvnetConfig, SimpleConvnet import numpy as np def get_model_config_by_name(name): if name == 'DenseNet': return DenseNetConfig elif name == 'SimpleConvnet': return SimpleConvnetConfig else: raise ValueError('Unknown mode...
0.574275
0.128388
import collections from functools import partial import QDS import math # Define global stimulus parameters p = {'_sName' : "RGC_MovingBar", '_sDescr' : "'moving bar' in fingerprinting stimulus set", "nTrials" : 2, "DirList" : [0,180, 45,225, 90,270, 135,315], ...
Stimuli/New Stimuli/RGC_MovingBar_3.py
import collections from functools import partial import QDS import math # Define global stimulus parameters p = {'_sName' : "RGC_MovingBar", '_sDescr' : "'moving bar' in fingerprinting stimulus set", "nTrials" : 2, "DirList" : [0,180, 45,225, 90,270, 135,315], ...
0.512693
0.233947
# OpenCV's Python demo # -- adapted by <NAME> to work with ctypes-opencv from ctypes_opencv import * from random import randint def minarea_array(img, count): pointMat = cvCreateMat( count, 1, CV_32SC2 ) for i in range(count): pointMat[i,0] = [randint(img.width/4, img.width*3/4), ...
Codes/PC-Interface/ctypes_opencv/demo/minarea.py
# OpenCV's Python demo # -- adapted by <NAME> to work with ctypes-opencv from ctypes_opencv import * from random import randint def minarea_array(img, count): pointMat = cvCreateMat( count, 1, CV_32SC2 ) for i in range(count): pointMat[i,0] = [randint(img.width/4, img.width*3/4), ...
0.365796
0.329554
import random class WebConf: IP181 = [ 'http://www.ip181.com/daili/1.html', 'http://www.ip181.com/daili/2.html', 'http://www.ip181.com/daili/3.html', 'http://www.ip181.com/daili/4.html', 'http://www.ip181.com/daili/5.html', 'http://www.ip181.com/daili/6.html', '...
Lib/Config.py
import random class WebConf: IP181 = [ 'http://www.ip181.com/daili/1.html', 'http://www.ip181.com/daili/2.html', 'http://www.ip181.com/daili/3.html', 'http://www.ip181.com/daili/4.html', 'http://www.ip181.com/daili/5.html', 'http://www.ip181.com/daili/6.html', '...
0.301773
0.217815
import contextlib import copy import datetime import io import json import logging import os import numpy as np import pycocotools.mask as mask_util from PIL import Image from fvcore.common.file_io import PathManager from fvcore.common.file_io import file_lock from fvcore.common.timer import Timer from tkdet.structur...
tkdet/data/datasets/coco.py
import contextlib import copy import datetime import io import json import logging import os import numpy as np import pycocotools.mask as mask_util from PIL import Image from fvcore.common.file_io import PathManager from fvcore.common.file_io import file_lock from fvcore.common.timer import Timer from tkdet.structur...
0.500977
0.252897
import sys import unittest from qiskit import execute, Aer sys.path.insert(0, "../") from qtcodes import RepetitionQubit, RepetitionDecoder class TestRep(unittest.TestCase): """ Unittests for the XXZZ (CSS) Rotated Surface Code """ def setUp(self): self.params = {"d": 5} self.params[...
test/rep.py
import sys import unittest from qiskit import execute, Aer sys.path.insert(0, "../") from qtcodes import RepetitionQubit, RepetitionDecoder class TestRep(unittest.TestCase): """ Unittests for the XXZZ (CSS) Rotated Surface Code """ def setUp(self): self.params = {"d": 5} self.params[...
0.6508
0.5526
import numpy as np from sklearn.utils import check_random_state from scipy import spatial from ..space import Space, Categorical from .base import InitialPointGenerator def _random_permute_matrix(h, random_state=None): rng = check_random_state(random_state) h_rand_perm = np.zeros_like(h) samples, n = h.sh...
skopt/sampler/lhs.py
import numpy as np from sklearn.utils import check_random_state from scipy import spatial from ..space import Space, Categorical from .base import InitialPointGenerator def _random_permute_matrix(h, random_state=None): rng = check_random_state(random_state) h_rand_perm = np.zeros_like(h) samples, n = h.sh...
0.91607
0.521227
import requests import random import string from plugins.oob import verify_request, gen_oob_domain # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''Apache APISIX apisix/batch-requests Remote Code Execution''', "description": '''A default configuration of Apache API...
2022/CVE-2022-24112/poc/pocsploit/CVE-2022-24112.py
import requests import random import string from plugins.oob import verify_request, gen_oob_domain # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''Apache APISIX apisix/batch-requests Remote Code Execution''', "description": '''A default configuration of Apache API...
0.468791
0.25097
from colorsys import hsv_to_rgb from math import exp, sqrt import random def get_random_colors(n, h_range=(0.0, 1.0), s_range=(0.2, 1.0), v_range=(0.6, 1.0)): """ get random, visually distinct colors, for use in for example qualitative choropleth map. Colors are generated in the HSV space and converted to...
random_map_colors.py
from colorsys import hsv_to_rgb from math import exp, sqrt import random def get_random_colors(n, h_range=(0.0, 1.0), s_range=(0.2, 1.0), v_range=(0.6, 1.0)): """ get random, visually distinct colors, for use in for example qualitative choropleth map. Colors are generated in the HSV space and converted to...
0.90345
0.635844
import numpy import scipy.io.wavfile as wf from pydub import AudioSegment import sys # From https://stackoverflow.com/questions/29547218/ # remove-silence-at-the-beginning-and-at-the-end-of-wave-files-with-pydub def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10): ''' sound is a pydub....
silenceRemoval.py
import numpy import scipy.io.wavfile as wf from pydub import AudioSegment import sys # From https://stackoverflow.com/questions/29547218/ # remove-silence-at-the-beginning-and-at-the-end-of-wave-files-with-pydub def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10): ''' sound is a pydub....
0.313525
0.225683
from web3 import Web3 import time from addresses.bsc_addresses import bsc_token_address_dict, bsc_provider, lp_static_busd_contract_address, lp_static_busd_abi, share_contract_address, charge_abi from swap.swap import * from profile_executor import * from config import * from swap.router_addresses import pancake_router...
charge.py
from web3 import Web3 import time from addresses.bsc_addresses import bsc_token_address_dict, bsc_provider, lp_static_busd_contract_address, lp_static_busd_abi, share_contract_address, charge_abi from swap.swap import * from profile_executor import * from config import * from swap.router_addresses import pancake_router...
0.599954
0.130784
from pathlib import Path from shutil import rmtree from tempfile import mkdtemp import pytest from olivertwist.config.model import Config, RuleConfig, Severity from olivertwist.manifest import Manifest, Node from olivertwist.ruleengine.engine import RuleEngine from olivertwist.ruleengine.result import Result from oli...
tests/ruleengine/test_engine.py
from pathlib import Path from shutil import rmtree from tempfile import mkdtemp import pytest from olivertwist.config.model import Config, RuleConfig, Severity from olivertwist.manifest import Manifest, Node from olivertwist.ruleengine.engine import RuleEngine from olivertwist.ruleengine.result import Result from oli...
0.513912
0.372277
import numpy as np import pandas as pd def y2indicator(Y):#将样本label转换为one-hot格式 N = len(Y)#样本数量 K = len(set(Y))#去重之后,得到样本label类别数量, I = np.zeros([N,K])#生成一个NxK的0矩阵,N为样本量,K为label类别数量 I[np.arange(N), Y] = 1#将每一行中的样本label值对应的列标记为1,从而转换为one-hot形式 return I def get_label_data(x_data,y_data,lab...
data_process.py
import numpy as np import pandas as pd def y2indicator(Y):#将样本label转换为one-hot格式 N = len(Y)#样本数量 K = len(set(Y))#去重之后,得到样本label类别数量, I = np.zeros([N,K])#生成一个NxK的0矩阵,N为样本量,K为label类别数量 I[np.arange(N), Y] = 1#将每一行中的样本label值对应的列标记为1,从而转换为one-hot形式 return I def get_label_data(x_data,y_data,lab...
0.169063
0.48688
# Load libraries. import os, sys, argparse import numpy as np, scipy as sp from scipy.io import savemat from helper_code import ( find_challenge_files, load_header, load_recording, get_leads, six_leads, four_leads, three_leads, two_leads, ) # Parse arguments. def get_parser(): description = 'Extract red...
extract_leads_wfdb.py
# Load libraries. import os, sys, argparse import numpy as np, scipy as sp from scipy.io import savemat from helper_code import ( find_challenge_files, load_header, load_recording, get_leads, six_leads, four_leads, three_leads, two_leads, ) # Parse arguments. def get_parser(): description = 'Extract red...
0.516595
0.147617
from galaxywrap import core from astropy.io import fits import pytest import os from distutils import dir_util from pathlib import Path import numpy as np from astropy.table import Table def get_directory(): return Path(__file__).parent def load_header(): return fits.getheader(get_directory()/'test_core/img...
galaxywrap/tests/test_core.py
from galaxywrap import core from astropy.io import fits import pytest import os from distutils import dir_util from pathlib import Path import numpy as np from astropy.table import Table def get_directory(): return Path(__file__).parent def load_header(): return fits.getheader(get_directory()/'test_core/img...
0.648578
0.652546
import numpy as np import scipy as sp import scipy.optimize import scipy.integrate import scipy.special import matplotlib.pyplot as plt import compute_NTK_spectrum as cNTK import gegenbauer import math def uc_implicit(x, *args): spectrum, p, lamb = args return 1 - np.sum( spectrum / (x * np.ones(len(spectrum))...
approx_learning_curves.py
import numpy as np import scipy as sp import scipy.optimize import scipy.integrate import scipy.special import matplotlib.pyplot as plt import compute_NTK_spectrum as cNTK import gegenbauer import math def uc_implicit(x, *args): spectrum, p, lamb = args return 1 - np.sum( spectrum / (x * np.ones(len(spectrum))...
0.379034
0.453927
import os from typing import Callable, Union import shutil import py import pytest from . import utils from .conftest import FuzzyCallChecker from .git_utils import GitTestEnvironment, GitClient from .perforce_utils import P4TestEnvironment, PerforceWorkspace @pytest.fixture() def p4_submit_environment(perforce_wor...
tests/test_submit.py
import os from typing import Callable, Union import shutil import py import pytest from . import utils from .conftest import FuzzyCallChecker from .git_utils import GitTestEnvironment, GitClient from .perforce_utils import P4TestEnvironment, PerforceWorkspace @pytest.fixture() def p4_submit_environment(perforce_wor...
0.513425
0.347426
import urllib2 import json # Top 16 Teams Make the playoffs # Odds - 31st, 30th, 29th, 28th, 27th, 26th, 25th, 24th, 23rd, 22nd, 21st, 20th, 19th, 18th, 17th odds = [0.185, 0.135, 0.115, 0.095, 0.085, 0.075, 0.065, 0.06, 0.05, 0.035, 0.03, 0.025, 0.02, 0.015, 0.01] class Team(): def __init__(self, name, poi...
nhlPicker.py
import urllib2 import json # Top 16 Teams Make the playoffs # Odds - 31st, 30th, 29th, 28th, 27th, 26th, 25th, 24th, 23rd, 22nd, 21st, 20th, 19th, 18th, 17th odds = [0.185, 0.135, 0.115, 0.095, 0.085, 0.075, 0.065, 0.06, 0.05, 0.035, 0.03, 0.025, 0.02, 0.015, 0.01] class Team(): def __init__(self, name, poi...
0.164987
0.167763
class CmdBuilderBase(object): def __init__(self): self._options = { "-v": "", "-c": "", "-u": "", "-l": "", "-a": "", "-A": "", "-e": "", "-E": "", "-n": "", "-x": "", "-X": ""...
snmp-collector/utils/cmd_builder/__init__.py
class CmdBuilderBase(object): def __init__(self): self._options = { "-v": "", "-c": "", "-u": "", "-l": "", "-a": "", "-A": "", "-e": "", "-E": "", "-n": "", "-x": "", "-X": ""...
0.368406
0.178956
import numpy as np import copy import settings from utility import seq_is_equal, distance_between, angle_is_between, find_angle from neural_network import NNetwork, sigmoid, softmax class Population: """ The environment of bots and food. """ def __init__(self, size, mutation_rate): assert(size...
src/population.py
import numpy as np import copy import settings from utility import seq_is_equal, distance_between, angle_is_between, find_angle from neural_network import NNetwork, sigmoid, softmax class Population: """ The environment of bots and food. """ def __init__(self, size, mutation_rate): assert(size...
0.534855
0.558658
# Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS # OF ANY KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. ...
target_tools/response_helpers.py
# Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS # OF ANY KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. ...
0.731155
0.133246
import os.path as osp import re from glob import glob import pysubs2 from PyPDF2 import PdfFileReader def naruto_order_episodes(x): return float(re.findall("(\d+)", x)[0]) def extract_naruto(): subtitles_dir = './naruto_subtitles' lines = [] for i, file in enumerate(sorted(glob(osp.join(subtitles_d...
anime_extract_subtitles.py
import os.path as osp import re from glob import glob import pysubs2 from PyPDF2 import PdfFileReader def naruto_order_episodes(x): return float(re.findall("(\d+)", x)[0]) def extract_naruto(): subtitles_dir = './naruto_subtitles' lines = [] for i, file in enumerate(sorted(glob(osp.join(subtitles_d...
0.114035
0.169269
from typing import Optional, Iterable, Callable try: # Assume we're a sub-module in a package. from series.abstract_series import AbstractSeries from series import series_classes as sc from utils import numeric as nm except ImportError: # Apparently no higher-level package has been imported, fall back to...
series/simple/any_series.py
from typing import Optional, Iterable, Callable try: # Assume we're a sub-module in a package. from series.abstract_series import AbstractSeries from series import series_classes as sc from utils import numeric as nm except ImportError: # Apparently no higher-level package has been imported, fall back to...
0.880168
0.548674
import random import math import time import binascii import secrets from Crypto.Cipher import AES from Crypto.Hash import SHA from Crypto.Util.Padding import pad, unpad with open("flag.txt", "r") as f: flag = f.read().strip().encode("ascii") with open("key.txt", "r") as f: key = int(f.read().strip()) targ...
BCACTF/2021/crypto/FNES_2/fnes2.py
import random import math import time import binascii import secrets from Crypto.Cipher import AES from Crypto.Hash import SHA from Crypto.Util.Padding import pad, unpad with open("flag.txt", "r") as f: flag = f.read().strip().encode("ascii") with open("key.txt", "r") as f: key = int(f.read().strip()) targ...
0.194406
0.272609
from claims_to_quality.analyzer.calculation.patient_process_measure import PatientProcessMeasure from claims_to_quality.lib.helpers.decorators import override from claims_to_quality.lib.qpp_logging import logging_config logger = logging_config.get_logger(__name__) class MultipleEncounterMeasure(PatientProcessMeasure...
claims_to_quality/analyzer/calculation/multiple_encounter_measure.py
from claims_to_quality.analyzer.calculation.patient_process_measure import PatientProcessMeasure from claims_to_quality.lib.helpers.decorators import override from claims_to_quality.lib.qpp_logging import logging_config logger = logging_config.get_logger(__name__) class MultipleEncounterMeasure(PatientProcessMeasure...
0.846451
0.479199
from __future__ import annotations from TableTypes import TableTypes from Row import Row from prettytable import PrettyTable, MARKDOWN from DbConnection import DbConnection class Table: def __init__(self, name: str, tableType: TableTypes=TableTypes.TABLE, formatAsMarkdown: bool=False): self._name = name ...
src/Table.py
from __future__ import annotations from TableTypes import TableTypes from Row import Row from prettytable import PrettyTable, MARKDOWN from DbConnection import DbConnection class Table: def __init__(self, name: str, tableType: TableTypes=TableTypes.TABLE, formatAsMarkdown: bool=False): self._name = name ...
0.803444
0.271867
import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.colors import LinearSegmentedColormap wrrblues = ['#004174','#5898c9', '#b4cfe4'] colsgrey = ['#333333','#777777','#bbbbbb','#dddddd'] globfigparams={'fontsize':8,'family':'serif','usetex':True,'preamble':'\\usepackage{times}','column...
simulation_scripts/plotting.py
import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.colors import LinearSegmentedColormap wrrblues = ['#004174','#5898c9', '#b4cfe4'] colsgrey = ['#333333','#777777','#bbbbbb','#dddddd'] globfigparams={'fontsize':8,'family':'serif','usetex':True,'preamble':'\\usepackage{times}','column...
0.325521
0.470554
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Flatten from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout from keras.layer...
Kode/LSTMS.py
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Flatten from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout from keras.layer...
0.631026
0.53358
import random from collections import defaultdict from threading import Lock import numpy as np from supervisely_lib import logger from supervisely_lib.annotation.annotation import Annotation from supervisely_lib.imaging import image as sly_image def samples_by_tags(required_tags, project): """ Split sample...
superviselySDK/supervisely_lib/nn/dataset.py
import random from collections import defaultdict from threading import Lock import numpy as np from supervisely_lib import logger from supervisely_lib.annotation.annotation import Annotation from supervisely_lib.imaging import image as sly_image def samples_by_tags(required_tags, project): """ Split sample...
0.513425
0.174833
from django.core.management import BaseCommand from django.db.transaction import atomic from calculator.models import ( Scheme, FeeType, Price, Unit ) class Command(BaseCommand): help = ''' Create new fee type prices based on an existing feetype's. Provide the ID of the source fee type as wel...
fee_calculator/apps/calculator/management/commands/copyfeetype.py
from django.core.management import BaseCommand from django.db.transaction import atomic from calculator.models import ( Scheme, FeeType, Price, Unit ) class Command(BaseCommand): help = ''' Create new fee type prices based on an existing feetype's. Provide the ID of the source fee type as wel...
0.578091
0.142143
from enum import Enum, IntEnum class ToioIDType(Enum): INVALID = 0 POSITION = 1 STANDARD = 2 MISSED = 3 class ToioID: def __init__(self, type: ToioIDType): self.type = type def isPosition(self): return self.type == ToioIDType.POSITION def isStandard(self): retur...
tomotoio/data.py
from enum import Enum, IntEnum class ToioIDType(Enum): INVALID = 0 POSITION = 1 STANDARD = 2 MISSED = 3 class ToioID: def __init__(self, type: ToioIDType): self.type = type def isPosition(self): return self.type == ToioIDType.POSITION def isStandard(self): retur...
0.829457
0.496765
from xml.etree import ElementTree as ET # Import PyHouse files from Modules.Utilities.xml_tools import PutGetXML from Modules.Core.data_objects import DeviceData from Modules.Computer import logging_pyh as Logger LOG = Logger.getLogger('PyHouse.DeviceTools ') class XML(object): @staticmethod ...
src/Modules/Utilities/device_tools.py
from xml.etree import ElementTree as ET # Import PyHouse files from Modules.Utilities.xml_tools import PutGetXML from Modules.Core.data_objects import DeviceData from Modules.Computer import logging_pyh as Logger LOG = Logger.getLogger('PyHouse.DeviceTools ') class XML(object): @staticmethod ...
0.376967
0.073997
import os import glob import numpy as np import skimage.io as skio import imageio import utils import metrics from core.experiments import Experiment class SaveGauganCompatibleLayoutsFromGraphBasedMaskGenerator(Experiment): name = "collect-gaugan-results" requires_model = True @classmethod def spec...
experiments/collect_results_from_gaugan.py
import os import glob import numpy as np import skimage.io as skio import imageio import utils import metrics from core.experiments import Experiment class SaveGauganCompatibleLayoutsFromGraphBasedMaskGenerator(Experiment): name = "collect-gaugan-results" requires_model = True @classmethod def spec...
0.360489
0.153232
import tkinter as tk import tkutil from viewable import Viewable, CustomView from tkutil import merge_megaconfig # parts BODY = "body" LABEL_HEADER = "label_header" LABEL_MESSAGE = "label_message" class Toast(tk.Toplevel): """ A toast is a dialog box with or without decoration that is displayed for a gi...
megawidget/toast/__init__.py
import tkinter as tk import tkutil from viewable import Viewable, CustomView from tkutil import merge_megaconfig # parts BODY = "body" LABEL_HEADER = "label_header" LABEL_MESSAGE = "label_message" class Toast(tk.Toplevel): """ A toast is a dialog box with or without decoration that is displayed for a gi...
0.77535
0.2084
import logging import PIL import os from PIL import Image # This class allows you to resize and mirror an image of the dataset according to specific rules class ImageResizer: def __init__(self, image_width, quality, source_folder, destination_folder, file_name, keep_aspect_ratio): self.logger = logging.g...
odir_image_resizer.py
import logging import PIL import os from PIL import Image # This class allows you to resize and mirror an image of the dataset according to specific rules class ImageResizer: def __init__(self, image_width, quality, source_folder, destination_folder, file_name, keep_aspect_ratio): self.logger = logging.g...
0.683208
0.234615
from sqlalchemy import engine, schema from sqlalchemy.sql import util as sql_util class DDLBase(schema.SchemaVisitor): def __init__(self, connection): self.connection = connection class SchemaGenerator(DDLBase): def __init__(self, dialect, connection, checkfirst=False, tables=None, **kwargs): ...
Lib/site-packages/sqlalchemy/engine/ddl.py
from sqlalchemy import engine, schema from sqlalchemy.sql import util as sql_util class DDLBase(schema.SchemaVisitor): def __init__(self, connection): self.connection = connection class SchemaGenerator(DDLBase): def __init__(self, dialect, connection, checkfirst=False, tables=None, **kwargs): ...
0.580709
0.256774
from collections import deque import gym from keras.models import Sequential from keras.layers import Convolution2D, Dense, Activation import numpy as np import random import tensorflow as tf # I worked through this tutorial https://keon.io/deep-q-learning/ # That tutorial is not asynchronous, though # This code clos...
src/deep_qlearning.py
from collections import deque import gym from keras.models import Sequential from keras.layers import Convolution2D, Dense, Activation import numpy as np import random import tensorflow as tf # I worked through this tutorial https://keon.io/deep-q-learning/ # That tutorial is not asynchronous, though # This code clos...
0.842199
0.370055
from __future__ import unicode_literals # libs from rest_framework import exceptions, status from rest_framework.views import exception_handler class RequiredException(Exception): pass class MaxLengthExceededException(Exception): pass class UniquenessException(Exception): pass class InvalidTypeExce...
utils/exceptions.py
from __future__ import unicode_literals # libs from rest_framework import exceptions, status from rest_framework.views import exception_handler class RequiredException(Exception): pass class MaxLengthExceededException(Exception): pass class UniquenessException(Exception): pass class InvalidTypeExce...
0.687525
0.061255
from __future__ import division from __future__ import print_function from keras.callbacks import ReduceLROnPlateau, ModelCheckpoint """ @author : Hyunwoong @when : 2019-11-27 @homepage : https://github.com/gusdnd852 """ from keras.optimizers import SGD from keras.preprocessing.image import ImageDataGene...
nn/train.py
from __future__ import division from __future__ import print_function from keras.callbacks import ReduceLROnPlateau, ModelCheckpoint """ @author : Hyunwoong @when : 2019-11-27 @homepage : https://github.com/gusdnd852 """ from keras.optimizers import SGD from keras.preprocessing.image import ImageDataGene...
0.547101
0.092401
import random import django import os import argparse os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") django.setup() from datacenter.models import Schoolkid, Mark, Chastisement, Subject, Lesson, Commendation from django.core.exceptions import ObjectDoesNotExist def fix_marks(schoolkid): chil...
secondary_functions.py
import random import django import os import argparse os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") django.setup() from datacenter.models import Schoolkid, Mark, Chastisement, Subject, Lesson, Commendation from django.core.exceptions import ObjectDoesNotExist def fix_marks(schoolkid): chil...
0.194024
0.177668
limite_sup = 10 def listarQuestoes(conexao):# {{{ q1(conexao) q2(conexao) q3(conexao) q4(conexao) q5(conexao) q6a(conexao) q6b(conexao) q7(conexao) q8(conexao) # q9(conexao)# }}} def q1(conexao):# {{{ print(">> Questão 1:") sql_entry = """ select * ...
reports.py
limite_sup = 10 def listarQuestoes(conexao):# {{{ q1(conexao) q2(conexao) q3(conexao) q4(conexao) q5(conexao) q6a(conexao) q6b(conexao) q7(conexao) q8(conexao) # q9(conexao)# }}} def q1(conexao):# {{{ print(">> Questão 1:") sql_entry = """ select * ...
0.161783
0.192615
from logging import ERROR, INFO from ganjoor import Ganjoor from uuid import uuid4 from telegram.ext import Dispatcher, CallbackContext, InlineQueryHandler from telegram import (Update, InlineQueryResultArticle, InputTextMessageContent) from telegram.inline.inlinekeyboardbutton import InlineKeyboa...
bot/ganjoor/search_poet_poems.py
from logging import ERROR, INFO from ganjoor import Ganjoor from uuid import uuid4 from telegram.ext import Dispatcher, CallbackContext, InlineQueryHandler from telegram import (Update, InlineQueryResultArticle, InputTextMessageContent) from telegram.inline.inlinekeyboardbutton import InlineKeyboa...
0.425367
0.076788
import argparse import numpy as np import torch import wandb from gym_carla.envs.carla_pid_env import CarlaPidEnv from torch.utils.data import DataLoader from train_bc import BCTrainer from models.carlaAffordancesDataset import AffordancesDataset, HLCAffordanceDataset from agent import BCStochasticAgent, MultiTaskAg...
bc/test_bc.py
import argparse import numpy as np import torch import wandb from gym_carla.envs.carla_pid_env import CarlaPidEnv from torch.utils.data import DataLoader from train_bc import BCTrainer from models.carlaAffordancesDataset import AffordancesDataset, HLCAffordanceDataset from agent import BCStochasticAgent, MultiTaskAg...
0.627152
0.153137
import action import constants import colors from counter import Counter import dungeoncreatorvisualizer from equipment import EquipmentSlots import gametime import geometry as geo import graphic import gui import menu import rectfactory import sacrifice import save import settings import state import style import icon...
menufactory.py
import action import constants import colors from counter import Counter import dungeoncreatorvisualizer from equipment import EquipmentSlots import gametime import geometry as geo import graphic import gui import menu import rectfactory import sacrifice import save import settings import state import style import icon...
0.273671
0.12817
import argparse import configparser import json import logging import time import coloredlogs from flask import Flask, request import telegram from telegram.error import NetworkError, Unauthorized coloredlogs.install(level='DEBUG') parser = argparse.ArgumentParser(description='TravisCI notifier for Telegram') parser...
travisci_notification_telegram.py
import argparse import configparser import json import logging import time import coloredlogs from flask import Flask, request import telegram from telegram.error import NetworkError, Unauthorized coloredlogs.install(level='DEBUG') parser = argparse.ArgumentParser(description='TravisCI notifier for Telegram') parser...
0.225161
0.047272
from otri.filtering.filters.merge_filter import SequentialMergeFilter, Stream import unittest class SequentialMergeFilterTest(unittest.TestCase): def setUp(self): self.inputs = [Stream([1,2,3,4],is_closed=True), Stream([4,5,6,7], is_closed=True)] self.outputs = [Stream()] self.f = Sequenti...
test/filtering/filters/merge_filter_test.py
from otri.filtering.filters.merge_filter import SequentialMergeFilter, Stream import unittest class SequentialMergeFilterTest(unittest.TestCase): def setUp(self): self.inputs = [Stream([1,2,3,4],is_closed=True), Stream([4,5,6,7], is_closed=True)] self.outputs = [Stream()] self.f = Sequenti...
0.600188
0.508056
__author__ = 'Sliver' import os from tkinter import * import tkinter.messagebox as mbox from rsa import RSA from makeRsaKeys import makeKeyFiles, delKeyFiles, Key class Cipher(Frame): def __init__(self, master): frame = Frame(master) frame.pack() self.var1 = Variable() self.var2 ...
main.py
__author__ = 'Sliver' import os from tkinter import * import tkinter.messagebox as mbox from rsa import RSA from makeRsaKeys import makeKeyFiles, delKeyFiles, Key class Cipher(Frame): def __init__(self, master): frame = Frame(master) frame.pack() self.var1 = Variable() self.var2 ...
0.215805
0.099689
import numpy as np def grams(sentence, n): """ creates groups of n-grams :param sentence: list containing the model proposed sentence :param n: size of the n-gram to use for evaluation :return: new """ new = [] ln = len(sentence) for i, word in enumerate(sentence): s = word...
supervised_learning/0x10-nlp_metrics/2-cumulative_bleu.py
import numpy as np def grams(sentence, n): """ creates groups of n-grams :param sentence: list containing the model proposed sentence :param n: size of the n-gram to use for evaluation :return: new """ new = [] ln = len(sentence) for i, word in enumerate(sentence): s = word...
0.670177
0.633269
import sys print(sys.version) import numpy as np import argparse sys.path.append('../') from alchemistry_toolkit.utils import * from alchemistry_toolkit.estimators.free_energy_estimator import FreeEnergy_HILLS def initialize(): """ An argument parser as an initializing function. """ parser = argparse....
alchemistry_toolkit/analysis/PLUMED_outputs_analysis.py
import sys print(sys.version) import numpy as np import argparse sys.path.append('../') from alchemistry_toolkit.utils import * from alchemistry_toolkit.estimators.free_energy_estimator import FreeEnergy_HILLS def initialize(): """ An argument parser as an initializing function. """ parser = argparse....
0.322526
0.230405
import torch import torch.nn as nn import math class MAUCell(nn.Module): def __init__(self, in_channel, num_hidden, height, width, filter_size, stride, tau, cell_mode): super(MAUCell, self).__init__() self.num_hidden = num_hidden self.padding = (filter_size[0] // 2, filter_size[1] // 2) ...
core/layers/MAUCell.py
import torch import torch.nn as nn import math class MAUCell(nn.Module): def __init__(self, in_channel, num_hidden, height, width, filter_size, stride, tau, cell_mode): super(MAUCell, self).__init__() self.num_hidden = num_hidden self.padding = (filter_size[0] // 2, filter_size[1] // 2) ...
0.920478
0.49048
from copy import copy Sbox = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0...
Img_Steganography/AES.py
from copy import copy Sbox = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0...
0.055477
0.531635
import click from typing import ( Any, ) from eth2deposit.exceptions import ValidationError from eth2deposit.key_handling.key_derivation.mnemonic import ( verify_mnemonic, ) from eth2deposit.utils.constants import ( WORD_LISTS_PATH, ) from .generate_keys import ( generate_keys, generate_keys_argume...
eth2deposit/cli/existing_mnemonic.py
import click from typing import ( Any, ) from eth2deposit.exceptions import ValidationError from eth2deposit.key_handling.key_derivation.mnemonic import ( verify_mnemonic, ) from eth2deposit.utils.constants import ( WORD_LISTS_PATH, ) from .generate_keys import ( generate_keys, generate_keys_argume...
0.434941
0.305386
import os from azure.cli.testsdk import ScenarioTest from .. import try_manual, raise_if from azure.cli.testsdk import ResourceGroupPreparer TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) @try_manual def setup(test, rg): test.kwargs.update({ 'cluster_name': test.create_random...
src/stack-hci/azext_stack_hci/tests/latest/test_azure_stack_hci_scenario.py
import os from azure.cli.testsdk import ScenarioTest from .. import try_manual, raise_if from azure.cli.testsdk import ResourceGroupPreparer TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) @try_manual def setup(test, rg): test.kwargs.update({ 'cluster_name': test.create_random...
0.341583
0.127653
from random import randrange import pytest from multiprocessing.pool import ThreadPool from tensora import Tensor, tensor_method, evaluate def test_csr_matrix_vector_product(): A = Tensor.from_aos( [[1, 0], [0, 1], [1, 2]], [2.0, -2.0, 4.0], dimensions=(2, 3), format='ds' ) x = T...
tests/test_function.py
from random import randrange import pytest from multiprocessing.pool import ThreadPool from tensora import Tensor, tensor_method, evaluate def test_csr_matrix_vector_product(): A = Tensor.from_aos( [[1, 0], [0, 1], [1, 2]], [2.0, -2.0, 4.0], dimensions=(2, 3), format='ds' ) x = T...
0.651577
0.845624
from .resource_base import ResourceBase class Request(ResourceBase): """Request. :param created_by: The ID of user who created this item. Optional. :type created_by: str :param created_date: The date time when this item is created. Optional. :type created_date: datetime :param id:...
venv/lib/python3.8/site-packages/vsts/symbol/v4_1/models/request.py
from .resource_base import ResourceBase class Request(ResourceBase): """Request. :param created_by: The ID of user who created this item. Optional. :type created_by: str :param created_date: The date time when this item is created. Optional. :type created_date: datetime :param id:...
0.848925
0.160957
import json from django.db.models import Count, F from collections import defaultdict from rest_framework import serializers from bims.models.location_site import LocationSite from bims.models.biological_collection_record import BiologicalCollectionRecord from bims.models.iucn_status import IUCNStatus from bims.seriali...
bims/serializers/location_site_detail_serializer.py
import json from django.db.models import Count, F from collections import defaultdict from rest_framework import serializers from bims.models.location_site import LocationSite from bims.models.biological_collection_record import BiologicalCollectionRecord from bims.models.iucn_status import IUCNStatus from bims.seriali...
0.303525
0.250282
from __future__ import division import ast from operator import itemgetter from django.db import transaction from django.db.models import Q from django.utils import timezone from rest_framework import serializers from rest_framework.exceptions import ValidationError from crowdsourcing import models from crowdsourcin...
crowdsourcing/serializers/task.py
from __future__ import division import ast from operator import itemgetter from django.db import transaction from django.db.models import Q from django.utils import timezone from rest_framework import serializers from rest_framework.exceptions import ValidationError from crowdsourcing import models from crowdsourcin...
0.566978
0.072966
from rpython.rlib.rstring import StringBuilder from hippy.builtin import wrap, Optional from hippy.objects.base import W_Root from hippy.error import InvalidCallback FLUSH = 4 class Buffer(object): def __init__(self, space, callback, chunk_size, prev): self.space = space self.callback = callback ...
hippy/buffering.py
from rpython.rlib.rstring import StringBuilder from hippy.builtin import wrap, Optional from hippy.objects.base import W_Root from hippy.error import InvalidCallback FLUSH = 4 class Buffer(object): def __init__(self, space, callback, chunk_size, prev): self.space = space self.callback = callback ...
0.589126
0.110279
# OS-9/68000 Executable File Loader for IDA 6.9 (old!) import struct import idaapi FORMAT_EXE = 'OS-9/68000 Executable' # TODO: what li.read returns/throws on short-read or EOF? (assuming partial str on short-read, None on EOF) def read(li, bytes): d = li.read(bytes) if d is None or len(d) < bytes: raise EOFErr...
os9x.py
# OS-9/68000 Executable File Loader for IDA 6.9 (old!) import struct import idaapi FORMAT_EXE = 'OS-9/68000 Executable' # TODO: what li.read returns/throws on short-read or EOF? (assuming partial str on short-read, None on EOF) def read(li, bytes): d = li.read(bytes) if d is None or len(d) < bytes: raise EOFErr...
0.200871
0.196075
import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from torchvision.utils import save_image import im2mesh.common as common try: import open3d as o3d except: print("Warning: failed to import open3d, some function may not be used. ") def visualize_data(data, data_ty...
im2mesh/utils/visualize.py
import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from torchvision.utils import save_image import im2mesh.common as common try: import open3d as o3d except: print("Warning: failed to import open3d, some function may not be used. ") def visualize_data(data, data_ty...
0.696887
0.644533
"""Unit tests for arghelper.py. """ import argparse import os import unittest import arghelper class TestExtantItem(unittest.TestCase): def setUp(self): # NOQA self.existing_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'existing_dir') self.non_existin...
tests/test_arghelper.py
"""Unit tests for arghelper.py. """ import argparse import os import unittest import arghelper class TestExtantItem(unittest.TestCase): def setUp(self): # NOQA self.existing_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'existing_dir') self.non_existin...
0.496094
0.323113
from twisted.internet.defer import Deferred, inlineCallbacks, returnValue from twisted.logger import Logger from autobahn.twisted.wamp import ApplicationSession from autobahn.wamp.types import SubscribeOptions, PublishOptions, RegisterOptions import time import datetime class Sessioner(ApplicationSession): logge...
backend/sessioner.py
from twisted.internet.defer import Deferred, inlineCallbacks, returnValue from twisted.logger import Logger from autobahn.twisted.wamp import ApplicationSession from autobahn.wamp.types import SubscribeOptions, PublishOptions, RegisterOptions import time import datetime class Sessioner(ApplicationSession): logge...
0.325413
0.087213
import random import string from datetime import datetime from bolinette import blnt, web from bolinette.decorators import controller, get, post, patch, delete from bolinette.defaults.services import UserService, RoleService from bolinette.exceptions import ForbiddenError @controller('user', '/user') class UserContr...
bolinette/defaults/controllers/user.py
import random import string from datetime import datetime from bolinette import blnt, web from bolinette.decorators import controller, get, post, patch, delete from bolinette.defaults.services import UserService, RoleService from bolinette.exceptions import ForbiddenError @controller('user', '/user') class UserContr...
0.577853
0.066206
from django.shortcuts import render, redirect, HttpResponseRedirect from .forms import StudentRegistration from .models import User from django.contrib.auth.decorators import login_required # Create your views here. @login_required def add_show(request): if request.method == 'POST': river = '' ob =...
enroll/views.py
from django.shortcuts import render, redirect, HttpResponseRedirect from .forms import StudentRegistration from .models import User from django.contrib.auth.decorators import login_required # Create your views here. @login_required def add_show(request): if request.method == 'POST': river = '' ob =...
0.303732
0.106598
from typing import Dict from unittest.mock import MagicMock from requests import Session from fastapi_metabot.module import Module def test_commands_route( module: Module, test_client: Session, mock_background_tasks: MagicMock, test_command_metadata: Dict, ) -> None: name = 'test...
fastapi-metabot/tests/test_routes.py
from typing import Dict from unittest.mock import MagicMock from requests import Session from fastapi_metabot.module import Module def test_commands_route( module: Module, test_client: Session, mock_background_tasks: MagicMock, test_command_metadata: Dict, ) -> None: name = 'test...
0.738292
0.448245
from dash.development.base_component import Component, _explicitize_args class Stepper(Component): """A Stepper component. Material UI Stepper component Keyword arguments: - activeStep (number; default 0): Set the active step (zero based index). This will enable Step control helpers - alternativeLabel (boolean;...
sd_material_ui/Stepper.py
from dash.development.base_component import Component, _explicitize_args class Stepper(Component): """A Stepper component. Material UI Stepper component Keyword arguments: - activeStep (number; default 0): Set the active step (zero based index). This will enable Step control helpers - alternativeLabel (boolean;...
0.828835
0.31025
import sys sys.path.append('..') from display import Display from PyQt5.QtWidgets import (QApplication, QWidget, QHBoxLayout, QVBoxLayout, QPushButton) class DisplayExample(QWidget): """Application to demonstrate the Morse Trainer 'display' widget.""" def __init__(self): ...
tests/test_display.py
import sys sys.path.append('..') from display import Display from PyQt5.QtWidgets import (QApplication, QWidget, QHBoxLayout, QVBoxLayout, QPushButton) class DisplayExample(QWidget): """Application to demonstrate the Morse Trainer 'display' widget.""" def __init__(self): ...
0.291989
0.097648
from six.moves.urllib.parse import urljoin from werkzeug.datastructures import EnvironHeaders, ImmutableMultiDict from openapi_core.contrib.flask import FlaskOpenAPIRequest from openapi_core.validation.request.datatypes import RequestParameters class TestFlaskOpenAPIRequest(object): def test_simple(self, reques...
tests/integration/contrib/flask/test_flask_requests.py
from six.moves.urllib.parse import urljoin from werkzeug.datastructures import EnvironHeaders, ImmutableMultiDict from openapi_core.contrib.flask import FlaskOpenAPIRequest from openapi_core.validation.request.datatypes import RequestParameters class TestFlaskOpenAPIRequest(object): def test_simple(self, reques...
0.488283
0.271259
import asyncio import pendulum import pytest from prefect_server import api, config, utilities from prefect_server.database import models from prefect_server.utilities.exceptions import Unauthorized async def test_create_logs(flow_run_id): where_clause = { "flow_run_id": {"_eq": flow_run_id}, } ...
server/tests/api/test_logs.py
import asyncio import pendulum import pytest from prefect_server import api, config, utilities from prefect_server.database import models from prefect_server.utilities.exceptions import Unauthorized async def test_create_logs(flow_run_id): where_clause = { "flow_run_id": {"_eq": flow_run_id}, } ...
0.528533
0.42913
from interactions.constraints import ANYWHERE, Constraint from postures.base_postures import MobilePosture from postures.posture_graph import get_mobile_posture_constraint from sims4.tuning.tunable import HasTunableFactory, AutoFactoryInit, OptionalTunable, TunableRange, Tunable, TunedInterval from world.ocean_tuning i...
Scripts/simulation/routing/waypoints/waypoint_generator.py
from interactions.constraints import ANYWHERE, Constraint from postures.base_postures import MobilePosture from postures.posture_graph import get_mobile_posture_constraint from sims4.tuning.tunable import HasTunableFactory, AutoFactoryInit, OptionalTunable, TunableRange, Tunable, TunedInterval from world.ocean_tuning i...
0.864325
0.28061
from evoplotter import plotter from evoplotter.dims import * # Data props = [ {"dimX": "A", "dimY": "C", "trainSet": "9,9,7,6,6,3,3,2,2,1", "validSet": "10,10,7,6,6,3,6,6,7,9"}, {"dimX": "A", "dimY": "C", "trainSet": "8,8,7,5,5,3,3,2,2,1", "validSet": "9,9,7,6,6,3,5,5,7,8"}, {"dimX": "A", "dimY": "C", "tr...
examples/plot_progression_grid.py
from evoplotter import plotter from evoplotter.dims import * # Data props = [ {"dimX": "A", "dimY": "C", "trainSet": "9,9,7,6,6,3,3,2,2,1", "validSet": "10,10,7,6,6,3,6,6,7,9"}, {"dimX": "A", "dimY": "C", "trainSet": "8,8,7,5,5,3,3,2,2,1", "validSet": "9,9,7,6,6,3,5,5,7,8"}, {"dimX": "A", "dimY": "C", "tr...
0.526099
0.407628
import json import warnings import kulado import kulado.runtime from .. import utilities, tables class OutputBlob(kulado.CustomResource): date_format: kulado.Output[str] """ The date format. Wherever `{date}` appears in `path_pattern`, the value of this property is used as the date format instead. """...
sdk/python/kulado_azure/streamanalytics/output_blob.py
import json import warnings import kulado import kulado.runtime from .. import utilities, tables class OutputBlob(kulado.CustomResource): date_format: kulado.Output[str] """ The date format. Wherever `{date}` appears in `path_pattern`, the value of this property is used as the date format instead. """...
0.743354
0.331079
import json from uuid import UUID, uuid4 from typing import List, Union from msrest.serialization import Model from botframework.streaming.payloads import ResponseMessageStream from botframework.streaming.payloads.models import Serializable class StreamingRequest: GET = "GET" POST = "POST" PUT = "PUT" ...
libraries/botframework-streaming/botframework/streaming/streaming_request.py
import json from uuid import UUID, uuid4 from typing import List, Union from msrest.serialization import Model from botframework.streaming.payloads import ResponseMessageStream from botframework.streaming.payloads.models import Serializable class StreamingRequest: GET = "GET" POST = "POST" PUT = "PUT" ...
0.619356
0.081228
import numpy as np import pandas as pd from sklearn.base import BaseEstimator from sklearn.utils.validation import ( check_X_y, check_array, check_is_fitted, check_random_state, ) from bpr_numba import fit_bpr from utils import ( create_user_map_table, create_item_map_table, create_user_map...
src/bayesian_personalized_ranking/bpr_sklearn.py
import numpy as np import pandas as pd from sklearn.base import BaseEstimator from sklearn.utils.validation import ( check_X_y, check_array, check_is_fitted, check_random_state, ) from bpr_numba import fit_bpr from utils import ( create_user_map_table, create_item_map_table, create_user_map...
0.795975
0.270381