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 re import sys import logging import logging.handlers from pygments.lexer import RegexLexer, include from pygments.token import (Punctuation, Text, Comment, Keyword, Name, String, Generic, Operator, Number, Whitespace, Literal, Error, Token) from pygments import highlight from pygments.formatters impor...
peri/logger_colors.py
import re import sys import logging import logging.handlers from pygments.lexer import RegexLexer, include from pygments.token import (Punctuation, Text, Comment, Keyword, Name, String, Generic, Operator, Number, Whitespace, Literal, Error, Token) from pygments import highlight from pygments.formatters impor...
0.260201
0.140307
import pyDOE as doe import numpy as np import os from itertools import repeat from scipy import stats import matplotlib.pyplot as plt from matplotlib import rcParams import ParetoFrontND as pf import StandardTestFunctions as fn import GPyOpt plt.style.use('ggplot') rcParams['font.sans-serif'] = "Segoe UI" rcParams['fo...
standard-test-functions/figure_4.py
import pyDOE as doe import numpy as np import os from itertools import repeat from scipy import stats import matplotlib.pyplot as plt from matplotlib import rcParams import ParetoFrontND as pf import StandardTestFunctions as fn import GPyOpt plt.style.use('ggplot') rcParams['font.sans-serif'] = "Segoe UI" rcParams['fo...
0.455683
0.606178
from powrl3.util.fileio import * import numpy as np from collections import deque import random import pickle import os class EligibilityTraces(object): def __init__(self, actions, n_dim): self.actions = actions n = len(actions) self.n_dim = n_dim self.traces = np.zeros((n, n_dim...
powrl3/agent/a2c/util.py
from powrl3.util.fileio import * import numpy as np from collections import deque import random import pickle import os class EligibilityTraces(object): def __init__(self, actions, n_dim): self.actions = actions n = len(actions) self.n_dim = n_dim self.traces = np.zeros((n, n_dim...
0.474388
0.206134
from copy import deepcopy from scan.test.fetch.kube_fetch.test_data.kube_access import BASE_RESPONSE VSERVICES_FOLDER_DOC = { "_id": "5aaf8369c6ad1791934c9a15", "environment": "kube-aci", "id": "b5fee42e-1b31-11e8-9d88-00505699cf9e-vservices", "type": "vservices_folder", "parent_type": "namespace"...
scan/test/fetch/kube_fetch/test_data/kube_fetch_vservices.py
from copy import deepcopy from scan.test.fetch.kube_fetch.test_data.kube_access import BASE_RESPONSE VSERVICES_FOLDER_DOC = { "_id": "5aaf8369c6ad1791934c9a15", "environment": "kube-aci", "id": "b5fee42e-1b31-11e8-9d88-00505699cf9e-vservices", "type": "vservices_folder", "parent_type": "namespace"...
0.385028
0.289409
import numpy as np import torch import os, time, sys from os.path import join as pjoin from PIL import Image import argparse from torch.utils.data import DataLoader from torchvision.transforms import ToPILImage import models from utils import convert_state_dict, Logger from dataset.dataset import VOC12 def main(args...
test.py
import numpy as np import torch import os, time, sys from os.path import join as pjoin from PIL import Image import argparse from torch.utils.data import DataLoader from torchvision.transforms import ToPILImage import models from utils import convert_state_dict, Logger from dataset.dataset import VOC12 def main(args...
0.412648
0.235152
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
actions/delete_l2_port_channel.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
0.739046
0.21099
import json from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.views.generic import FormView, ListView, UpdateView from djofx import models from djofx.forms import CategoriseTransactionForm, CategoryForm from djofx.utils import qs_to_monthly_report from djofx.views.base ...
djofx/views/category.py
import json from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.views.generic import FormView, ListView, UpdateView from djofx import models from djofx.forms import CategoriseTransactionForm, CategoryForm from djofx.utils import qs_to_monthly_report from djofx.views.base ...
0.478041
0.129155
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import interpolate import time start_time = time.time() data_matrix = np.array(pd.read_csv('SUSY.csv')) X = data_matrix[:,1:] Y = data_matrix[:,0] Y[Y==0.0] = -1.0 nrows, ncols = X.shape[0], X.shape[1] training_percent = 70 print "\...
main.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import interpolate import time start_time = time.time() data_matrix = np.array(pd.read_csv('SUSY.csv')) X = data_matrix[:,1:] Y = data_matrix[:,0] Y[Y==0.0] = -1.0 nrows, ncols = X.shape[0], X.shape[1] training_percent = 70 print "\...
0.303938
0.416797
from typing import Iterable, Tuple, Optional import torch import numpy as np from tqdm import tqdm import sys sys.path.append('..') from ltss.utils import read_records_csv, reshape_vector, flatten_vector from ltss.vectorise import vectorise_record class DataHandler(object): """ Contains logic for loading d...
training/loader.py
from typing import Iterable, Tuple, Optional import torch import numpy as np from tqdm import tqdm import sys sys.path.append('..') from ltss.utils import read_records_csv, reshape_vector, flatten_vector from ltss.vectorise import vectorise_record class DataHandler(object): """ Contains logic for loading d...
0.864282
0.606498
from posixpath import expanduser from typing import Dict from lpulive.lpulive_urls import (GET_CAHAT_MEMBERS_URL, GET_CONVRSATION_URL, GET_MESSAGES_THREADS_URL, GET_MESSAGES_URL, GET_WORKSPACE_DETAIL_URL, LOGIN_URL, LOGIN_VIA_TOKEN_URL, SEARCH_URL, ...
lpulive/lpulive_main.py
from posixpath import expanduser from typing import Dict from lpulive.lpulive_urls import (GET_CAHAT_MEMBERS_URL, GET_CONVRSATION_URL, GET_MESSAGES_THREADS_URL, GET_MESSAGES_URL, GET_WORKSPACE_DETAIL_URL, LOGIN_URL, LOGIN_VIA_TOKEN_URL, SEARCH_URL, ...
0.437583
0.052328
import os, sys, datetime, re, cPickle, gzip, time, csv, glob from cartography.geometry import Geometry, Point, LinearRing, Polygon from cartography.proj.srs import SpatialReference from jpltime import adoytoaymd GRANULE_RE = re.compile(r'^(M(?:Y|O)D).*?\.(A\d{7}\.\d{4})') CSV_LINE = "%s,%f,%f,%f,%f,%s,%s" dataDirs ...
scripts/dumpCSV_MODIS.py
import os, sys, datetime, re, cPickle, gzip, time, csv, glob from cartography.geometry import Geometry, Point, LinearRing, Polygon from cartography.proj.srs import SpatialReference from jpltime import adoytoaymd GRANULE_RE = re.compile(r'^(M(?:Y|O)D).*?\.(A\d{7}\.\d{4})') CSV_LINE = "%s,%f,%f,%f,%f,%s,%s" dataDirs ...
0.306527
0.232354
import pyyjj import json from contextlib import contextmanager from sqlalchemy import inspect, types, TypeDecorator import kungfu.wingchun.constants as wc_constants def make_url(location, filename): db_file = location.locator.layout_file(location, pyyjj.layout.SQLITE, filename) return 'sqlite:///{}'.format(db_...
core/python/kungfu/data/sqlite/__init__.py
import pyyjj import json from contextlib import contextmanager from sqlalchemy import inspect, types, TypeDecorator import kungfu.wingchun.constants as wc_constants def make_url(location, filename): db_file = location.locator.layout_file(location, pyyjj.layout.SQLITE, filename) return 'sqlite:///{}'.format(db_...
0.706393
0.239283
from tkinter import * from tkinter import ttk, messagebox from sqlite3 import Error, connect import os def agenda(): """ #### Estabelece a conexão com o banco de dados Agenda.db """ dirdb = os.path.dirname(__file__) nomedb = dirdb + '/Agenda.db' con = connect(nomedb) return con def l...
projetos/Agenda/libagenda.py
from tkinter import * from tkinter import ttk, messagebox from sqlite3 import Error, connect import os def agenda(): """ #### Estabelece a conexão com o banco de dados Agenda.db """ dirdb = os.path.dirname(__file__) nomedb = dirdb + '/Agenda.db' con = connect(nomedb) return con def l...
0.485844
0.192444
# reference about how f2py and cython modules coexists: # https://stackoverflow.com/questions/7932028/setup-py-for-packages-that-depend-on-both-cython-and-f2py from setuptools import setup import numpy as np try: from Cython.Build import cythonize dynprog_ext_modules = cythonize(['graphflow/pagerank/cpageran...
setup.py
# reference about how f2py and cython modules coexists: # https://stackoverflow.com/questions/7932028/setup-py-for-packages-that-depend-on-both-cython-and-f2py from setuptools import setup import numpy as np try: from Cython.Build import cythonize dynprog_ext_modules = cythonize(['graphflow/pagerank/cpageran...
0.732018
0.37734
from selenium import webdriver import threading import queue import time import requests import json import pymongo song_hash_queue = queue.Queue() ROOT_URL = 'http://www.kugou.com/yy/special/index/1-3-0.html' PLAY_URL = 'http://www.kugou.com/yy/index.php?r=play/getdata&hash=' #1FF3CB3D374E44AAC3AC98BE047748E3 SHOW_BR...
python_demo_v1/spider/spider_kugou_song.py
from selenium import webdriver import threading import queue import time import requests import json import pymongo song_hash_queue = queue.Queue() ROOT_URL = 'http://www.kugou.com/yy/special/index/1-3-0.html' PLAY_URL = 'http://www.kugou.com/yy/index.php?r=play/getdata&hash=' #1FF3CB3D374E44AAC3AC98BE047748E3 SHOW_BR...
0.253676
0.047206
def transcript(input_lang, output_lang, word, engine): if input_lang=="en" and output_lang=="ru": print("In future.") if input_lang=="ru" and output_lang=="en": new_word_letters=[] word_chars=list(word) if engine=="2": for letter in word_chars: ...
res/transcriptor.py
def transcript(input_lang, output_lang, word, engine): if input_lang=="en" and output_lang=="ru": print("In future.") if input_lang=="ru" and output_lang=="en": new_word_letters=[] word_chars=list(word) if engine=="2": for letter in word_chars: ...
0.050647
0.169166
from shapely.geometry import Polygon from shapely.geometry import Point, LineString from shapely.geometry import MultiLineString from shapely.ops import linemerge, split, nearest_points from scipy.stats import multivariate_normal import numpy as np import geopandas as gpd import pandas as pd import json from observ...
tmmpy/track_simulation.py
from shapely.geometry import Polygon from shapely.geometry import Point, LineString from shapely.geometry import MultiLineString from shapely.ops import linemerge, split, nearest_points from scipy.stats import multivariate_normal import numpy as np import geopandas as gpd import pandas as pd import json from observ...
0.667039
0.539832
from itertools import chain from typing import List # Scikit-optimize has a wide range of useful sampling functions, see below link # https://scikit-optimize.github.io/stable/auto_examples/sampler/initial-sampling-method.html import skopt import pygosolnp # The Sampling class is an abstract class that can be inher...
python_examples/example_grid_sampling.py
from itertools import chain from typing import List # Scikit-optimize has a wide range of useful sampling functions, see below link # https://scikit-optimize.github.io/stable/auto_examples/sampler/initial-sampling-method.html import skopt import pygosolnp # The Sampling class is an abstract class that can be inher...
0.91376
0.665574
import unittest from flask import json from tests.base_test import BaseTest from app import db from app.model.chain_step import ChainStep from app.model.questionnaires.chain_session_step import ChainSessionStep class TestChainStep(BaseTest, unittest.TestCase): def test_chain_step_basics(self): self.con...
backend/tests/test_chain_steps.py
import unittest from flask import json from tests.base_test import BaseTest from app import db from app.model.chain_step import ChainStep from app.model.questionnaires.chain_session_step import ChainSessionStep class TestChainStep(BaseTest, unittest.TestCase): def test_chain_step_basics(self): self.con...
0.459561
0.450843
from multiprocessing import Event, Lock, Process import datetime import json from vesper.django.app.models import Job from vesper.util.bunch import Bunch from vesper.util.repeating_timer import RepeatingTimer import vesper.command.job_runner as job_runner import vesper.util.archive_lock as archive_lock import vesper.u...
vesper/command/job_manager.py
from multiprocessing import Event, Lock, Process import datetime import json from vesper.django.app.models import Job from vesper.util.bunch import Bunch from vesper.util.repeating_timer import RepeatingTimer import vesper.command.job_runner as job_runner import vesper.util.archive_lock as archive_lock import vesper.u...
0.600188
0.162579
from math import exp, cos, sin, sqrt from pathlib import Path # AHA imports import magma as m # msdsl imports from ..common import * from msdsl import MixedSignalModel, VerilogGenerator, AnalogSignal, Deriv NAME = Path(__file__).stem.split('_')[1] BUILD_DIR = Path(__file__).resolve().parent / 'build' def pytest_gen...
tests/rlc/test_rlc.py
from math import exp, cos, sin, sqrt from pathlib import Path # AHA imports import magma as m # msdsl imports from ..common import * from msdsl import MixedSignalModel, VerilogGenerator, AnalogSignal, Deriv NAME = Path(__file__).stem.split('_')[1] BUILD_DIR = Path(__file__).resolve().parent / 'build' def pytest_gen...
0.365004
0.258577
import torch import numpy as np import pandas as pd import os from DBN import DBN from load_dataset import MNIST import cv2 from PIL import Image from matplotlib import pyplot as plt def image_beautifier(names, final_name): image_names = sorted(names) images = [Image.open(x) for x in names] widths, heights = zip(*...
test_MNIST_DBN_example.py
import torch import numpy as np import pandas as pd import os from DBN import DBN from load_dataset import MNIST import cv2 from PIL import Image from matplotlib import pyplot as plt def image_beautifier(names, final_name): image_names = sorted(names) images = [Image.open(x) for x in names] widths, heights = zip(*...
0.298594
0.350088
from pathlib import Path from io import StringIO import numpy as np import pandas as pd import requests def import_and_clean_cases(save_path: Path) -> pd.DataFrame: ''' Import and clean case data from covidtracking.com. ''' # Parameters for filtering raw df kept_columns = ['date','state','positi...
us_states_validation/etl.py
from pathlib import Path from io import StringIO import numpy as np import pandas as pd import requests def import_and_clean_cases(save_path: Path) -> pd.DataFrame: ''' Import and clean case data from covidtracking.com. ''' # Parameters for filtering raw df kept_columns = ['date','state','positi...
0.541166
0.405213
import csv import os import shutil import tempfile from unittest import TestCase from src.extractor import extract_dot_text, extract_dot_text_to_file, \ extract_function_to_file, get_opcode PREFIX = "BCCFLT_" class TestExtractor(TestCase): tmpdir: str = None file: str = "./resources/tempfile" expect...
tests/extractor_tests.py
import csv import os import shutil import tempfile from unittest import TestCase from src.extractor import extract_dot_text, extract_dot_text_to_file, \ extract_function_to_file, get_opcode PREFIX = "BCCFLT_" class TestExtractor(TestCase): tmpdir: str = None file: str = "./resources/tempfile" expect...
0.141845
0.115636
import argparse import numpy as np import scipy.io as sio from niio import loaded import os from fragmenter import RegionExtractor as re from congrads import conmap parser = argparse.ArgumentParser() parser.add_argument('-s', '--subject', help='Input subject name.', r...
bin/eta2_regions.py
import argparse import numpy as np import scipy.io as sio from niio import loaded import os from fragmenter import RegionExtractor as re from congrads import conmap parser = argparse.ArgumentParser() parser.add_argument('-s', '--subject', help='Input subject name.', r...
0.499512
0.179207
import flask import os import sendgrid import orton_restitution app = flask.Flask(__name__) app.secret_key = os.getenv('SECRET_KEY') @app.route('/') def index(): """Index page.""" return flask.render_template('index.html') @app.route('/send-email', methods=['POST']) def send_email(): email = flask.request.for...
web.py
import flask import os import sendgrid import orton_restitution app = flask.Flask(__name__) app.secret_key = os.getenv('SECRET_KEY') @app.route('/') def index(): """Index page.""" return flask.render_template('index.html') @app.route('/send-email', methods=['POST']) def send_email(): email = flask.request.for...
0.21917
0.049474
from pycont import Contract, Template, TemplateError import unittest import trafaret as t class TestValidator(unittest.TestCase): def test_template(self): with self.assertRaises(ValueError): template = Template('error') trafaret = t.String() template = Template(trafaret) ...
tests/test_validator.py
from pycont import Contract, Template, TemplateError import unittest import trafaret as t class TestValidator(unittest.TestCase): def test_template(self): with self.assertRaises(ValueError): template = Template('error') trafaret = t.String() template = Template(trafaret) ...
0.483648
0.598723
import json import shlex from abc import abstractmethod from contextlib import contextmanager from copy import deepcopy from os import getenv, getcwd, chdir, environ from os.path import join, basename, normpath, abspath from typing import Optional, List, Generator, Dict, Tuple, Union import click from jsonschema.val...
gameta/context.py
import json import shlex from abc import abstractmethod from contextlib import contextmanager from copy import deepcopy from os import getenv, getcwd, chdir, environ from os.path import join, basename, normpath, abspath from typing import Optional, List, Generator, Dict, Tuple, Union import click from jsonschema.val...
0.750553
0.207917
from __future__ import annotations from datetime import date, datetime, time from decimal import Decimal from typing import Any from watchmen_data_kernel.common import ask_all_date_formats, ask_full_datetime_formats, ask_time_formats, \ DataKernelException from watchmen_model.admin import Factor, FactorType from wat...
packages/watchmen-data-kernel/src/watchmen_data_kernel/topic_schema/utils.py
from __future__ import annotations from datetime import date, datetime, time from decimal import Decimal from typing import Any from watchmen_data_kernel.common import ask_all_date_formats, ask_full_datetime_formats, ask_time_formats, \ DataKernelException from watchmen_model.admin import Factor, FactorType from wat...
0.528777
0.283386
from selfea.utils.data_structure_utils import return_indices, get_max_value_key, get_min_value_key from selfea.utils.dask_clients import ClientFuture from selfea.core._feature_evaluator import FeatureEvaluator from selfea.default_models.default_xgboost_regressor import DefaultXGBoostRegressor from collections import de...
selfea/selfea.py
from selfea.utils.data_structure_utils import return_indices, get_max_value_key, get_min_value_key from selfea.utils.dask_clients import ClientFuture from selfea.core._feature_evaluator import FeatureEvaluator from selfea.default_models.default_xgboost_regressor import DefaultXGBoostRegressor from collections import de...
0.200245
0.187226
import json import multiprocessing import time import requests import snappi from flask import Flask, Response, request from otg_gnmi.common.utils import init_logging, get_current_time from tests.utils.common import get_mockserver_status from tests.utils.settings import MockConfig app = Flask(__name__) CONFIG = Mock...
tests/snappiserver.py
import json import multiprocessing import time import requests import snappi from flask import Flask, Response, request from otg_gnmi.common.utils import init_logging, get_current_time from tests.utils.common import get_mockserver_status from tests.utils.settings import MockConfig app = Flask(__name__) CONFIG = Mock...
0.408631
0.068226
import tornado.web import tornado.websocket import tornado.httpserver import tornado.ioloop import logging import json from threading import Thread from queue import Queue # Handle WebSocket clients clients = [] class WebSocketHandler(tornado.websocket.WebSocketHandler): """ Handle default WebSocket connections...
lib/WebSocketServer.py
import tornado.web import tornado.websocket import tornado.httpserver import tornado.ioloop import logging import json from threading import Thread from queue import Queue # Handle WebSocket clients clients = [] class WebSocketHandler(tornado.websocket.WebSocketHandler): """ Handle default WebSocket connections...
0.53437
0.074164
"""Handling of build perf test reports""" from collections import OrderedDict, Mapping, namedtuple from datetime import datetime, timezone from numbers import Number from statistics import mean, stdev, variance AggregateTestData = namedtuple('AggregateTestData', ['metadata', 'results']) def isofmt_to_timestamp(stri...
poky/scripts/lib/build_perf/report.py
"""Handling of build perf test reports""" from collections import OrderedDict, Mapping, namedtuple from datetime import datetime, timezone from numbers import Number from statistics import mean, stdev, variance AggregateTestData = namedtuple('AggregateTestData', ['metadata', 'results']) def isofmt_to_timestamp(stri...
0.701509
0.418697
import numpy as np import warnings from scipy import sparse from sklearn.utils import (check_array, check_consistent_length) from sklearn.cluster import DBSCAN as DBSCAN_original import daal4py from daal4py.sklearn._utils import (make2d, getFPType) def _daal_dbscan(X, eps=0.5, min_samples=5, sample_weight=None): ...
daal4py/sklearn/cluster/_dbscan_0_21.py
import numpy as np import warnings from scipy import sparse from sklearn.utils import (check_array, check_consistent_length) from sklearn.cluster import DBSCAN as DBSCAN_original import daal4py from daal4py.sklearn._utils import (make2d, getFPType) def _daal_dbscan(X, eps=0.5, min_samples=5, sample_weight=None): ...
0.84489
0.59514
from __future__ import annotations import typing import enum from pantra.components.context import Context from pantra.models.types import * from pantra.common import ADict, WebUnits if typing.TYPE_CHECKING: from typing import * from pantra.models.runtime import AttrInfo from pantra.components.context im...
components/Widgets/__init__.py
from __future__ import annotations import typing import enum from pantra.components.context import Context from pantra.models.types import * from pantra.common import ADict, WebUnits if typing.TYPE_CHECKING: from typing import * from pantra.models.runtime import AttrInfo from pantra.components.context im...
0.438905
0.122235
# Standard library imports import pkg_resources # Third party imports import pytest from qtpy.QtCore import QObject, Signal, Slot # Local imports from spyder.plugins.completion.api import ( SpyderCompletionProvider, CompletionRequestTypes) class DummyCompletionReceiver(QObject): """Dummy class that can hand...
spyder/plugins/completion/tests/test_plugin.py
# Standard library imports import pkg_resources # Third party imports import pytest from qtpy.QtCore import QObject, Signal, Slot # Local imports from spyder.plugins.completion.api import ( SpyderCompletionProvider, CompletionRequestTypes) class DummyCompletionReceiver(QObject): """Dummy class that can hand...
0.637595
0.390883
"""This program helps organize and version your dot files with Git.""" import homekeeper.config import homekeeper.util import logging import os import shutil __version__ = '3.2.0' class Homekeeper(object): """Organizes and versions your dot files.""" def __init__(self, pathname=None): self.pathname =...
homekeeper/__init__.py
"""This program helps organize and version your dot files with Git.""" import homekeeper.config import homekeeper.util import logging import os import shutil __version__ = '3.2.0' class Homekeeper(object): """Organizes and versions your dot files.""" def __init__(self, pathname=None): self.pathname =...
0.715523
0.184676
from __future__ import absolute_import import os import shutil import hashlib import stat import re from git.repo import Repo from gitdb.exc import BadName, BadObject from lockfile import LockFile from st2common import log as logging from st2common.content import utils from st2common.constants.pack import MANIFEST_F...
st2common/st2common/util/pack_management.py
from __future__ import absolute_import import os import shutil import hashlib import stat import re from git.repo import Repo from gitdb.exc import BadName, BadObject from lockfile import LockFile from st2common import log as logging from st2common.content import utils from st2common.constants.pack import MANIFEST_F...
0.518302
0.091301
"""Helper functions for the Keras implementations of models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import multiprocessing import os import time from absl import logging import tensorflow as tf from tensorflow.core.protobuf import rewriter_conf...
image_classification/tensorflow2/tf2_common/utils/misc/keras_utils.py
"""Helper functions for the Keras implementations of models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import multiprocessing import os import time from absl import logging import tensorflow as tf from tensorflow.core.protobuf import rewriter_conf...
0.862901
0.422266
from pprint import pprint from marshmallow import fields, Schema, ValidationError, validate, validates, validates_schema class PersonSchema(Schema): first_name = fields.String(required=True, error_messages={"required": "Please enter first name"}) last_name = fields.String(allow_none=None) email = fields.E...
schema_validation.py
from pprint import pprint from marshmallow import fields, Schema, ValidationError, validate, validates, validates_schema class PersonSchema(Schema): first_name = fields.String(required=True, error_messages={"required": "Please enter first name"}) last_name = fields.String(allow_none=None) email = fields.E...
0.373304
0.231951
import random class Converter(object): def dec2bin(self, decimal): if type(decimal).__name__ == 'str': print "Error type : Not a integer" return 0 digit = 1 binary = 0 decimal = int(decimal) while decimal != 0: binary = binary + (...
crc/PyCRC-master/pycrc/crclib.py
import random class Converter(object): def dec2bin(self, decimal): if type(decimal).__name__ == 'str': print "Error type : Not a integer" return 0 digit = 1 binary = 0 decimal = int(decimal) while decimal != 0: binary = binary + (...
0.500488
0.191914
import datetime import random import re import ssl import typing import aiohttp from vkquick.json_parsers import json_parser_policy def random_id(side: int = 2 ** 31 - 1) -> int: """ Случайное число в диапазоне +-`side`. Используется для API метода `messages.send` """ return random.randint(-side...
vkquick/chatbot/utils.py
import datetime import random import re import ssl import typing import aiohttp from vkquick.json_parsers import json_parser_policy def random_id(side: int = 2 ** 31 - 1) -> int: """ Случайное число в диапазоне +-`side`. Используется для API метода `messages.send` """ return random.randint(-side...
0.521715
0.218294
__AUTHOR__ = "hugsy" __VERSION__ = 0.1 import os import gdb def fastbin_index(sz): return (sz >> 4) - 2 if current_arch.ptrsize == 8 else (sz >> 3) - 2 def nfastbins(): return fastbin_index( (80 * current_arch.ptrsize // 4)) - 1 def get_tcache_count(): if get_libc_version() < (2, 27): return ...
scripts/visualize_heap.py
__AUTHOR__ = "hugsy" __VERSION__ = 0.1 import os import gdb def fastbin_index(sz): return (sz >> 4) - 2 if current_arch.ptrsize == 8 else (sz >> 3) - 2 def nfastbins(): return fastbin_index( (80 * current_arch.ptrsize // 4)) - 1 def get_tcache_count(): if get_libc_version() < (2, 27): return ...
0.270769
0.173954
from unittest import TestCase from unittest.mock import Mock, call, patch import os import sys sys.path.append(os.path.abspath('./src')) from pkgs.ui.models.ctrlrModel import CtrlrModel # noqa: E402 class TestCtrlrModel(TestCase): """ CtrlrModel test cases. """ def setUp(self): """ ...
tests/unit/pkgs/ui/models/ctrlrModel/test_CtrlrModel.py
from unittest import TestCase from unittest.mock import Mock, call, patch import os import sys sys.path.append(os.path.abspath('./src')) from pkgs.ui.models.ctrlrModel import CtrlrModel # noqa: E402 class TestCtrlrModel(TestCase): """ CtrlrModel test cases. """ def setUp(self): """ ...
0.490968
0.326191
import unittest import time from app import create_app,db from app.models import User,AnonymousUser,Role,Permission class UserModelTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() ...
tests/test_user_model.py
import unittest import time from app import create_app,db from app.models import User,AnonymousUser,Role,Permission class UserModelTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() ...
0.325199
0.270112
import json from . import db import pandas as pd from datetime import datetime from geoalchemy2 import functions from geoalchemy2.types import Geometry from flask import current_app, request, url_for from .errors import AlreadyExistsError class BaseExtension(db.MapperExtension): """Base extension for all entities...
app/models.py
import json from . import db import pandas as pd from datetime import datetime from geoalchemy2 import functions from geoalchemy2.types import Geometry from flask import current_app, request, url_for from .errors import AlreadyExistsError class BaseExtension(db.MapperExtension): """Base extension for all entities...
0.763836
0.138899
import numpy as np from ..helpers import numerical_test __all__ = ( 'central_moment', 'mean', 'median', 'mode', 'standard_deviation', 'standard_moment', ) def mean(dist): """ Computes the mean of the distribution. Parameters ---------- dist : Distribution The di...
dit/algorithms/stats.py
import numpy as np from ..helpers import numerical_test __all__ = ( 'central_moment', 'mean', 'median', 'mode', 'standard_deviation', 'standard_moment', ) def mean(dist): """ Computes the mean of the distribution. Parameters ---------- dist : Distribution The di...
0.934887
0.871037
import pprint import re # noqa: F401 import six class Quote(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name ...
sdk/lusid/models/quote.py
import pprint import re # noqa: F401 import six class Quote(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name ...
0.835618
0.128388
import os import re import codecs from setuptools import setup from setuptools import find_packages PROJECT = os.path.abspath(os.path.dirname(__file__)) REQUIRE_PATH = "requirements.txt" EXCLUDES = ( "tests", "bin", "docs", "fixtures", "register", "notebooks", "examples", ) long_description = open('README.rs...
setup.py
import os import re import codecs from setuptools import setup from setuptools import find_packages PROJECT = os.path.abspath(os.path.dirname(__file__)) REQUIRE_PATH = "requirements.txt" EXCLUDES = ( "tests", "bin", "docs", "fixtures", "register", "notebooks", "examples", ) long_description = open('README.rs...
0.423935
0.167866
import sys import unittest from pyasn1.codec.der.decoder import decode as der_decoder from pyasn1.codec.der.encoder import encode as der_encoder from pyasn1.type import univ from pyasn1_modules import pem, rfc2985, rfc5280, rfc5652, rfc7292 class PKCS9AttrsTestCase(unittest.TestCase): pem_text = """\ <KEY> """ ...
tests/test_rfc2985.py
import sys import unittest from pyasn1.codec.der.decoder import decode as der_decoder from pyasn1.codec.der.encoder import encode as der_encoder from pyasn1.type import univ from pyasn1_modules import pem, rfc2985, rfc5280, rfc5652, rfc7292 class PKCS9AttrsTestCase(unittest.TestCase): pem_text = """\ <KEY> """ ...
0.412767
0.47098
import sys from com.l2jserver import Config from com.l2jserver.gameserver.model.quest import State from com.l2jserver.gameserver.model.quest import QuestState from com.l2jserver.gameserver.model.quest.jython import QuestJython as JQuest qn = "426_FishingShot" SWEET_FLUID = 7586 MOBS1 = { 20005:45,20013:100,20016:...
L2J_DataPack/data/scripts/quests/426_FishingShot/__init__.py
import sys from com.l2jserver import Config from com.l2jserver.gameserver.model.quest import State from com.l2jserver.gameserver.model.quest import QuestState from com.l2jserver.gameserver.model.quest.jython import QuestJython as JQuest qn = "426_FishingShot" SWEET_FLUID = 7586 MOBS1 = { 20005:45,20013:100,20016:...
0.204501
0.24907
#input modules import datetime #imports from flask_restful import Resource from flask import request, make_response, jsonify #local import from app.api.v2.utilis.validations import CheckData from app.api.v2.models.questions import QuestionsModel from app.api.v2.models.meetup import MeetUp #error messages empty_questio...
app/api/v2/views/questionsviews.py
#input modules import datetime #imports from flask_restful import Resource from flask import request, make_response, jsonify #local import from app.api.v2.utilis.validations import CheckData from app.api.v2.models.questions import QuestionsModel from app.api.v2.models.meetup import MeetUp #error messages empty_questio...
0.218003
0.167185
from abc import ABC, abstractmethod from typing import Dict, Generic, Iterable, Optional, TypeVar, Union VT = Union[ str, int, float, bool, "Config", Dict[str, Union[str, int, float, bool]] ] FT = TypeVar("FT", bound="VT") RawConfig = Dict[str, VT] class Field(ABC, Generic[FT]): def __init__( self,...
src/config/abc.py
from abc import ABC, abstractmethod from typing import Dict, Generic, Iterable, Optional, TypeVar, Union VT = Union[ str, int, float, bool, "Config", Dict[str, Union[str, int, float, bool]] ] FT = TypeVar("FT", bound="VT") RawConfig = Dict[str, VT] class Field(ABC, Generic[FT]): def __init__( self,...
0.92058
0.226249
import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class AmiFromInstance(pulumi.CustomResource): architecture: pulumi.Output[str] """ Machine architecture for created instances. Defaults to "x86_64". """ description: pulumi.Output[str] """ A lo...
sdk/python/pulumi_aws/ec2/ami_from_instance.py
import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class AmiFromInstance(pulumi.CustomResource): architecture: pulumi.Output[str] """ Machine architecture for created instances. Defaults to "x86_64". """ description: pulumi.Output[str] """ A lo...
0.672547
0.173183
from __future__ import print_function import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.datasets import fetch_20newsgroups from sklearn.datasets.twenty_newsgroups import strip_newsgroup_footer from sklearn.datasets.twenty_newsgroups import strip_newsgroup_quoting from sklearn.de...
examples/compose/plot_column_transformer.py
from __future__ import print_function import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.datasets import fetch_20newsgroups from sklearn.datasets.twenty_newsgroups import strip_newsgroup_footer from sklearn.datasets.twenty_newsgroups import strip_newsgroup_quoting from sklearn.de...
0.851614
0.499451
import os import os.path import copy import hashlib import errno import numpy as np from numpy.testing import assert_array_almost_equal def check_integrity(fpath, md5): if not os.path.isfile(fpath): return False md5o = hashlib.md5() with open(fpath, 'rb') as f: # read in 1MB chunks ...
code/data/data_util.py
import os import os.path import copy import hashlib import errno import numpy as np from numpy.testing import assert_array_almost_equal def check_integrity(fpath, md5): if not os.path.isfile(fpath): return False md5o = hashlib.md5() with open(fpath, 'rb') as f: # read in 1MB chunks ...
0.515864
0.472197
from functools import partial from typing import Callable, Dict from .. import core from .. import linear_util as lu from ..core import Trace, Tracer, new_master from ..abstract_arrays import ShapedArray, raise_to_shaped from ..util import safe_map, safe_zip, unzip2, unzip3 map = safe_map zip = safe_zip def identi...
jax/interpreters/parallel.py
from functools import partial from typing import Callable, Dict from .. import core from .. import linear_util as lu from ..core import Trace, Tracer, new_master from ..abstract_arrays import ShapedArray, raise_to_shaped from ..util import safe_map, safe_zip, unzip2, unzip3 map = safe_map zip = safe_zip def identi...
0.565899
0.307943
from mqtt import MqttMessage, MqttConfigMessage from workers.base import BaseWorker import logger REQUIREMENTS = ["python-smartgadget"] ATTR_CONFIG = [ # (attribute_name, device_class, unit_of_measurement) ("temperature", "temperature", "°C"), ("humidity", "humidity", "%"), ("battery_level", "battery...
workers/smartgadget.py
from mqtt import MqttMessage, MqttConfigMessage from workers.base import BaseWorker import logger REQUIREMENTS = ["python-smartgadget"] ATTR_CONFIG = [ # (attribute_name, device_class, unit_of_measurement) ("temperature", "temperature", "°C"), ("humidity", "humidity", "%"), ("battery_level", "battery...
0.379263
0.1425
import torch import torch.nn as nn import torch.nn.functional as F import dgl """ Graph Transformer """ from layers.graph_transformer_layer import GraphTransformerLayer from layers.mlp_readout_layer import MLPReadout class GraphTransformerNet(nn.Module): def __init__(self, net_params): super()....
nets/SBMs_node_classification/graph_transformer_net.py
import torch import torch.nn as nn import torch.nn.functional as F import dgl """ Graph Transformer """ from layers.graph_transformer_layer import GraphTransformerLayer from layers.mlp_readout_layer import MLPReadout class GraphTransformerNet(nn.Module): def __init__(self, net_params): super()....
0.908364
0.297741
import torch, pdb, os, json from shared import _cat_ import numpy as np from model import OptionInfer, Scorer from collections import defaultdict def get_model(path, cuda=True): opt = OptionInfer(cuda) if path.endswith('.yaml') or path.endswith('.yml'): from model import JointScorer model = Jo...
src/score.py
import torch, pdb, os, json from shared import _cat_ import numpy as np from model import OptionInfer, Scorer from collections import defaultdict def get_model(path, cuda=True): opt = OptionInfer(cuda) if path.endswith('.yaml') or path.endswith('.yml'): from model import JointScorer model = Jo...
0.446736
0.242015
# ============= enthought library imports ======================= from reportlab.lib.pagesizes import A4, letter, landscape, A2, A0 from reportlab.lib.units import inch, cm from traits.api import Str, Bool, Enum, Button, Float, Color from traitsui.api import View, Item, UItem, HGroup, Group, VGroup, spring, Spring fr...
pychron/core/pdf/options.py
# ============= enthought library imports ======================= from reportlab.lib.pagesizes import A4, letter, landscape, A2, A0 from reportlab.lib.units import inch, cm from traits.api import Str, Bool, Enum, Button, Float, Color from traitsui.api import View, Item, UItem, HGroup, Group, VGroup, spring, Spring fr...
0.520009
0.134406
import os import shlex import shutil from abc import ABCMeta, abstractmethod from glob import glob from . import util _modulefile_template = """#%%Module1.0 set MODULENAME [ file tail [ file dirname $ModulesCurrentModulefile ] ] set MODULEVERSION [ file tail $ModulesCurrentModulefile ] set MODULEBASE %s set basedir $...
moduledev/module.py
import os import shlex import shutil from abc import ABCMeta, abstractmethod from glob import glob from . import util _modulefile_template = """#%%Module1.0 set MODULENAME [ file tail [ file dirname $ModulesCurrentModulefile ] ] set MODULEVERSION [ file tail $ModulesCurrentModulefile ] set MODULEBASE %s set basedir $...
0.622115
0.107063
import itertools import gzip import json import shutil from pathlib import Path from typing import Iterable, Generator, List, Callable, TypeVar, Optional, Union, Any def gzip_unpack(input_file: str, output_file: str): with gzip.open(input_file, "rb") as packed: with open(output_file, "wb") as unpacked: ...
utils/functions.py
import itertools import gzip import json import shutil from pathlib import Path from typing import Iterable, Generator, List, Callable, TypeVar, Optional, Union, Any def gzip_unpack(input_file: str, output_file: str): with gzip.open(input_file, "rb") as packed: with open(output_file, "wb") as unpacked: ...
0.783409
0.303113
from __future__ import print_function import re, atexit @atexit.register def graceful_exit(): from platform import system if system() == 'Windows': raw_input('Press enter to close the window...') # add tab completion to raw_input, for those platforms that support it try: import readline if 'libedit'...
simulator.py
from __future__ import print_function import re, atexit @atexit.register def graceful_exit(): from platform import system if system() == 'Windows': raw_input('Press enter to close the window...') # add tab completion to raw_input, for those platforms that support it try: import readline if 'libedit'...
0.116512
0.066904
import os import re from django import forms from django.conf import settings from django.forms import ModelForm from django.forms.models import modelformset_factory from django.template import Context, Template, TemplateSyntaxError import commonware.log import happyforms from piston.models import Consumer from produ...
src/olympia/zadmin/forms.py
import os import re from django import forms from django.conf import settings from django.forms import ModelForm from django.forms.models import modelformset_factory from django.template import Context, Template, TemplateSyntaxError import commonware.log import happyforms from piston.models import Consumer from produ...
0.427397
0.088583
import itertools COLOR_WILD = 0 COLOR_RED = 1 COLOR_YELLOW = 2 COLOR_GREEN = 3 COLOR_BLUE = 4 CARD_0 = 0 CARD_1 = 1 CARD_2 = 2 CARD_3 = 3 CARD_4 = 4 CARD_5 = 5 CARD_6 = 6 CARD_7 = 7 CARD_8 = 8 CARD_9 = 9 CARD_SKIP = 10 CARD_REVERSE = 11 CARD_DRAWTWO = 12 CARD_WILD = 13 CARD_DRAWFOUR = 14 CARD_DRAWEIGHT = 15 CARD_SHU...
modules/games/uno_vars.py
import itertools COLOR_WILD = 0 COLOR_RED = 1 COLOR_YELLOW = 2 COLOR_GREEN = 3 COLOR_BLUE = 4 CARD_0 = 0 CARD_1 = 1 CARD_2 = 2 CARD_3 = 3 CARD_4 = 4 CARD_5 = 5 CARD_6 = 6 CARD_7 = 7 CARD_8 = 8 CARD_9 = 9 CARD_SKIP = 10 CARD_REVERSE = 11 CARD_DRAWTWO = 12 CARD_WILD = 13 CARD_DRAWFOUR = 14 CARD_DRAWEIGHT = 15 CARD_SHU...
0.221267
0.0745
from moontracker.models import Alert from tests.utils import test_client def test_valid_post(): response = test_client.post( '/', data={ 'phone_number': '5558675309', 'asset': 'BTC', 'market': 'gemini', 'cond_option': '1', 'price': '100' ...
tests/views/test_home.py
from moontracker.models import Alert from tests.utils import test_client def test_valid_post(): response = test_client.post( '/', data={ 'phone_number': '5558675309', 'asset': 'BTC', 'market': 'gemini', 'cond_option': '1', 'price': '100' ...
0.66061
0.393909
from __future__ import annotations from typing import TYPE_CHECKING, Any, Callable, Dict, List, Union from httpx import AsyncClient from supertokens_python.recipe.thirdparty.provider import Provider from supertokens_python.recipe.thirdparty.types import ( AccessTokenAPI, AuthorisationRedirectAPI, UserInfo, UserIn...
supertokens_python/recipe/thirdparty/providers/facebook.py
from __future__ import annotations from typing import TYPE_CHECKING, Any, Callable, Dict, List, Union from httpx import AsyncClient from supertokens_python.recipe.thirdparty.provider import Provider from supertokens_python.recipe.thirdparty.types import ( AccessTokenAPI, AuthorisationRedirectAPI, UserInfo, UserIn...
0.789761
0.071851
import numpy as np import pandas as pd import visualisation from population import Country def run(n_infected, total_time, super_spreader_proportion=0.05, infection_distance=0.5, infection_probability=0.1, return_gif_frames=False, figsize=(8, 8)): df = pd.DataFram...
simulation.py
import numpy as np import pandas as pd import visualisation from population import Country def run(n_infected, total_time, super_spreader_proportion=0.05, infection_distance=0.5, infection_probability=0.1, return_gif_frames=False, figsize=(8, 8)): df = pd.DataFram...
0.402392
0.302939
from __future__ import print_function as _print_function import sys as _sys from tensorflow.python.framework.ops import name_scope from tensorflow.python.keras.backend import abs from tensorflow.python.keras.backend import all from tensorflow.python.keras.backend import any from tensorflow.python.keras.backend import...
cart_venv/Lib/site-packages/tensorflow_core/python/keras/api/keras/backend/__init__.py
from __future__ import print_function as _print_function import sys as _sys from tensorflow.python.framework.ops import name_scope from tensorflow.python.keras.backend import abs from tensorflow.python.keras.backend import all from tensorflow.python.keras.backend import any from tensorflow.python.keras.backend import...
0.707708
0.128826
from __future__ import absolute_import, print_function from sentry import eventstore, nodestore from sentry.models import Event, EventAttachment, UserReport from ..base import BaseDeletionTask, BaseRelation, ModelDeletionTask, ModelRelation class EventDataDeletionTask(BaseDeletionTask): """ Deletes nodestor...
src/sentry/deletions/defaults/group.py
from __future__ import absolute_import, print_function from sentry import eventstore, nodestore from sentry.models import Event, EventAttachment, UserReport from ..base import BaseDeletionTask, BaseRelation, ModelDeletionTask, ModelRelation class EventDataDeletionTask(BaseDeletionTask): """ Deletes nodestor...
0.638046
0.141163
from abc import ABC, abstractmethod from collections import OrderedDict from typing import Any, Dict, Generator, List from the_census._api.models import GeographyItem from the_census._geographies.models import GeoDomain from the_census._variables.models import Group, GroupVariable, VariableCode class ICensusApiFetch...
the_census/_api/interface.py
from abc import ABC, abstractmethod from collections import OrderedDict from typing import Any, Dict, Generator, List from the_census._api.models import GeographyItem from the_census._geographies.models import GeoDomain from the_census._variables.models import Group, GroupVariable, VariableCode class ICensusApiFetch...
0.923726
0.573678
# pylint: disable=C0111 # The documentation is extracted from the base classes # pylint: disable=E1101,E1102 # We dynamically generate the Button class # pylint: disable=R0903 # We implement stubs import enum import Xlib.display import Xlib.ext import Xlib.ext.xtest import Xlib.X import Xlib.protocol from pynput._...
pype/vendor/pynput/mouse/_xorg.py
# pylint: disable=C0111 # The documentation is extracted from the base classes # pylint: disable=E1101,E1102 # We dynamically generate the Button class # pylint: disable=R0903 # We implement stubs import enum import Xlib.display import Xlib.ext import Xlib.ext.xtest import Xlib.X import Xlib.protocol from pynput._...
0.637031
0.115486
from sawtooth_processor_test.message_factory import MessageFactory class XoMessageFactory: def __init__(self, signer=None): self._factory = MessageFactory( family_name="xo", family_version="1.0", namespace=MessageFactory.sha512("xo".encode("utf-8"))[0:6], s...
sdk/examples/xo_python/sawtooth_xo/xo_message_factory.py
from sawtooth_processor_test.message_factory import MessageFactory class XoMessageFactory: def __init__(self, signer=None): self._factory = MessageFactory( family_name="xo", family_version="1.0", namespace=MessageFactory.sha512("xo".encode("utf-8"))[0:6], s...
0.754915
0.29682
from urllib.request import urlopen, Request from urllib.parse import urlencode, quote_plus from bs4 import BeautifulSoup from django.utils.encoding import smart_str import threading, random browsers = ['Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3', 'Mozilla/5.0 (Window...
BingQuaker/core.py
from urllib.request import urlopen, Request from urllib.parse import urlencode, quote_plus from bs4 import BeautifulSoup from django.utils.encoding import smart_str import threading, random browsers = ['Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3', 'Mozilla/5.0 (Window...
0.372619
0.104843
from bootstrapvz.base import Task from bootstrapvz.common import phases from bootstrapvz.common.tasks import workspace from bootstrapvz.common.tools import rel_path import os import shutil import json assets = rel_path(__file__, 'assets') class CheckBoxPath(Task): description = 'Checking if the vagrant box file ...
bootstrapvz/plugins/vagrant/tasks.py
from bootstrapvz.base import Task from bootstrapvz.common import phases from bootstrapvz.common.tasks import workspace from bootstrapvz.common.tools import rel_path import os import shutil import json assets = rel_path(__file__, 'assets') class CheckBoxPath(Task): description = 'Checking if the vagrant box file ...
0.50293
0.099821
from sqlalchemy import ( create_engine, Column, ForeignKey, Integer, String, PrimaryKeyConstraint, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import Session from .common import CHANNELS Base = declarative_base() sessio...
src/laptimer/db.py
from sqlalchemy import ( create_engine, Column, ForeignKey, Integer, String, PrimaryKeyConstraint, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import Session from .common import CHANNELS Base = declarative_base() sessio...
0.59843
0.236643
import logging from babel import Locale from functools import lru_cache from flask import Blueprint, request, current_app from flask_babel import gettext, get_locale from elasticsearch import TransportError from followthemoney import model from followthemoney.exc import InvalidData from jwt import ExpiredSignatureError...
aleph/views/base_api.py
import logging from babel import Locale from functools import lru_cache from flask import Blueprint, request, current_app from flask_babel import gettext, get_locale from elasticsearch import TransportError from followthemoney import model from followthemoney.exc import InvalidData from jwt import ExpiredSignatureError...
0.583678
0.109016
from __future__ import ( absolute_import, division, print_function, unicode_literals, ) from builtins import * from past.builtins import basestring from ..restsession import RestSession from ..utils import ( check_type, apply_path_params, extract_and_parse_json, pprint_request_info, ...
dnacentersdk/api/custom_caller.py
from __future__ import ( absolute_import, division, print_function, unicode_literals, ) from builtins import * from past.builtins import basestring from ..restsession import RestSession from ..utils import ( check_type, apply_path_params, extract_and_parse_json, pprint_request_info, ...
0.713232
0.158272
import sys, os import binascii, sqlite3 ## Global Options gOpts = { "multiple" : False, "subdirs" : False, "force" : False } class Message: def __init__( self, data ): self.parse_data( data ) def parse_data( self, data ): self.type = data[ 0 ] se...
src/smsExtractor.py
import sys, os import binascii, sqlite3 ## Global Options gOpts = { "multiple" : False, "subdirs" : False, "force" : False } class Message: def __init__( self, data ): self.parse_data( data ) def parse_data( self, data ): self.type = data[ 0 ] se...
0.17075
0.294995
import logging import uuid from typing import Callable, Any, Union import asyncio from Foundation import NSData, CBUUID from CoreBluetooth import ( CBCharacteristicWriteWithResponse, CBCharacteristicWriteWithoutResponse, ) from bleak.backends.client import BaseBleakClient from bleak.backends.corebluetooth.cha...
bleak/backends/corebluetooth/client.py
import logging import uuid from typing import Callable, Any, Union import asyncio from Foundation import NSData, CBUUID from CoreBluetooth import ( CBCharacteristicWriteWithResponse, CBCharacteristicWriteWithoutResponse, ) from bleak.backends.client import BaseBleakClient from bleak.backends.corebluetooth.cha...
0.861363
0.07538
import datetime import pytz from pdb import set_trace import numpy as np from unittest import TestCase from .. import segmentize, check_format, compute_seeds, export_graph, \ feature_lines_to_image, compute_feature_lines, extract_training_points from .helpers import iter_all_files import os __dirname__ = os.path.d...
static/server/modules/test/test_overall_process.py
import datetime import pytz from pdb import set_trace import numpy as np from unittest import TestCase from .. import segmentize, check_format, compute_seeds, export_graph, \ feature_lines_to_image, compute_feature_lines, extract_training_points from .helpers import iter_all_files import os __dirname__ = os.path.d...
0.348978
0.202739
import os from pathlib import Path import requests import errno import shutil import hashlib import zipfile import logging from .tqdm import tqdm logger = logging.getLogger(__name__) __all__ = ['unzip', 'download', 'mkdir', 'check_sha1', 'raise_num_file'] def unzip(zip_file_path, root=os.path.expanduser('./')): ...
autogluon/utils/files.py
import os from pathlib import Path import requests import errno import shutil import hashlib import zipfile import logging from .tqdm import tqdm logger = logging.getLogger(__name__) __all__ = ['unzip', 'download', 'mkdir', 'check_sha1', 'raise_num_file'] def unzip(zip_file_path, root=os.path.expanduser('./')): ...
0.599485
0.144269
import time import warnings from functools import partial import ast import numpy as np import scipy.sparse from sklearn.model_selection import train_test_split, RepeatedStratifiedKFold, \ RepeatedKFold from sklearn.utils import shuffle import pandas as pd from .ml import compute_estimator, train_estimator, get_cl...
flaml/automl.py
import time import warnings from functools import partial import ast import numpy as np import scipy.sparse from sklearn.model_selection import train_test_split, RepeatedStratifiedKFold, \ RepeatedKFold from sklearn.utils import shuffle import pandas as pd from .ml import compute_estimator, train_estimator, get_cl...
0.798737
0.301144
import copy from django.conf import settings from django.contrib.admin import ModelAdmin from django.contrib.admin.views.main import ChangeList from django.forms import ModelForm from django.contrib import admin from django.db import models from suit.widgets import NumberInput, SuitSplitDateTimeWidget from suit.compat ...
djangoPharma/env/Lib/site-packages/suit/admin.py
import copy from django.conf import settings from django.contrib.admin import ModelAdmin from django.contrib.admin.views.main import ChangeList from django.forms import ModelForm from django.contrib import admin from django.db import models from suit.widgets import NumberInput, SuitSplitDateTimeWidget from suit.compat ...
0.57093
0.142918
from unittest.mock import Mock, patch from homeassistant import config_entries from homeassistant.components import deconz from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.setup import async_setup_component import homeassistant.components.light as light from tests.common import m...
tests/components/deconz/test_light.py
from unittest.mock import Mock, patch from homeassistant import config_entries from homeassistant.components import deconz from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.setup import async_setup_component import homeassistant.components.light as light from tests.common import m...
0.70791
0.477981
from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 843493331 """ """ random actions, total chaos """ board = gamma_new(6, 5, 4, 4) assert board is...
z2/part2/interactive/jm/random_fuzzy_arrows_1/843493331.py
from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 843493331 """ """ random actions, total chaos """ board = gamma_new(6, 5, 4, 4) assert board is...
0.760562
0.8874
from datamart.materializers.materializer_base import MaterializerBase import pandas as pd import typing import sys import traceback import datetime class TradingEconomicsMarketMaterializer(MaterializerBase): """TradingEconomicsMaterializer class extended from Materializer class """ def __init__(self, ...
datamart/materializers/tradingeconomics_market_materializer.py
from datamart.materializers.materializer_base import MaterializerBase import pandas as pd import typing import sys import traceback import datetime class TradingEconomicsMarketMaterializer(MaterializerBase): """TradingEconomicsMaterializer class extended from Materializer class """ def __init__(self, ...
0.616936
0.184143
import argparse import serrant def main(): # Parse command line args args = parse_args() print("Loading resources...") # Load Errant annotator = serrant.load("en") # Open output M2 file out_m2 = open(args.out, "w") print("Processing M2 file...") # Open the m2 file and ...
serrant/commands/m2_to_m2.py
import argparse import serrant def main(): # Parse command line args args = parse_args() print("Loading resources...") # Load Errant annotator = serrant.load("en") # Open output M2 file out_m2 = open(args.out, "w") print("Processing M2 file...") # Open the m2 file and ...
0.459804
0.239805
import jaydebeapi import os import logging import sys # Отладочный режим # Значение True - включается автокомит после каждой транзакции, выдается больше отладочной информации на экран. # Значение False - Режим работы в продакшене. На экран работы ничего не выдается. # ВАЖНЫЙ МОМЕНТ! Сообщения в журнал работы (файл "ma...
ANBO/reports.py
import jaydebeapi import os import logging import sys # Отладочный режим # Значение True - включается автокомит после каждой транзакции, выдается больше отладочной информации на экран. # Значение False - Режим работы в продакшене. На экран работы ничего не выдается. # ВАЖНЫЙ МОМЕНТ! Сообщения в журнал работы (файл "ma...
0.097912
0.185062
import numpy as np import scipy.special _POISSON = .25 _N_PROCS = 4 def get_flexure_parameter(h, E, n_dim, gamma_mantle=33000.): """ Calculate the flexure parameter based on some physical constants. *h* is the Effective elastic thickness of Earth's crust (m), *E* is Young's Modulus, and *n_dim* is ...
landlab/components/flexure/funcs.py
import numpy as np import scipy.special _POISSON = .25 _N_PROCS = 4 def get_flexure_parameter(h, E, n_dim, gamma_mantle=33000.): """ Calculate the flexure parameter based on some physical constants. *h* is the Effective elastic thickness of Earth's crust (m), *E* is Young's Modulus, and *n_dim* is ...
0.896007
0.579162
import logging XPATH_EMPTY = object() XPATH_NO_DEFAULT = object() logger = logging.getLogger() class X(object): """ doc_xpath_dict_map using object receive list of string or single string. Will pick the first xpath matched. """ XPATH_NO_DEFAULT = NotImplemented def __init__(self, *xpath, d...
doc_xpath.py
import logging XPATH_EMPTY = object() XPATH_NO_DEFAULT = object() logger = logging.getLogger() class X(object): """ doc_xpath_dict_map using object receive list of string or single string. Will pick the first xpath matched. """ XPATH_NO_DEFAULT = NotImplemented def __init__(self, *xpath, d...
0.47926
0.188007
import typing from abc import ABCMeta, abstractmethod from .skill import RuntimeConfigurationBuilder from .dispatch_components import ( AbstractRequestHandler, AbstractRequestInterceptor, AbstractResponseInterceptor, AbstractExceptionHandler) from .exceptions import SkillBuilderException if typing.TYPE_CHEC...
ask-sdk-runtime/ask_sdk_runtime/skill_builder.py
import typing from abc import ABCMeta, abstractmethod from .skill import RuntimeConfigurationBuilder from .dispatch_components import ( AbstractRequestHandler, AbstractRequestInterceptor, AbstractResponseInterceptor, AbstractExceptionHandler) from .exceptions import SkillBuilderException if typing.TYPE_CHEC...
0.888928
0.140867
from abc import ABCMeta, abstractmethod import torch.nn as nn class BaseDenseHead(nn.Module, metaclass=ABCMeta): """Base class for DenseHeads.""" def __init__(self): super(BaseDenseHead, self).__init__() @abstractmethod def loss(self, **kwargs): """Compute losses of the head.""" ...
mmdet/models/dense_heads/base_dense_head.py
from abc import ABCMeta, abstractmethod import torch.nn as nn class BaseDenseHead(nn.Module, metaclass=ABCMeta): """Base class for DenseHeads.""" def __init__(self): super(BaseDenseHead, self).__init__() @abstractmethod def loss(self, **kwargs): """Compute losses of the head.""" ...
0.939554
0.317664
# app.py # Required imports import os import time import json from flask_cors import CORS import firebase_admin from flask import Flask, request, jsonify, redirect, session, render_template from firebase_admin import credentials, firestore, initialize_app from twilio.rest import Client from twilio.twiml.messaging_resp...
HW1_Main.py
# app.py # Required imports import os import time import json from flask_cors import CORS import firebase_admin from flask import Flask, request, jsonify, redirect, session, render_template from firebase_admin import credentials, firestore, initialize_app from twilio.rest import Client from twilio.twiml.messaging_resp...
0.379723
0.08292
from openstack.baremetal.v1 import _common from openstack.baremetal.v1 import allocation as _allocation from openstack.baremetal.v1 import chassis as _chassis from openstack.baremetal.v1 import driver as _driver from openstack.baremetal.v1 import node as _node from openstack.baremetal.v1 import port as _port from open...
openstack/baremetal/v1/_proxy.py
from openstack.baremetal.v1 import _common from openstack.baremetal.v1 import allocation as _allocation from openstack.baremetal.v1 import chassis as _chassis from openstack.baremetal.v1 import driver as _driver from openstack.baremetal.v1 import node as _node from openstack.baremetal.v1 import port as _port from open...
0.854869
0.383295
from PyQt5.QtCore import QObject, pyqtSignal, QTimer from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog from functools import partial from PyQt5.QtGui import QIcon, QTextCursor from .uicore import UI from core import getPortList, myserial import time class MySignals(QObject): # 定义一种信号,两个参数 类型分别是: QTex...
ui/mainwindow.py
from PyQt5.QtCore import QObject, pyqtSignal, QTimer from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog from functools import partial from PyQt5.QtGui import QIcon, QTextCursor from .uicore import UI from core import getPortList, myserial import time class MySignals(QObject): # 定义一种信号,两个参数 类型分别是: QTex...
0.187467
0.064065
from typing import Optional, Type from mautrix.util.config import BaseProxyConfig, ConfigUpdateHelper from maubot import Plugin, MessageEvent from maubot.handlers import command import json import datetime class Config(BaseProxyConfig): def do_update(self, helper: ConfigUpdateHelper) -> None: helper.copy...
invite.py
from typing import Optional, Type from mautrix.util.config import BaseProxyConfig, ConfigUpdateHelper from maubot import Plugin, MessageEvent from maubot.handlers import command import json import datetime class Config(BaseProxyConfig): def do_update(self, helper: ConfigUpdateHelper) -> None: helper.copy...
0.624752
0.113236
from types import FunctionType import pkgutil BUILD_DIR = 'generated' CLASS_OPTIONS = [':show-inheritance:', ':members:', ':special-members:', ':exclude-members: __init__, __weakref__'] FUNCTION_OPTIONS = [] MODULE_OPTIONS = [':show-inheritance:'] def section(name, level=0, section_levels='*=-'): return name ...
docs/source/gen_apidoc.py
from types import FunctionType import pkgutil BUILD_DIR = 'generated' CLASS_OPTIONS = [':show-inheritance:', ':members:', ':special-members:', ':exclude-members: __init__, __weakref__'] FUNCTION_OPTIONS = [] MODULE_OPTIONS = [':show-inheritance:'] def section(name, level=0, section_levels='*=-'): return name ...
0.330147
0.070913
import os import sys import cmd import shlex import fnmatch import logging import binascii import argparse import traceback import hexdump import speakeasy import speakeasy.winenv.arch as e_arch from speakeasy.errors import SpeakeasyError if sys.platform != 'win32': import readline # noqa (used by cmd) class ...
debugger/debugger.py
import os import sys import cmd import shlex import fnmatch import logging import binascii import argparse import traceback import hexdump import speakeasy import speakeasy.winenv.arch as e_arch from speakeasy.errors import SpeakeasyError if sys.platform != 'win32': import readline # noqa (used by cmd) class ...
0.427158
0.065485