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
from flask import request from assemblyline.common import forge from assemblyline.datastore import SearchException from assemblyline_ui.config import STORAGE from assemblyline_ui.api.base import api_login, make_api_response, make_subapi_blueprint Classification = forge.get_classification() config = forge.get_config(...
assemblyline_ui/api/v4/error.py
from flask import request from assemblyline.common import forge from assemblyline.datastore import SearchException from assemblyline_ui.config import STORAGE from assemblyline_ui.api.base import api_login, make_api_response, make_subapi_blueprint Classification = forge.get_classification() config = forge.get_config(...
0.581541
0.101857
from . import AWSHelperFn, AWSObject, AWSProperty from .validators import boolean, integer, positive_integer EC2_INSTANCE_LAUNCH = "autoscaling:EC2_INSTANCE_LAUNCH" EC2_INSTANCE_LAUNCH_ERROR = "autoscaling:EC2_INSTANCE_LAUNCH_ERROR" EC2_INSTANCE_TERMINATE = "autoscaling:EC2_INSTANCE_TERMINATE" EC2_INSTANCE_TERMINATE...
troposphere/autoscaling.py
from . import AWSHelperFn, AWSObject, AWSProperty from .validators import boolean, integer, positive_integer EC2_INSTANCE_LAUNCH = "autoscaling:EC2_INSTANCE_LAUNCH" EC2_INSTANCE_LAUNCH_ERROR = "autoscaling:EC2_INSTANCE_LAUNCH_ERROR" EC2_INSTANCE_TERMINATE = "autoscaling:EC2_INSTANCE_TERMINATE" EC2_INSTANCE_TERMINATE...
0.705988
0.106644
def preprocess_chinese(path): pass def read_chinese(path): output_path = path + '_output.txt' content = path + '_sentence.txt' aspect = path + '_target.txt' polarity = path + '_label.txt' fin = open(content, 'r', encoding='utf-8', newline='\n', errors='ignore') reviews = fin.readlines() ...
utils/chinese_preprocess.py
def preprocess_chinese(path): pass def read_chinese(path): output_path = path + '_output.txt' content = path + '_sentence.txt' aspect = path + '_target.txt' polarity = path + '_label.txt' fin = open(content, 'r', encoding='utf-8', newline='\n', errors='ignore') reviews = fin.readlines() ...
0.166472
0.144934
from typing import List from albumcollections import cache from albumcollections.spotify.item.spotify_music import SpotifyAlbum from .spotify_item import SpotifyItem class SpotifyCollection(SpotifyItem): """Class to hold selected information about a spotify collection. Uses database entries associated with ...
albumcollections/spotify/item/spotify_collection.py
from typing import List from albumcollections import cache from albumcollections.spotify.item.spotify_music import SpotifyAlbum from .spotify_item import SpotifyItem class SpotifyCollection(SpotifyItem): """Class to hold selected information about a spotify collection. Uses database entries associated with ...
0.859752
0.19758
import errno import re import sys from threading import Lock import rospy from std_msgs.msg import ( Bool, Empty, ) import baxter_dataflow from baxter_core_msgs.msg import ( AssemblyState, ) from baxter_interface import settings class RobotEnable(object): """ Class RobotEnable - simple contr...
src/baxter_interface/robot_enable.py
import errno import re import sys from threading import Lock import rospy from std_msgs.msg import ( Bool, Empty, ) import baxter_dataflow from baxter_core_msgs.msg import ( AssemblyState, ) from baxter_interface import settings class RobotEnable(object): """ Class RobotEnable - simple contr...
0.5083
0.176991
from pprint import pprint import os, json, requests from bs4 import BeautifulSoup from pathlib import Path class GamePlaylistDownloader(object): """ Download playlist from https://downloads.khinsider.com """ def __init__(self,url,showLog=True): self.url = url self.showLog = showLog self....
mp3_downloader.py
from pprint import pprint import os, json, requests from bs4 import BeautifulSoup from pathlib import Path class GamePlaylistDownloader(object): """ Download playlist from https://downloads.khinsider.com """ def __init__(self,url,showLog=True): self.url = url self.showLog = showLog self....
0.109337
0.048971
import skia import pytest import sys @pytest.fixture def colorinfo(): return skia.ColorInfo( skia.ColorType.kRGBA_8888_ColorType, skia.AlphaType.kPremul_AlphaType, skia.ColorSpace.MakeSRGB()) @pytest.mark.parametrize('args', [ tuple(), ( skia.ColorType.kUnknown_ColorType,...
tests/test_imageinfo.py
import skia import pytest import sys @pytest.fixture def colorinfo(): return skia.ColorInfo( skia.ColorType.kRGBA_8888_ColorType, skia.AlphaType.kPremul_AlphaType, skia.ColorSpace.MakeSRGB()) @pytest.mark.parametrize('args', [ tuple(), ( skia.ColorType.kUnknown_ColorType,...
0.535827
0.759538
import os import time import torch import utils.utils as utils from PIL import Image import cv2 import numpy as np import matplotlib.pyplot as plt import torchvision.transforms ''' Class Evaluator: Simple NN evaluator for object detection. It implements the ability plot real and predicted class and box values. It ...
utils/evaluator.py
import os import time import torch import utils.utils as utils from PIL import Image import cv2 import numpy as np import matplotlib.pyplot as plt import torchvision.transforms ''' Class Evaluator: Simple NN evaluator for object detection. It implements the ability plot real and predicted class and box values. It ...
0.637369
0.555556
import copy import itertools from enum import Enum from ... import errors as err from .substitutions import create_substitution, substitute_expression from ..formulas import land, lor, Quantifier, QuantifiedFormula, Atom, Tautology, Contradiction, CompoundFormula from .errors import TransformationError class Quantif...
src/tarski/syntax/transform/quantifier_elimination.py
import copy import itertools from enum import Enum from ... import errors as err from .substitutions import create_substitution, substitute_expression from ..formulas import land, lor, Quantifier, QuantifiedFormula, Atom, Tautology, Contradiction, CompoundFormula from .errors import TransformationError class Quantif...
0.693265
0.259998
import asyncio import logging import time import subprocess from datetime import timedelta from discord import Game from discord.ext.commands import Bot, Cog, command, Context from jingler.configuration import pyproject, BASE_DIR from jingler.database.db import Database from jingler.emojis import Emoji STARTUP_TIME ...
jingler/cogs/misc.py
import asyncio import logging import time import subprocess from datetime import timedelta from discord import Game from discord.ext.commands import Bot, Cog, command, Context from jingler.configuration import pyproject, BASE_DIR from jingler.database.db import Database from jingler.emojis import Emoji STARTUP_TIME ...
0.386185
0.059757
import copy import os import unittest import shutil from parameterized import parameterized import tensorflow as tf from opennmt import Runner from opennmt.config import load_model from opennmt.utils import misc from opennmt.tests import test_util test_dir = os.path.dirname(os.path.realpath(__file__)) root_dir = ...
opennmt/tests/runner_test.py
import copy import os import unittest import shutil from parameterized import parameterized import tensorflow as tf from opennmt import Runner from opennmt.config import load_model from opennmt.utils import misc from opennmt.tests import test_util test_dir = os.path.dirname(os.path.realpath(__file__)) root_dir = ...
0.506836
0.352063
from datetime import datetime, timedelta from typing import List from fastapi import APIRouter, Depends from fastapi import HTTPException from tracardi.service.storage.driver import storage from tracardi.service.storage.factory import StorageFor, StorageForBulk, storage_manager from tracardi.domain.record.event_debug...
app/api/event_endpoint.py
from datetime import datetime, timedelta from typing import List from fastapi import APIRouter, Depends from fastapi import HTTPException from tracardi.service.storage.driver import storage from tracardi.service.storage.factory import StorageFor, StorageForBulk, storage_manager from tracardi.domain.record.event_debug...
0.426083
0.124612
import numpy as np from scipy import linalg def helmert(pos1, pos2, Q, n): pt1 = np.hsplit(pos1[0:3 * n], n) pt2 = np.hsplit(pos2[0:3 * n], n) e = np.matrix(np.ones(n)).T sig = np.identity(3) # outlier loop start i = 0 # iterator preventing infinite loops tst2 = np.array([7]) # loop st...
helmert_comp.py
import numpy as np from scipy import linalg def helmert(pos1, pos2, Q, n): pt1 = np.hsplit(pos1[0:3 * n], n) pt2 = np.hsplit(pos2[0:3 * n], n) e = np.matrix(np.ones(n)).T sig = np.identity(3) # outlier loop start i = 0 # iterator preventing infinite loops tst2 = np.array([7]) # loop st...
0.361165
0.617599
import pytest from eventlet import GreenPool, sleep from eventlet.event import Event import nameko.rpc from nameko.containers import ServiceContainer from nameko.rpc import Rpc, rpc from nameko.testing.services import get_extension from nameko.utils import ( REDACTED, fail_fast_imap, get_redacted_args, import_fro...
nameko/test/utils/test_utils.py
import pytest from eventlet import GreenPool, sleep from eventlet.event import Event import nameko.rpc from nameko.containers import ServiceContainer from nameko.rpc import Rpc, rpc from nameko.testing.services import get_extension from nameko.utils import ( REDACTED, fail_fast_imap, get_redacted_args, import_fro...
0.560012
0.391057
from __future__ import annotations # Bokeh imports from .action import FAILED, PASSED, ActionReturn from .config import Config from .system import System __all__ = ( "publish_conda_package", "publish_documentation", "publish_npm_package", "publish_pip_packages", "unpack_deployment_tarball", ) CLO...
release/deploy.py
from __future__ import annotations # Bokeh imports from .action import FAILED, PASSED, ActionReturn from .config import Config from .system import System __all__ = ( "publish_conda_package", "publish_documentation", "publish_npm_package", "publish_pip_packages", "unpack_deployment_tarball", ) CLO...
0.569374
0.085633
"""Wrapper script for oclint""" import os from hooks.utils import StaticAnalyzerCmd class OCLintCmd(StaticAnalyzerCmd): """Class for the OCLint command.""" command = "oclint" lookbehind = "OCLint version " def __init__(self, args): super().__init__(self.command, self.lookbehind, args) ...
hooks/oclint.py
"""Wrapper script for oclint""" import os from hooks.utils import StaticAnalyzerCmd class OCLintCmd(StaticAnalyzerCmd): """Class for the OCLint command.""" command = "oclint" lookbehind = "OCLint version " def __init__(self, args): super().__init__(self.command, self.lookbehind, args) ...
0.619932
0.127979
import youtube_dl import os import threading import logging import json import requests import hot logger = logging.getLogger("RaspberryCast") volume = 0 def launchvideo(url, config, sub=False): setState("2") os.system("echo -n q > /tmp/cmd &") # Kill previous instance of OMX if config["new_log"]: ...
process.py
import youtube_dl import os import threading import logging import json import requests import hot logger = logging.getLogger("RaspberryCast") volume = 0 def launchvideo(url, config, sub=False): setState("2") os.system("echo -n q > /tmp/cmd &") # Kill previous instance of OMX if config["new_log"]: ...
0.219756
0.0686
import contextlib import sys import logging import time import itertools from .config import config from .exceptions import MaxWhileTries log = logging.getLogger(__name__) @contextlib.contextmanager def nested(*managers): """ Like contextlib.nested but takes callables returning context managers, to avoid...
teuthology/contextutil.py
import contextlib import sys import logging import time import itertools from .config import config from .exceptions import MaxWhileTries log = logging.getLogger(__name__) @contextlib.contextmanager def nested(*managers): """ Like contextlib.nested but takes callables returning context managers, to avoid...
0.35354
0.133528
import logging from typing import Dict, List, Type, Any, Union, Sequence from importlib import import_module import attr import pydocspec from . import brains, _model @attr.s(auto_attribs=True) class GenericFactory: bases: Dict[str, Type[Any]] mixins: Dict[str, List[Type[Any]]] = attr.ib(factory=dict) de...
pydocspec/specfactory.py
import logging from typing import Dict, List, Type, Any, Union, Sequence from importlib import import_module import attr import pydocspec from . import brains, _model @attr.s(auto_attribs=True) class GenericFactory: bases: Dict[str, Type[Any]] mixins: Dict[str, List[Type[Any]]] = attr.ib(factory=dict) de...
0.811639
0.432603
"""Process Entity class.""" from datetime import datetime from typing import Any, Mapping, Optional from ..._version import VERSION from ...common.utility import export from .entity import Entity from .account import Account from .entity_enums import ElevationToken from .file import File from .host import Host from .h...
msticpy/datamodel/entities/process.py
"""Process Entity class.""" from datetime import datetime from typing import Any, Mapping, Optional from ..._version import VERSION from ...common.utility import export from .entity import Entity from .account import Account from .entity_enums import ElevationToken from .file import File from .host import Host from .h...
0.906514
0.130867
import logging from hashlib import sha1 from django.core.cache import caches from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ import requests from requests.exceptions import Timeout, HTTPError from zxcvbn import zxcvbn logger = logging.getLogger('kompassi') MINIMUM...
core/utils/password_utils.py
import logging from hashlib import sha1 from django.core.cache import caches from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ import requests from requests.exceptions import Timeout, HTTPError from zxcvbn import zxcvbn logger = logging.getLogger('kompassi') MINIMUM...
0.555194
0.257392
from __future__ import absolute_import, division from packaging.version import Version import numpy as np from toolz import memoize from datashader.glyphs.glyph import Glyph from datashader.utils import isreal, ngjit from numba import cuda try: import cudf from ..transfer_functions._cuda_utils import cuda_ar...
datashader/glyphs/points.py
from __future__ import absolute_import, division from packaging.version import Version import numpy as np from toolz import memoize from datashader.glyphs.glyph import Glyph from datashader.utils import isreal, ngjit from numba import cuda try: import cudf from ..transfer_functions._cuda_utils import cuda_ar...
0.828592
0.315749
import sequence_diagrams try: SD_loaded reload(sequence_diagrams) except: SD_loaded = True from sequence_diagrams import * import theme.colors as thc import theme.figure_settings as tfs import argparse parser = argparse.ArgumentParser(description="Generate pulse sequence acquisitions.") parser.add_argum...
figures/scripts/t1_sequence.py
import sequence_diagrams try: SD_loaded reload(sequence_diagrams) except: SD_loaded = True from sequence_diagrams import * import theme.colors as thc import theme.figure_settings as tfs import argparse parser = argparse.ArgumentParser(description="Generate pulse sequence acquisitions.") parser.add_argum...
0.410638
0.205914
import sys import os import torch import torch.nn as nn import torch.nn.functional as F from torchinfo import summary sys.path.append(os.getcwd()) from module.complex_conv2d import ComplexConv2d from module.complex_lstm import ComplexLSTM from module.complex_conv_transpose2d import ComplexConvTranspose2d from audio.u...
module/dc_crn.py
import sys import os import torch import torch.nn as nn import torch.nn.functional as F from torchinfo import summary sys.path.append(os.getcwd()) from module.complex_conv2d import ComplexConv2d from module.complex_lstm import ComplexLSTM from module.complex_conv_transpose2d import ComplexConvTranspose2d from audio.u...
0.757346
0.377053
import sys, logging, open_color, arcade #check to make sure we are running the right version of Python version = (3,7) assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1]) #turn on logging, in case we have to leave ourselves debugging messages logging.basicC...
main.py
import sys, logging, open_color, arcade #check to make sure we are running the right version of Python version = (3,7) assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1]) #turn on logging, in case we have to leave ourselves debugging messages logging.basicC...
0.348978
0.385143
import numpy as np import matplotlib.pyplot as plt import csv import datetime as dt import matplotlib.dates as mdates t = [] a = [] b = [] c = [] real = [] with open('data.tsv','r') as csvfile: rows = csv.DictReader(csvfile, delimiter="\t") for row in rows: tiempo = row['Fecha'] tiempo = dt.da...
csvToPlotInteractivo.py
import numpy as np import matplotlib.pyplot as plt import csv import datetime as dt import matplotlib.dates as mdates t = [] a = [] b = [] c = [] real = [] with open('data.tsv','r') as csvfile: rows = csv.DictReader(csvfile, delimiter="\t") for row in rows: tiempo = row['Fecha'] tiempo = dt.da...
0.380183
0.451206
import numpy as np from abc import abstractmethod class Scaler(object): @abstractmethod def fit(self, records): pass @abstractmethod def fit_scaling(self, records): pass @abstractmethod def scaling(self, records): pass @abstractmethod def inverse_scaling(sel...
preprocess/scaler.py
import numpy as np from abc import abstractmethod class Scaler(object): @abstractmethod def fit(self, records): pass @abstractmethod def fit_scaling(self, records): pass @abstractmethod def scaling(self, records): pass @abstractmethod def inverse_scaling(sel...
0.886014
0.290798
from pymtl3 import * from pymtl3.stdlib.basic_rtl import Mux, Reg, RegEn, RegisterFile from pymtl3.stdlib.ifcs import InValRdyIfc, OutValRdyIfc class PipeQueue1RTL( Component ): def construct( s, Type ): s.enq = InValRdyIfc ( Type ) s.deq = OutValRdyIfc( Type ) s.buffer = m = RegEn( Type ) m.out /...
pymtl3/stdlib/queues/valrdy_queues.py
from pymtl3 import * from pymtl3.stdlib.basic_rtl import Mux, Reg, RegEn, RegisterFile from pymtl3.stdlib.ifcs import InValRdyIfc, OutValRdyIfc class PipeQueue1RTL( Component ): def construct( s, Type ): s.enq = InValRdyIfc ( Type ) s.deq = OutValRdyIfc( Type ) s.buffer = m = RegEn( Type ) m.out /...
0.380414
0.168412
from __future__ import unicode_literals from .once import OnceIE from ..compat import compat_urllib_parse_unquote class GameSpotIE(OnceIE): _VALID_URL = r"https?://(?:www\.)?gamespot\.com/(?:video|article|review)s/(?:[^/]+/\d+-|embed/)(?P<id>\d+)" _TESTS = [ { "url": "http://www.gamespot....
youtuatools/extractor/gamespot.py
from __future__ import unicode_literals from .once import OnceIE from ..compat import compat_urllib_parse_unquote class GameSpotIE(OnceIE): _VALID_URL = r"https?://(?:www\.)?gamespot\.com/(?:video|article|review)s/(?:[^/]+/\d+-|embed/)(?P<id>\d+)" _TESTS = [ { "url": "http://www.gamespot....
0.547222
0.249985
================================================================ A Robot moves in a Plane starting from the origin point (0,0). The robot can move toward UP, DOWN, LEFT, RIGHT. The trace of Robot movement is as given following: Assumed the fixed movements: UP 5 DOWN 3 LEFT 3 RIGHT 2 The numbers after directions ar...
distance_by_coordinate_positions_of_robot_movements.py
================================================================ A Robot moves in a Plane starting from the origin point (0,0). The robot can move toward UP, DOWN, LEFT, RIGHT. The trace of Robot movement is as given following: Assumed the fixed movements: UP 5 DOWN 3 LEFT 3 RIGHT 2 The numbers after directions ar...
0.694199
0.698574
from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.template import loader from django.db import connection from django.http import HttpResponseRedirect import datetime from dj...
administrator/views.py
from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.template import loader from django.db import connection from django.http import HttpResponseRedirect import datetime from dj...
0.389663
0.077274
from SPARQLWrapper import SPARQLWrapper, JSON class KBHelper: def __init__(self, endpoint): self.endpoint = endpoint self.sparql = SPARQLWrapper(self.endpoint) def query_relatedSymptom(self, disease_name): sparql_tem = """ SELECT ?object_name WHERE { ...
app/doctor_bot/ontology/kb_helper.py
from SPARQLWrapper import SPARQLWrapper, JSON class KBHelper: def __init__(self, endpoint): self.endpoint = endpoint self.sparql = SPARQLWrapper(self.endpoint) def query_relatedSymptom(self, disease_name): sparql_tem = """ SELECT ?object_name WHERE { ...
0.508788
0.075176
from indicators.trend_indicators import exponential_moving_average def average_true_range(df, target, period): """ Function to compute Average True Range (ATR) This is a lagging indicator df - the data frame target - column name to store output period - period of the atr """ base = 'T...
indicators/volatility_indicator.py
from indicators.trend_indicators import exponential_moving_average def average_true_range(df, target, period): """ Function to compute Average True Range (ATR) This is a lagging indicator df - the data frame target - column name to store output period - period of the atr """ base = 'T...
0.873902
0.593845
import os, sys import errno from pprint import pprint import string import unittest from test_all import db, test_support, verbose, get_new_environment_path, get_new_database_path #---------------------------------------------------------------------- class SimpleRecnoTestCase(unittest.TestCase): if sys.versio...
Lib/bsddb/test/test_recno.py
import os, sys import errno from pprint import pprint import string import unittest from test_all import db, test_support, verbose, get_new_environment_path, get_new_database_path #---------------------------------------------------------------------- class SimpleRecnoTestCase(unittest.TestCase): if sys.versio...
0.199464
0.26019
import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TO...
models.py
import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() ## TO...
0.822653
0.65624
import logging from workflows.arlexecute.imaging.imaging_arlexecute import zero_list_arlexecute_workflow, \ predict_list_arlexecute_workflow from wrappers.arlexecute.execution_support.arlexecute import arlexecute from wrappers.arlexecute.imaging.base import predict_skycomponent_visibility from wrappers.arlexecute....
workflows/arlexecute/skymodel/skymodel_arlexecute.py
import logging from workflows.arlexecute.imaging.imaging_arlexecute import zero_list_arlexecute_workflow, \ predict_list_arlexecute_workflow from wrappers.arlexecute.execution_support.arlexecute import arlexecute from wrappers.arlexecute.imaging.base import predict_skycomponent_visibility from wrappers.arlexecute....
0.707101
0.468791
from aiorecollect.errors import RecollectError from homeassistant import data_entry_flow from homeassistant.components.recollect_waste import ( CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, ) from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from tests.async_mock import patch from tests.common...
tests/components/recollect_waste/test_config_flow.py
from aiorecollect.errors import RecollectError from homeassistant import data_entry_flow from homeassistant.components.recollect_waste import ( CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, ) from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from tests.async_mock import patch from tests.common...
0.744935
0.407923
import ck.kernel as ck import copy import re import argparse # Platform tag. platform_tags='nvidia-tx1' # Batch size. bs={ 'start':1, 'stop':8, 'step':1, 'default':1 } # Number of statistical repetitions e.g. 3. num_repetitions=3 # Number of batches to run (the first is to be discarded) e.g. 5. num_batches...
program/image-classification-tf-py/benchmark.nvidia-tx1.py
import ck.kernel as ck import copy import re import argparse # Platform tag. platform_tags='nvidia-tx1' # Batch size. bs={ 'start':1, 'stop':8, 'step':1, 'default':1 } # Number of statistical repetitions e.g. 3. num_repetitions=3 # Number of batches to run (the first is to be discarded) e.g. 5. num_batches...
0.442155
0.144149
import logging import dlib from multiprocessing import Pool name_list = list() d_trackers = list() class ReusablePool: """ Manage reusable tracker objects for use by client. """ def __init__(self, size): logging.debug('Creating ' + str(size) + ' trackers!') self._reusables = [dlib.co...
faceR/tracking/dlib_tracking.py
import logging import dlib from multiprocessing import Pool name_list = list() d_trackers = list() class ReusablePool: """ Manage reusable tracker objects for use by client. """ def __init__(self, size): logging.debug('Creating ' + str(size) + ' trackers!') self._reusables = [dlib.co...
0.432543
0.238284
import logging from discord.ext import commands from random import choice log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setFormatter(logging.Formatter('[%(asctime)s - %(name)s - %(levelname)s] %(message)s')) log.addHandler(stream_handler) REGIONA...
UnusedCogs/movie_poll.py
import logging from discord.ext import commands from random import choice log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setFormatter(logging.Formatter('[%(asctime)s - %(name)s - %(levelname)s] %(message)s')) log.addHandler(stream_handler) REGIONA...
0.118309
0.080069
import traceback from logging import getLogger from functools import wraps from time import time from flask import request from flask.wrappers import Response from werkzeug.datastructures import Headers from ggrc import db from ggrc import settings from ggrc.login import get_current_user from ggrc.models.mixins impor...
src/ggrc/models/background_task.py
import traceback from logging import getLogger from functools import wraps from time import time from flask import request from flask.wrappers import Response from werkzeug.datastructures import Headers from ggrc import db from ggrc import settings from ggrc.login import get_current_user from ggrc.models.mixins impor...
0.557845
0.083591
from unittest.mock import Mock import pytket as tk from pytket.circuit import Bit, Qubit # pylint: disable=no-name-in-module from pytket.utils import probs_from_counts from discopy import messages from discopy.quantum.circuit import ( Functor, Id, bit, qubit, Discard, Measure) from discopy.quantum.gates import (...
discopy/quantum/tk.py
from unittest.mock import Mock import pytket as tk from pytket.circuit import Bit, Qubit # pylint: disable=no-name-in-module from pytket.utils import probs_from_counts from discopy import messages from discopy.quantum.circuit import ( Functor, Id, bit, qubit, Discard, Measure) from discopy.quantum.gates import (...
0.862916
0.580055
def gen(i,j,c): return j+1+(i*c) def cUp(m,i,j): return (m[i-1][j]!="#") def cRight(m,i,j): return (m[i][j+1]!="#") def cDown(m,i,j): return (m[i+1][j]!="#") def cLeft(m,i,j): return (m[i][j-1]!="#") def getAdjecencyList(m,r,c): g={} for i in range(0,r): for j in ran...
PrinceOfPersia2.py
def gen(i,j,c): return j+1+(i*c) def cUp(m,i,j): return (m[i-1][j]!="#") def cRight(m,i,j): return (m[i][j+1]!="#") def cDown(m,i,j): return (m[i+1][j]!="#") def cLeft(m,i,j): return (m[i][j-1]!="#") def getAdjecencyList(m,r,c): g={} for i in range(0,r): for j in ran...
0.035103
0.112576
import sys import os import getopt import subprocess import glob import imp def usage(): '''Print usage information for the program''' argv0 = basename(sys.argv[0]) print(""" Usage: ------ %(argv0)s [options] [config_name] Where config_name is the one of the defined configuration files if no config file is ...
tools/run.py
import sys import os import getopt import subprocess import glob import imp def usage(): '''Print usage information for the program''' argv0 = basename(sys.argv[0]) print(""" Usage: ------ %(argv0)s [options] [config_name] Where config_name is the one of the defined configuration files if no config file is ...
0.229104
0.119639
import numpy as np from .model import Model from ..util.util import sigmoid, add_intersect class LogisticRegression(Model): def __init__(self, gd=False, epochs=1000, lr=0.001): """Linear regression Model epochs: number of epochs lr: learning rate for GD """ super(LogisticRegression, self).__init__() se...
src/si/supervised/logreg.py
import numpy as np from .model import Model from ..util.util import sigmoid, add_intersect class LogisticRegression(Model): def __init__(self, gd=False, epochs=1000, lr=0.001): """Linear regression Model epochs: number of epochs lr: learning rate for GD """ super(LogisticRegression, self).__init__() se...
0.66072
0.59355
import sys, os import unreal_engine as ue from unreal_engine import UObject, FVector, FRotator, FTransform, FColor, FLinearColor from unreal_engine.classes import Pawn import traceback def log(*args): print(' '.join(str(x) for x in args)) def logTB(): for line in traceback.format_exc().split('\n'): lo...
output_params/Content/Scripts/helpers.py
import sys, os import unreal_engine as ue from unreal_engine import UObject, FVector, FRotator, FTransform, FColor, FLinearColor from unreal_engine.classes import Pawn import traceback def log(*args): print(' '.join(str(x) for x in args)) def logTB(): for line in traceback.format_exc().split('\n'): lo...
0.212069
0.19129
"""A basic example for using the signature API.""" # [START signature-basic-example] import tink from tink import cleartext_keyset_handle from tink import signature def example(): """Sign and verify using digital signatures.""" # Register the signature key managers. This is needed to create # PublicKeySign and ...
examples/python/signature/signature_basic.py
"""A basic example for using the signature API.""" # [START signature-basic-example] import tink from tink import cleartext_keyset_handle from tink import signature def example(): """Sign and verify using digital signatures.""" # Register the signature key managers. This is needed to create # PublicKeySign and ...
0.872402
0.351158
from __future__ import print_function from __future__ import division from __future__ import absolute_import import ironicclient.v1.chassis as IrChassis import ironicclient.v1.driver as IrDriver import ironicclient.v1.node as IrNode import ironicclient.v1.port as IrPort import mock from congress.datasources import i...
congress/tests/datasources/test_ironic_driver.py
from __future__ import print_function from __future__ import division from __future__ import absolute_import import ironicclient.v1.chassis as IrChassis import ironicclient.v1.driver as IrDriver import ironicclient.v1.node as IrNode import ironicclient.v1.port as IrPort import mock from congress.datasources import i...
0.520984
0.18279
from typing import TYPE_CHECKING from azure.core import PipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Optional from azure.core.credentials import TokenCredential from ._configuration import EntitySe...
sdk/EntitySearch/entity_search_client/_entity_search_client.py
from typing import TYPE_CHECKING from azure.core import PipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Optional from azure.core.credentials import TokenCredential from ._configuration import EntitySe...
0.779028
0.104569
from __future__ import absolute_import, division, print_function, unicode_literals import functools import unittest from builtins import range from pants.engine.nodes import Return _WAITING = 'TODO: Waiting' @unittest.skip('Skipped to expedite landing #3821; see: #4027.') class GraphTest(unittest.TestCase): d...
tests/python/pants_test/engine/test_graph.py
from __future__ import absolute_import, division, print_function, unicode_literals import functools import unittest from builtins import range from pants.engine.nodes import Return _WAITING = 'TODO: Waiting' @unittest.skip('Skipped to expedite landing #3821; see: #4027.') class GraphTest(unittest.TestCase): d...
0.63409
0.330552
from soccer.data import LEAGUE_PROPERTIES, LEAGUE_NAMES from . import BaseWriter import click import json import io __all__ = ['Stdout', 'Fstdout', 'Fjson', 'Json'] class Stdout(BaseWriter): def __init__(self, output_file): enums = dict( CL_POSITION="green", EL_POSITION="yellow", ...
soccer/writers/writers.py
from soccer.data import LEAGUE_PROPERTIES, LEAGUE_NAMES from . import BaseWriter import click import json import io __all__ = ['Stdout', 'Fstdout', 'Fjson', 'Json'] class Stdout(BaseWriter): def __init__(self, output_file): enums = dict( CL_POSITION="green", EL_POSITION="yellow", ...
0.209268
0.151498
import falcon from falcon_redis_cache.hooks import CacheProvider from falcon_redis_cache.utils import clear_resource_cache from blog.core.comments import get_comment, edit_comment, delete_comment, comment_to_dto, \ like_comment from blog.db import Comment, User from blog.errors import UnauthorizedRequestError from ...
blog/resources/comments.py
import falcon from falcon_redis_cache.hooks import CacheProvider from falcon_redis_cache.utils import clear_resource_cache from blog.core.comments import get_comment, edit_comment, delete_comment, comment_to_dto, \ like_comment from blog.db import Comment, User from blog.errors import UnauthorizedRequestError from ...
0.469034
0.100657
import pygame from random import randrange, randint from itertools import cycle pygame.init() # Colors COLOR_LIGHT_GREY = (230, 230, 230) COLOR_LIGHT_BLUE = (51, 153, 255) # Window window = (960, 720) center = (window[0] // 2, window[1] // 2) screen = pygame.display.set_mode(window) pygame.display.set_caption("PySna...
snake/main.py
import pygame from random import randrange, randint from itertools import cycle pygame.init() # Colors COLOR_LIGHT_GREY = (230, 230, 230) COLOR_LIGHT_BLUE = (51, 153, 255) # Window window = (960, 720) center = (window[0] // 2, window[1] // 2) screen = pygame.display.set_mode(window) pygame.display.set_caption("PySna...
0.438064
0.182498
from typing import Optional, Tuple import numpy as np from scipy.special import gammaln from scipy.special import psi from scipy.special import factorial from scipy.optimize import fmin_l_bfgs_b as optim from numbers import Number def fit_nbinom( X: np.ndarray, initial_params: Optional[Tuple[Number, Number]] = No...
scirpy/util/_negative_binomial.py
from typing import Optional, Tuple import numpy as np from scipy.special import gammaln from scipy.special import psi from scipy.special import factorial from scipy.optimize import fmin_l_bfgs_b as optim from numbers import Number def fit_nbinom( X: np.ndarray, initial_params: Optional[Tuple[Number, Number]] = No...
0.930474
0.543227
import oneflow as flow from oneflow.python.framework.tensor import Tensor from oneflow.python.oneflow_export import oneflow_export from oneflow.python.nn.module import Module from typing import Optional, List, Tuple @oneflow_export("nn.Embedding") class Embedding(Module): r"""A simple lookup table that stores e...
oneflow/python/nn/modules/sparse.py
import oneflow as flow from oneflow.python.framework.tensor import Tensor from oneflow.python.oneflow_export import oneflow_export from oneflow.python.nn.module import Module from typing import Optional, List, Tuple @oneflow_export("nn.Embedding") class Embedding(Module): r"""A simple lookup table that stores e...
0.920469
0.618118
import phantom.app as phantom from phantom.action_result import ActionResult from digital_shadows_consts import DS_API_KEY_CFG, DS_API_SECRET_KEY_CFG, DS_LOOKUP_USERNAME_NOT_FOUND, DS_LOOKUP_USERNAME_SUCCESS from dsapi.service.data_breach_username_service import DataBreachUsernameService class DSLookupUsernameConne...
ds_lookup_username_connector.py
import phantom.app as phantom from phantom.action_result import ActionResult from digital_shadows_consts import DS_API_KEY_CFG, DS_API_SECRET_KEY_CFG, DS_LOOKUP_USERNAME_NOT_FOUND, DS_LOOKUP_USERNAME_SUCCESS from dsapi.service.data_breach_username_service import DataBreachUsernameService class DSLookupUsernameConne...
0.637708
0.127354
"""Client and server classes corresponding to protobuf-defined services.""" import grpc from yandex.cloud.mdb.kafka.v1 import connector_pb2 as yandex_dot_cloud_dot_mdb_dot_kafka_dot_v1_dot_connector__pb2 from yandex.cloud.mdb.kafka.v1 import connector_service_pb2 as yandex_dot_cloud_dot_mdb_dot_kafka_dot_v1_dot_connec...
yandex/cloud/mdb/kafka/v1/connector_service_pb2_grpc.py
"""Client and server classes corresponding to protobuf-defined services.""" import grpc from yandex.cloud.mdb.kafka.v1 import connector_pb2 as yandex_dot_cloud_dot_mdb_dot_kafka_dot_v1_dot_connector__pb2 from yandex.cloud.mdb.kafka.v1 import connector_service_pb2 as yandex_dot_cloud_dot_mdb_dot_kafka_dot_v1_dot_connec...
0.772402
0.135204
from urllib.parse import urlencode import requests import time from airflow.hooks.base_hook import BaseHook class FacebookAdsHook(BaseHook): def __init__(self, facebook_ads_conn_id="facebook_ads_default"): self.facebook_ads_conn_id = facebook_ads_conn_id self.connection = self.get_connection(face...
hooks/facebook_ads_hook.py
from urllib.parse import urlencode import requests import time from airflow.hooks.base_hook import BaseHook class FacebookAdsHook(BaseHook): def __init__(self, facebook_ads_conn_id="facebook_ads_default"): self.facebook_ads_conn_id = facebook_ads_conn_id self.connection = self.get_connection(face...
0.431105
0.080937
import detl from detl.processor import load_and_save, identity_wrapper, Processor, change_state from detl.mydb import MyDb import shutil import os from test_util import save_int, load_int import unittest import pytest from detl.wrapper import wrap_obj, wrap_results class DecoratorTest(unittest.TestCase): @pytest....
tests/test_processors.py
import detl from detl.processor import load_and_save, identity_wrapper, Processor, change_state from detl.mydb import MyDb import shutil import os from test_util import save_int, load_int import unittest import pytest from detl.wrapper import wrap_obj, wrap_results class DecoratorTest(unittest.TestCase): @pytest....
0.367951
0.408277
import re from django.db.models import Q from django.core.validators import ValidationError from django.forms import ModelForm, Form, BooleanField, CharField, ChoiceField, PasswordInput from django.forms.widgets import TextInput from django.utils.translation import ugettext_lazy as _ from rr.models.attribute import A...
rr/forms/testuser.py
import re from django.db.models import Q from django.core.validators import ValidationError from django.forms import ModelForm, Form, BooleanField, CharField, ChoiceField, PasswordInput from django.forms.widgets import TextInput from django.utils.translation import ugettext_lazy as _ from rr.models.attribute import A...
0.45641
0.139866
import argparse import os import re import sys def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "input", metavar="FTOPTION_H", help="Path to input ftoption.h file." ) parser.add_argument("--output", help="Output to file instead of stdout.") parser.a...
thirdparty/freetype/builds/meson/process_ftoption_h.py
import argparse import os import re import sys def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "input", metavar="FTOPTION_H", help="Path to input ftoption.h file." ) parser.add_argument("--output", help="Output to file instead of stdout.") parser.a...
0.233532
0.095265
from __future__ import print_function import unittest import json from bs4 import BeautifulSoup from knowledge_repo import KnowledgeRepository from knowledge_repo.app.models import Comment, Post, User from knowledge_repo.app.proxies import db_session class CommentTest(unittest.TestCase): def setUp(self): ...
tests/test_comments.py
from __future__ import print_function import unittest import json from bs4 import BeautifulSoup from knowledge_repo import KnowledgeRepository from knowledge_repo.app.models import Comment, Post, User from knowledge_repo.app.proxies import db_session class CommentTest(unittest.TestCase): def setUp(self): ...
0.494385
0.180901
import utils import dbs import bson import sys, traceback import pymongo from config import * from pymongo import UpdateOne class PublishConverter: def __init__(self, publish_db, cache_period = 10000): self.childcount_dict = {} self.update_list = [] self.publish_db = publish_db self...
scripts/update_childcount.py
import utils import dbs import bson import sys, traceback import pymongo from config import * from pymongo import UpdateOne class PublishConverter: def __init__(self, publish_db, cache_period = 10000): self.childcount_dict = {} self.update_list = [] self.publish_db = publish_db self...
0.102507
0.122366
from kervi.controllers import Controller from kervi.values import NumberValue from mockup_spine import MockupSpine from kervi_config import get_test_config class XController(Controller): def __init__(self, **kwargs): Controller.__init__(self, "test_controller", "Test controller", **kwargs) self.inp...
kervi-core/tests/test_controller.py
from kervi.controllers import Controller from kervi.values import NumberValue from mockup_spine import MockupSpine from kervi_config import get_test_config class XController(Controller): def __init__(self, **kwargs): Controller.__init__(self, "test_controller", "Test controller", **kwargs) self.inp...
0.688887
0.271264
from oslo_config import cfg default_message_ttl = cfg.IntOpt( 'default_message_ttl', default=3600, help='Defines how long a message will be accessible.') default_message_delay = cfg.IntOpt( 'default_message_delay', default=0, help=('Defines the defautl value for queue delay seconds.' 'The ...
zaqar-8.0.0/zaqar/conf/transport.py
from oslo_config import cfg default_message_ttl = cfg.IntOpt( 'default_message_ttl', default=3600, help='Defines how long a message will be accessible.') default_message_delay = cfg.IntOpt( 'default_message_delay', default=0, help=('Defines the defautl value for queue delay seconds.' 'The ...
0.565779
0.151906
# # Variable Types - Strings (2) # # In the last class we learnt how to create strings, how to convert between string, integers and floats using the <code>str()</code>, <code>int()</code> and <code>float()</code> functions respectively. We also learnt that we can add and multiply strings, but that we cannot divide o...
PlotlyandPython/Lessons/(01) Intro to Python/Notebooks/Python Scripts/(04) Variable Types - Strings (2).py
# # Variable Types - Strings (2) # # In the last class we learnt how to create strings, how to convert between string, integers and floats using the <code>str()</code>, <code>int()</code> and <code>float()</code> functions respectively. We also learnt that we can add and multiply strings, but that we cannot divide o...
0.7586
0.75487
import numpy as np import pytest try: import faiss except ImportError: # pragma: no cover faiss = None from mars import tensor as mt from mars.core import tile from mars.learn.neighbors._faiss import build_faiss_index, _load_index, \ faiss_query, _gen_index_string_and_sample_count from mars.learn.neighbo...
mars/learn/neighbors/tests/test_faiss.py
import numpy as np import pytest try: import faiss except ImportError: # pragma: no cover faiss = None from mars import tensor as mt from mars.core import tile from mars.learn.neighbors._faiss import build_faiss_index, _load_index, \ faiss_query, _gen_index_string_and_sample_count from mars.learn.neighbo...
0.670608
0.674144
from flask import abort, jsonify from flask import g from flask import render_template from flask import request from flask import session from csh import constants from csh import db from csh.disanfang.gongyong import user_pd,news_phb from csh.models import News, Comment, CommentLike, User from csh.modules.news impor...
csh/modules/news/views.py
from flask import abort, jsonify from flask import g from flask import render_template from flask import request from flask import session from csh import constants from csh import db from csh.disanfang.gongyong import user_pd,news_phb from csh.models import News, Comment, CommentLike, User from csh.modules.news impor...
0.139543
0.064535
import pygame import os import threading import time from face import Face from solver import solver_func class UI: def __init__(self, board, piece_size): self.images = {} self.board = board # Size is width x height self.piece_size = piece_size self.board_size = self.piece_...
ui.py
import pygame import os import threading import time from face import Face from solver import solver_func class UI: def __init__(self, board, piece_size): self.images = {} self.board = board # Size is width x height self.piece_size = piece_size self.board_size = self.piece_...
0.3492
0.134577
from urllib.parse import quote_plus import json import jwt from django.views import View from django.views.generic import TemplateView from django.core.exceptions import ValidationError, PermissionDenied from django.conf import settings from django.shortcuts import redirect, render from django.contrib.auth import get...
django_jwtauth/views.py
from urllib.parse import quote_plus import json import jwt from django.views import View from django.views.generic import TemplateView from django.core.exceptions import ValidationError, PermissionDenied from django.conf import settings from django.shortcuts import redirect, render from django.contrib.auth import get...
0.655115
0.105948
from pypy.interpreter import gateway app = gateway.applevel(''' "NOT_RPYTHON" import builtins class fake_code(object): co_name = "?" co_filename = "?" co_firstlineno = 0 class fake_frame(object): f_back = None f_builtins = builtins.__dict__ f_code = fake_code() f_exc_traceback = None ...
pypy/module/sys/currentframes.py
from pypy.interpreter import gateway app = gateway.applevel(''' "NOT_RPYTHON" import builtins class fake_code(object): co_name = "?" co_filename = "?" co_firstlineno = 0 class fake_frame(object): f_back = None f_builtins = builtins.__dict__ f_code = fake_code() f_exc_traceback = None ...
0.654343
0.106226
"""Tests for util.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.lite.python import lite_constants from tensorflow.lite.python import util from tensorflow.lite.toco import types_pb2 as _types_pb2 from tensorflow.python.client import ...
tensorflow/lite/python/util_test.py
"""Tests for util.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.lite.python import lite_constants from tensorflow.lite.python import util from tensorflow.lite.toco import types_pb2 as _types_pb2 from tensorflow.python.client import ...
0.685423
0.566858
from unittest.mock import MagicMock import pytest from wellcomeml.io.epmc.client import EPMCClient @pytest.fixture def epmc_client(): return EPMCClient( max_retries=3 ) def test_search(epmc_client): epmc_client._execute_query = MagicMock() epmc_client.search( "session", "query", res...
tests/io/epmc/test_client.py
from unittest.mock import MagicMock import pytest from wellcomeml.io.epmc.client import EPMCClient @pytest.fixture def epmc_client(): return EPMCClient( max_retries=3 ) def test_search(epmc_client): epmc_client._execute_query = MagicMock() epmc_client.search( "session", "query", res...
0.674372
0.331552
from __future__ import unicode_literals, absolute_import import unittest from whispy_lispy import interpreter2, scopes2 from ..constructors import * class InterpreterTestCase(unittest.TestCase): def test_return_native_int(self): tree = ast.RootAbstractSyntaxNode((ast.Value((types.Int((3, )),)),)) ...
tests/test_interpreter2/__init__.py
from __future__ import unicode_literals, absolute_import import unittest from whispy_lispy import interpreter2, scopes2 from ..constructors import * class InterpreterTestCase(unittest.TestCase): def test_return_native_int(self): tree = ast.RootAbstractSyntaxNode((ast.Value((types.Int((3, )),)),)) ...
0.609059
0.36591
import argparse import logging import numpy as np import tensorflow as tf import tensorflow_addons as tfa import data.datasets3d import options from options import FLAGS def main(): parser = argparse.ArgumentParser() parser.add_argument('--input-model-path', type=str, required=True) parser.add_argument(...
src/scripts/build_multiperson_model.py
import argparse import logging import numpy as np import tensorflow as tf import tensorflow_addons as tfa import data.datasets3d import options from options import FLAGS def main(): parser = argparse.ArgumentParser() parser.add_argument('--input-model-path', type=str, required=True) parser.add_argument(...
0.828454
0.322873
import numpy as onp import pandas as pd from numpyro import distributions as dist from shabadoo import Poisson def test_single_coef_is_about_right(): """Test that a single coef model which has a known value gets there. This is a good round trip test that fitting works. """ # going to make a coe...
test/test_poisson.py
import numpy as onp import pandas as pd from numpyro import distributions as dist from shabadoo import Poisson def test_single_coef_is_about_right(): """Test that a single coef model which has a known value gets there. This is a good round trip test that fitting works. """ # going to make a coe...
0.858807
0.729026
from __future__ import absolute_import import json import os import tempfile import string import sys from nose.tools import assert_equal, assert_false, assert_true, assert_raises, eq_ from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import grant_access, add_to_group, add_pe...
desktop/libs/aws/src/aws/s3/s3fs_test.py
from __future__ import absolute_import import json import os import tempfile import string import sys from nose.tools import assert_equal, assert_false, assert_true, assert_raises, eq_ from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import grant_access, add_to_group, add_pe...
0.37399
0.208642
from django.conf import settings from django.core.management import BaseCommand from django.utils import timezone from django.utils.dateformat import format as format_date from mtp_common.tasks import send_email from core.notify.templates import ApiNotifyTemplates from notification.constants import EMAIL_FREQUENCY fro...
mtp_api/apps/notification/management/commands/send_notification_emails.py
from django.conf import settings from django.core.management import BaseCommand from django.utils import timezone from django.utils.dateformat import format as format_date from mtp_common.tasks import send_email from core.notify.templates import ApiNotifyTemplates from notification.constants import EMAIL_FREQUENCY fro...
0.412648
0.085671
import sys import requests import json from docopt import docopt import utils import transactions import rlp from . import __version__ from . config import read_config config = read_config() api_path = config.get('api', 'api_path') assert api_path.startswith('/') and not api_path.endswith('/') DEFAULT_HOST = config....
pyethereum/ethclient.py
import sys import requests import json from docopt import docopt import utils import transactions import rlp from . import __version__ from . config import read_config config = read_config() api_path = config.get('api', 'api_path') assert api_path.startswith('/') and not api_path.endswith('/') DEFAULT_HOST = config....
0.14013
0.253162
import json import os import torch from torch.utils.data import Dataset, DataLoader from torch.nn.utils.rnn import pad_sequence from transformers import AutoTokenizer from torchfly.text.datasets import Seq2SeqDataset # pylint:disable=no-member class TextRLCollator: def __init__(self, config, tokenizer): ...
Unconditional/TextGAIL/configure_dataloader.py
import json import os import torch from torch.utils.data import Dataset, DataLoader from torch.nn.utils.rnn import pad_sequence from transformers import AutoTokenizer from torchfly.text.datasets import Seq2SeqDataset # pylint:disable=no-member class TextRLCollator: def __init__(self, config, tokenizer): ...
0.719581
0.147248
from collections import defaultdict from dataclasses import dataclass, replace from enum import Enum from functools import lru_cache from typing import ( AbstractSet, Any, Callable, Collection, Dict, List, Mapping, Optional, Pattern, Sequence, Set, Tuple, Type, Ty...
apischema/deserialization/__init__.py
from collections import defaultdict from dataclasses import dataclass, replace from enum import Enum from functools import lru_cache from typing import ( AbstractSet, Any, Callable, Collection, Dict, List, Mapping, Optional, Pattern, Sequence, Set, Tuple, Type, Ty...
0.910503
0.189652
import click from clinicadl.utils import cli_param @click.command(name="save-tensor", no_args_is_help=True) @cli_param.argument.input_maps @cli_param.argument.data_group @click.option( "--caps_directory", type=click.Path(exists=True), default=None, help="Data using CAPS structure, if different from t...
clinicadl/save_tensor/save_tensor_cli.py
import click from clinicadl.utils import cli_param @click.command(name="save-tensor", no_args_is_help=True) @cli_param.argument.input_maps @cli_param.argument.data_group @click.option( "--caps_directory", type=click.Path(exists=True), default=None, help="Data using CAPS structure, if different from t...
0.647798
0.295135
from statistics import mean from typing import Optional from sgj.events_deck import EventsDeck class GameManager: ENERGY_ROUND_CHARGE = 2 def __init__(self, db_filepath: str): self.events_deck = EventsDeck(db_filepath) self.energy_min_max = [0, 100] self.energy = self.energy_min_max...
sgj/game_manager.py
from statistics import mean from typing import Optional from sgj.events_deck import EventsDeck class GameManager: ENERGY_ROUND_CHARGE = 2 def __init__(self, db_filepath: str): self.events_deck = EventsDeck(db_filepath) self.energy_min_max = [0, 100] self.energy = self.energy_min_max...
0.859354
0.217919
from tensortrade.orders import Order, OrderSpec from tensortrade.orders.criteria import Stop, Limit from tensortrade.trades import TradeSide, TradeType def market_order(step: int, side: 'TradeSide', pair: 'TradingPair', price: float, size: float, ...
tensortrade/orders/create.py
from tensortrade.orders import Order, OrderSpec from tensortrade.orders.criteria import Stop, Limit from tensortrade.trades import TradeSide, TradeType def market_order(step: int, side: 'TradeSide', pair: 'TradingPair', price: float, size: float, ...
0.714827
0.36642
from typing import List, Optional, Dict, Union from abc import abstractmethod from pathlib import Path import langdetect from haystack.nodes.base import BaseComponent from haystack.schema import Document # https://en.wikipedia.org/wiki/Ligature_(writing) KNOWN_LIGATURES = { # Latin "ff": "ff", "fi": "fi",...
haystack/nodes/file_converter/base.py
from typing import List, Optional, Dict, Union from abc import abstractmethod from pathlib import Path import langdetect from haystack.nodes.base import BaseComponent from haystack.schema import Document # https://en.wikipedia.org/wiki/Ligature_(writing) KNOWN_LIGATURES = { # Latin "ff": "ff", "fi": "fi",...
0.920057
0.472075
import shodan import sys import re import requests from time import sleep from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # Configuration API_KEY = "YOURAPIKEY" SEARCH_FOR = 'confluence' FILE = "/rest/tinymce/1/macro/preview" s...
Confluence/confluence.py
import shodan import sys import re import requests from time import sleep from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # Configuration API_KEY = "YOURAPIKEY" SEARCH_FOR = 'confluence' FILE = "/rest/tinymce/1/macro/preview" s...
0.092652
0.05498
import json import operator class DC(object): metrics = [] breakpoints = [] bp_values = [] @classmethod def register_metric(cls, metric): cls.metrics.append(metric) @classmethod def register_breakpoint(cls, *args): if len(args) == 1: cls.breakpoints.append(args...
server/utils/dc.py
import json import operator class DC(object): metrics = [] breakpoints = [] bp_values = [] @classmethod def register_metric(cls, metric): cls.metrics.append(metric) @classmethod def register_breakpoint(cls, *args): if len(args) == 1: cls.breakpoints.append(args...
0.697403
0.1929
from Data import Data from ReadConfiguration import ReadConfiguration from ReadData import ReadData from ConstructFeature import ConstructFeature from LoadFeature import LoadFeature from Train import Train import time if __name__ == '__main__': # Step 1 Read Configuration print("=========================...
user_satisfaction_prediction/machine_learning_model/Main.py
from Data import Data from ReadConfiguration import ReadConfiguration from ReadData import ReadData from ConstructFeature import ConstructFeature from LoadFeature import LoadFeature from Train import Train import time if __name__ == '__main__': # Step 1 Read Configuration print("=========================...
0.284775
0.216425
"""Support for "Auth"-related System Backend Methods.""" from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin from hvac.utils import validate_list_of_strings_param, list_to_comma_delimited from hvac import exceptions class Auth(SystemBackendMixin): def list_auth_methods(self): """L...
hvac/api/system_backend/auth.py
"""Support for "Auth"-related System Backend Methods.""" from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin from hvac.utils import validate_list_of_strings_param, list_to_comma_delimited from hvac import exceptions class Auth(SystemBackendMixin): def list_auth_methods(self): """L...
0.755457
0.233138
import pytest import mercantile @pytest.mark.parametrize('args', [ (486, 332, 10), [(486, 332, 10)], [mercantile.Tile(486, 332, 10)]]) def test_ul(args): expected = (-9.140625, 53.33087298301705) lnglat = mercantile.ul(*args) for a, b in zip(expected, lnglat): assert round(a - b, 7) =...
tests/test_funcs.py
import pytest import mercantile @pytest.mark.parametrize('args', [ (486, 332, 10), [(486, 332, 10)], [mercantile.Tile(486, 332, 10)]]) def test_ul(args): expected = (-9.140625, 53.33087298301705) lnglat = mercantile.ul(*args) for a, b in zip(expected, lnglat): assert round(a - b, 7) =...
0.632389
0.802942
import numpy as np import time import os from bark.runtime.commons.parameters import ParameterServer from bark.runtime.viewer.matplotlib_viewer import MPViewer from bark.runtime.viewer.video_renderer import VideoRenderer from bark.runtime.scenario.scenario_generation.config_with_ease import \ LaneCorridorConfig, Con...
examples/merging.py
import numpy as np import time import os from bark.runtime.commons.parameters import ParameterServer from bark.runtime.viewer.matplotlib_viewer import MPViewer from bark.runtime.viewer.video_renderer import VideoRenderer from bark.runtime.scenario.scenario_generation.config_with_ease import \ LaneCorridorConfig, Con...
0.466846
0.163813
import sys _b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@p...
base2designs/protos/ssd_anchor_generator_pb2.py
import sys _b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@p...
0.324449
0.169063
from typing import Dict from allennlp.models.model import Model from allennlp.data.vocabulary import Vocabulary from allennlp.modules.conditional_random_field import ConditionalRandomField, allowed_transitions from transformers.modeling_bert import BertModel, BertForPreTraining, BertConfig from transformers.tokenizati...
ecws/my_library/model/cws_model.py
from typing import Dict from allennlp.models.model import Model from allennlp.data.vocabulary import Vocabulary from allennlp.modules.conditional_random_field import ConditionalRandomField, allowed_transitions from transformers.modeling_bert import BertModel, BertForPreTraining, BertConfig from transformers.tokenizati...
0.757525
0.243991
from pprint import pformat from six import iteritems import re class JobPositionInput(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, position_id=None, incumbent_name=None, type=None, position_open_date=N...
smartrecruiters_python_client/models/job_position_input.py
from pprint import pformat from six import iteritems import re class JobPositionInput(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, position_id=None, incumbent_name=None, type=None, position_open_date=N...
0.833019
0.253659
import numpy as np import os import skimage.io from ..core.base import SyncableDataset from ..core.base import IndexSpec from . import volumetric_utils as vu from ...utils import io_utils as iou from ...utils import python_utils as pyu from ...utils.exceptions import assert_, ShapeError class VolumeLoader(SyncableDa...
inferno/io/volumetric/volume.py
import numpy as np import os import skimage.io from ..core.base import SyncableDataset from ..core.base import IndexSpec from . import volumetric_utils as vu from ...utils import io_utils as iou from ...utils import python_utils as pyu from ...utils.exceptions import assert_, ShapeError class VolumeLoader(SyncableDa...
0.653348
0.340074
import pytest import json from unilyze import Unichar TEST_CHAR = "Ä" u = Unichar() def load_json(filename): with open(filename, "r", encoding="utf-8") as fp: data = fp.read() return data def create_tests(): u = Unichar() raw_info = u.ucd_info_short(TEST_CHAR) with open("tests/testchar...
tests/test_unichar.py
import pytest import json from unilyze import Unichar TEST_CHAR = "Ä" u = Unichar() def load_json(filename): with open(filename, "r", encoding="utf-8") as fp: data = fp.read() return data def create_tests(): u = Unichar() raw_info = u.ucd_info_short(TEST_CHAR) with open("tests/testchar...
0.378689
0.336549
import os import time import numpy as np from bokeh import __version__ as bokeh_release_ver from bokeh.plotting import figure from bokeh.models import ( HoverTool, NumeralTickFormatter ) LOADER = """ #loader { position: absolute; left: 20%; top: 30%; z-index: 1000; border: 1...
app/covid/utilities.py
import os import time import numpy as np from bokeh import __version__ as bokeh_release_ver from bokeh.plotting import figure from bokeh.models import ( HoverTool, NumeralTickFormatter ) LOADER = """ #loader { position: absolute; left: 20%; top: 30%; z-index: 1000; border: 1...
0.644784
0.287529
from mpf.core.config_player import ConfigPlayer from mpf.core.randomizer import Randomizer from mpf.core.utility_functions import Util class RandomEventPlayer(ConfigPlayer): """Plays a random event based on config.""" config_file_section = 'random_event_player' show_section = 'random_events' __slot...
mpf/config_players/random_event_player.py
from mpf.core.config_player import ConfigPlayer from mpf.core.randomizer import Randomizer from mpf.core.utility_functions import Util class RandomEventPlayer(ConfigPlayer): """Plays a random event based on config.""" config_file_section = 'random_event_player' show_section = 'random_events' __slot...
0.785391
0.165189
# Global Imports import time import sys import os import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '127.0.0.1' port = 8080 s.bind((host, port)) print("") print("DanderSpritZ Listening Post is running on",host,":",port) print("") print("Waiting for Targets to connect...") s.listen(1) conn, ad...
src/c2/danderspritz/Server 5.py
# Global Imports import time import sys import os import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '127.0.0.1' port = 8080 s.bind((host, port)) print("") print("DanderSpritZ Listening Post is running on",host,":",port) print("") print("Waiting for Targets to connect...") s.listen(1) conn, ad...
0.161552
0.103976
from hashlib import sha1 from binascii import b2a_base64 from struct import pack # ============================================================================ # ===( MicroWebSrv2 : WebSockets Module )===================================== # ===========================================================================...
MicroWebSrv2/mods/WebSockets.py
from hashlib import sha1 from binascii import b2a_base64 from struct import pack # ============================================================================ # ===( MicroWebSrv2 : WebSockets Module )===================================== # ===========================================================================...
0.476092
0.063279