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 numba import jit class Decoder: ''' Data decoding with lossless compression algorithm (LZW) The class includes the following methods: __init__ - Object Initialization. init_trie - Initializing the trie trie_update - Add item to trie decode ...
LZWCompressor/Decoder.py
from numba import jit class Decoder: ''' Data decoding with lossless compression algorithm (LZW) The class includes the following methods: __init__ - Object Initialization. init_trie - Initializing the trie trie_update - Add item to trie decode ...
0.609408
0.569494
import logging from qpid.util import connect, URL, ssl from qpid.datatypes import Message, uuid4, RangedSet from qpid.connection import Connection from qpid.session import SessionClosed from moksha.hub.amqp.base import BaseAMQPHub log = logging.getLogger('moksha.hub') class QpidAMQPHub(BaseAMQPHub): """ I...
moksha/hub/amqp/qpid010.py
import logging from qpid.util import connect, URL, ssl from qpid.datatypes import Message, uuid4, RangedSet from qpid.connection import Connection from qpid.session import SessionClosed from moksha.hub.amqp.base import BaseAMQPHub log = logging.getLogger('moksha.hub') class QpidAMQPHub(BaseAMQPHub): """ I...
0.538498
0.130618
import shutil import traceback from abc import ABC, abstractmethod from pathlib import Path, PurePath from tempfile import TemporaryDirectory from typing import List, IO, Optional from zipfile import ZipFile import yaml from opera.error import ParseError, OperaError from opera.utils import determine_archive_format ...
src/opera/parser/tosca/csar.py
import shutil import traceback from abc import ABC, abstractmethod from pathlib import Path, PurePath from tempfile import TemporaryDirectory from typing import List, IO, Optional from zipfile import ZipFile import yaml from opera.error import ParseError, OperaError from opera.utils import determine_archive_format ...
0.634317
0.087019
import datetime import json from freezegun import freeze_time from mantarray_desktop_app import COMPILED_EXE_BUILD_TIMESTAMP from mantarray_desktop_app import create_magnetometer_config_dict from mantarray_desktop_app import CURRENT_SOFTWARE_VERSION from mantarray_desktop_app import MICRO_TO_BASE_CONVERSION from manta...
tests/server/test_routes_populate_queues.py
import datetime import json from freezegun import freeze_time from mantarray_desktop_app import COMPILED_EXE_BUILD_TIMESTAMP from mantarray_desktop_app import create_magnetometer_config_dict from mantarray_desktop_app import CURRENT_SOFTWARE_VERSION from mantarray_desktop_app import MICRO_TO_BASE_CONVERSION from manta...
0.313105
0.116613
import enum from models.base_pose import PoseModel from utils import Joint, normalize, log def distance(p1, p2): return ((p1.x - p2.x)**2 + (p1.y - p2.y)**2)**(1/2) def get_sin(elbow_p, wrist_p, c): return (wrist_p.y - elbow_p.y) / c def get_cos(elbow_p, wrist_p, c): return (wrist_p.x - elbow_p.x) / ...
src/models/intel_pose.py
import enum from models.base_pose import PoseModel from utils import Joint, normalize, log def distance(p1, p2): return ((p1.x - p2.x)**2 + (p1.y - p2.y)**2)**(1/2) def get_sin(elbow_p, wrist_p, c): return (wrist_p.y - elbow_p.y) / c def get_cos(elbow_p, wrist_p, c): return (wrist_p.x - elbow_p.x) / ...
0.566139
0.35301
from abc import ABC, abstractmethod import jax import jax.numpy as jnp import haiku as hk import optax import chex from .._base.mixins import RandomStateMixin from ..utils import get_grads_diagnostics, is_policy, is_stochastic, is_qfunction, is_vfunction, jit from ..value_losses import huber, quantile_huber from ..re...
coax/td_learning/_base.py
from abc import ABC, abstractmethod import jax import jax.numpy as jnp import haiku as hk import optax import chex from .._base.mixins import RandomStateMixin from ..utils import get_grads_diagnostics, is_policy, is_stochastic, is_qfunction, is_vfunction, jit from ..value_losses import huber, quantile_huber from ..re...
0.901922
0.362602
import glob import os import shutil import numpy as np import pytest import webbpsf from .utils import parametrized_data from mirage.psf.deployments import generate_random_ote_deployment, load_ote_from_deployment_yaml from mirage.utils.utils import ensure_dir_exists # Define directory and file locations __location__...
tests/test_deployments.py
import glob import os import shutil import numpy as np import pytest import webbpsf from .utils import parametrized_data from mirage.psf.deployments import generate_random_ote_deployment, load_ote_from_deployment_yaml from mirage.utils.utils import ensure_dir_exists # Define directory and file locations __location__...
0.635901
0.391551
from cuml.manifold import UMAP from sklearn.datasets import load_digits from numba import cuda from pyrr import Matrix44 import numpy as np import cudatashader as ds from cudatashader import transfer_functions as tf from cudatashader.colors import Hot from IPython.core.display import display, HTML, clear_output digits...
cudatashader-3d-demo/render_server.py
from cuml.manifold import UMAP from sklearn.datasets import load_digits from numba import cuda from pyrr import Matrix44 import numpy as np import cudatashader as ds from cudatashader import transfer_functions as tf from cudatashader.colors import Hot from IPython.core.display import display, HTML, clear_output digits...
0.676192
0.420659
import string import random def process_file(filename, skip_header): """Makes a histogram that contains the words from a file. filename: string skip_header: boolean, whether to skip the Gutenberg header Returns: map from each word to the number of times it appears. """ hist = {} fp = ...
Think Python/analyze_book.py
import string import random def process_file(filename, skip_header): """Makes a histogram that contains the words from a file. filename: string skip_header: boolean, whether to skip the Gutenberg header Returns: map from each word to the number of times it appears. """ hist = {} fp = ...
0.785802
0.539772
import betaDecay import spontaneousFission as sf import generalFunctions as gf from matplotlib import pyplot as plt from matplotlib import colors #Shows energy released when the nucleus is streched into an ellipsoid. A positive energy release indicates instantaneous fission. def fissionMap(zMin, zMax, aMin, aMax): ...
example.py
import betaDecay import spontaneousFission as sf import generalFunctions as gf from matplotlib import pyplot as plt from matplotlib import colors #Shows energy released when the nucleus is streched into an ellipsoid. A positive energy release indicates instantaneous fission. def fissionMap(zMin, zMax, aMin, aMax): ...
0.210685
0.643553
import chex import haiku as hk from jax import jit, random, lax, tree_map, vmap from jax.tree_util import tree_flatten, tree_unflatten import blackjax.nuts as nuts import blackjax.stan_warmup as stan_warmup import jax.numpy as jnp import typing_extensions from typing import Any, NamedTuple, Union from jsl.experimen...
jsl/experimental/seql/agents/blackjax_nuts_agent.py
import chex import haiku as hk from jax import jit, random, lax, tree_map, vmap from jax.tree_util import tree_flatten, tree_unflatten import blackjax.nuts as nuts import blackjax.stan_warmup as stan_warmup import jax.numpy as jnp import typing_extensions from typing import Any, NamedTuple, Union from jsl.experimen...
0.831212
0.365428
import sys import pygame from bullet import Bullet from alien import Alien from time import sleep def check_keydown_events(event, ship, ai_settings, screen, bullets): """ 响应按键 """ if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = T...
L/game/game_function.py
import sys import pygame from bullet import Bullet from alien import Alien from time import sleep def check_keydown_events(event, ship, ai_settings, screen, bullets): """ 响应按键 """ if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = T...
0.286169
0.145055
import StringIO import os import string try: from genshi import template as genshitemplate except ImportError, e: genshitemplate = None try: import jinja2 except ImportError, e: jinja2 = None from twisted.internet import defer, reactor from twisted.python import components from zope import interface ...
txtemplate/templates.py
import StringIO import os import string try: from genshi import template as genshitemplate except ImportError, e: genshitemplate = None try: import jinja2 except ImportError, e: jinja2 = None from twisted.internet import defer, reactor from twisted.python import components from zope import interface ...
0.49048
0.103522
INPUT_FILE = 'input.txt' def main(): with open(INPUT_FILE, 'r') as file: puzzle_input = file.read().split('\n\n') numbers_drown = puzzle_input[0] boards_definitions = puzzle_input[1:] numbers = [int(number) for number in numbers_drown.strip().split(',')] boards = [] for board_defin...
year-2021/day-04/part-2.py
INPUT_FILE = 'input.txt' def main(): with open(INPUT_FILE, 'r') as file: puzzle_input = file.read().split('\n\n') numbers_drown = puzzle_input[0] boards_definitions = puzzle_input[1:] numbers = [int(number) for number in numbers_drown.strip().split(',')] boards = [] for board_defin...
0.336985
0.394143
cities = [ 'Acampo', 'Acton', 'Adelanto', 'Adin', '<NAME>', 'Aguanga', 'Ahwahnee', 'Alameda', 'Alamo', 'Albany', 'Albion', 'Alderpoint', 'Alhambra', 'Aliso Viejo', 'Alleghany', 'Alpaugh', 'Alpine', 'Alta', 'Alta Loma', 'Altadena', 'Alta...
john_doe/cities/us/california.py
cities = [ 'Acampo', 'Acton', 'Adelanto', 'Adin', '<NAME>', 'Aguanga', 'Ahwahnee', 'Alameda', 'Alamo', 'Albany', 'Albion', 'Alderpoint', 'Alhambra', 'Aliso Viejo', 'Alleghany', 'Alpaugh', 'Alpine', 'Alta', 'Alta Loma', 'Altadena', 'Alta...
0.357231
0.191026
import unittest import sqlite3 from .. import db as doxygen_db from .. import exceptions from .. import sql from . import TEST_DB db = doxygen_db.DoxygenSQLite3(TEST_DB) class TestDatabase(unittest.TestCase): """Validate statements generated by the Statement class""" def test_undefined_table(self): ...
doxy_db/tests/t_db.py
import unittest import sqlite3 from .. import db as doxygen_db from .. import exceptions from .. import sql from . import TEST_DB db = doxygen_db.DoxygenSQLite3(TEST_DB) class TestDatabase(unittest.TestCase): """Validate statements generated by the Statement class""" def test_undefined_table(self): ...
0.498291
0.480601
import argparse import os import time import torch from tengine import tg import numpy as np import numpy as np import torchvision.transforms as transforms import torchvision.datasets as datasets from main import ( accuracy, AverageMeter ) IMG_SIZE = 224 parser = argparse.ArgumentParser(description='classif...
application/imagenet_example/eval_tengine.py
import argparse import os import time import torch from tengine import tg import numpy as np import numpy as np import torchvision.transforms as transforms import torchvision.datasets as datasets from main import ( accuracy, AverageMeter ) IMG_SIZE = 224 parser = argparse.ArgumentParser(description='classif...
0.712732
0.451447
from time import sleep import pandas as pd import numpy as np import lightgbm as lgb from sklearn.model_selection import StratifiedKFold, train_test_split from sklearn.metrics import roc_auc_score from miraiml import HyperSearchSpace, Config, Engine class LightGBM: def __init__(self, n_folds, **parameters): ...
examples/lightgbm_wrapper.py
from time import sleep import pandas as pd import numpy as np import lightgbm as lgb from sklearn.model_selection import StratifiedKFold, train_test_split from sklearn.metrics import roc_auc_score from miraiml import HyperSearchSpace, Config, Engine class LightGBM: def __init__(self, n_folds, **parameters): ...
0.715026
0.307956
import os.path as op from glob import glob from pprint import pprint import pandas as pd TARGET_FILES = [ # TE30 "power/{sub}/func/{prefix}_desc-TE30_bold.nii.gz", # OC "tedana/{sub}/func/{prefix}_desc-optcom_bold.nii.gz", # MEDN "tedana/{sub}/func/{prefix}_desc-optcomDenoised_bold.nii.gz", ...
processing/07b_check_denoising_completion.py
import os.path as op from glob import glob from pprint import pprint import pandas as pd TARGET_FILES = [ # TE30 "power/{sub}/func/{prefix}_desc-TE30_bold.nii.gz", # OC "tedana/{sub}/func/{prefix}_desc-optcom_bold.nii.gz", # MEDN "tedana/{sub}/func/{prefix}_desc-optcomDenoised_bold.nii.gz", ...
0.24726
0.141905
from __future__ import absolute_import from rest_framework.permissions import IsAuthenticated from sentry.api.base import Endpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.permissions import ScopedPermission from sentry.app import raven from sentry.models import SentryApp, SentryAppInsta...
src/sentry/api/bases/sentryapps.py
from __future__ import absolute_import from rest_framework.permissions import IsAuthenticated from sentry.api.base import Endpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.permissions import ScopedPermission from sentry.app import raven from sentry.models import SentryApp, SentryAppInsta...
0.587115
0.039565
import numpy as np import deeptrack as dt import random def GetSubSet(randset): """ Returns a function that takes a graph and returns a random subset of the graph. """ def inner(data): graph, labels, sets = data nodeidxs = np.where(sets[0] == randset)[0] edgeidxs = np.whe...
deeptrack/models/gnns/augmentations.py
import numpy as np import deeptrack as dt import random def GetSubSet(randset): """ Returns a function that takes a graph and returns a random subset of the graph. """ def inner(data): graph, labels, sets = data nodeidxs = np.where(sets[0] == randset)[0] edgeidxs = np.whe...
0.797793
0.712845
import numpy as np from scipy.interpolate import RectSphereBivariateSpline def regular_gldas(lats,lons,grids): ''' Normalize the GLDAS grid data to meet the requirements of spherical harmonic expansion with pyshtools based on the sampling theorem of Driscoll and Healy (1994). The normalized grid data has t...
ggtools/gg/regular_gldas.py
import numpy as np from scipy.interpolate import RectSphereBivariateSpline def regular_gldas(lats,lons,grids): ''' Normalize the GLDAS grid data to meet the requirements of spherical harmonic expansion with pyshtools based on the sampling theorem of Driscoll and Healy (1994). The normalized grid data has t...
0.832815
0.73678
import json import logging from kigo.etl.runtime.registry import MappingRegistry from kigo.etl.mapper.mapping import MappingInfo class Config: __config = {} @classmethod def load(cls, file_path): with open(file_path, "r") as f: Config.__config = json.load(f) Config.validate() ...
kigo/etl/configuration.py
import json import logging from kigo.etl.runtime.registry import MappingRegistry from kigo.etl.mapper.mapping import MappingInfo class Config: __config = {} @classmethod def load(cls, file_path): with open(file_path, "r") as f: Config.__config = json.load(f) Config.validate() ...
0.54577
0.097433
import os import sys import re import glob import argparse from pathlib import Path import utils def makePlot1cFilelists(golddir, resultdir, outputdir, genefile, queryNames): golddir = Path(golddir).resolve().as_posix() resultdir = Path(resultdir).resolve().as_posix() outputdir = Path(outputdir).resolve()...
tests/bioinform_tests/pytools/create_plot1c_filelists.py
import os import sys import re import glob import argparse from pathlib import Path import utils def makePlot1cFilelists(golddir, resultdir, outputdir, genefile, queryNames): golddir = Path(golddir).resolve().as_posix() resultdir = Path(resultdir).resolve().as_posix() outputdir = Path(outputdir).resolve()...
0.208259
0.146118
import json import logging import os from slack_sdk import WebClient from slack_sdk.errors import SlackApiError from constants import TRUE_VALUES states = json.loads(os.environ["STATES"]) def format_available_message(locations): message = ":large_green_circle: {}Vaccine appointments available at {} location{}:...
notify/slack.py
import json import logging import os from slack_sdk import WebClient from slack_sdk.errors import SlackApiError from constants import TRUE_VALUES states = json.loads(os.environ["STATES"]) def format_available_message(locations): message = ":large_green_circle: {}Vaccine appointments available at {} location{}:...
0.178347
0.081301
import requests import sys from functools import wraps import inspect from json import loads class IEX(object): """ Base class for IEX API """ _IEX_API_URL = "https://api.iextrading.com/1.0" def __init__(self, retries=5): """ Initialize the class retries: Maximum amount...
py_iex/iex.py
import requests import sys from functools import wraps import inspect from json import loads class IEX(object): """ Base class for IEX API """ _IEX_API_URL = "https://api.iextrading.com/1.0" def __init__(self, retries=5): """ Initialize the class retries: Maximum amount...
0.403684
0.121009
import SchemDraw as schem import SchemDraw.elements as e d = schem.Drawing(inches_per_unit=.5, unit=3) D1 = d.add(e.DIODE, theta=-45) d.add(e.DOT) D2 = d.add(e.DIODE, theta=225, reverse=True) d.add(e.DOT) D3 = d.add(e.DIODE, theta=135, reverse=True) d.add(e.DOT) D4 = d.add(e.DIODE, theta=45) d.add(e.DOT) d.add(e.LINE...
docs/gallery/powersupply.py
import SchemDraw as schem import SchemDraw.elements as e d = schem.Drawing(inches_per_unit=.5, unit=3) D1 = d.add(e.DIODE, theta=-45) d.add(e.DOT) D2 = d.add(e.DIODE, theta=225, reverse=True) d.add(e.DOT) D3 = d.add(e.DIODE, theta=135, reverse=True) d.add(e.DOT) D4 = d.add(e.DIODE, theta=45) d.add(e.DOT) d.add(e.LINE...
0.473901
0.570032
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support import...
wphafiye.py
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support import...
0.156427
0.105579
from uuid import uuid4 from . import settings from ..core.clients import OAuth2Client from .models import PayPalOAuthProfile class PayPalClient(OAuth2Client): """ Client to connect with the PayPal REST API. """ # Configuration service_name = 'PayPal' app_key = settings.APP_ID app_secret =...
socialnetworks/paypal/clients.py
from uuid import uuid4 from . import settings from ..core.clients import OAuth2Client from .models import PayPalOAuthProfile class PayPalClient(OAuth2Client): """ Client to connect with the PayPal REST API. """ # Configuration service_name = 'PayPal' app_key = settings.APP_ID app_secret =...
0.63409
0.097476
import cv2 import numpy as np from activity_service import add_to_sample, run_activity_inference import requests import json import base64 import configparser config = configparser.ConfigParser() config.read("config.ini") def encode_img(image): _, buffer = cv2.imencode('.jpg', image) enc_buff = base64.b64e...
visualizers.py
import cv2 import numpy as np from activity_service import add_to_sample, run_activity_inference import requests import json import base64 import configparser config = configparser.ConfigParser() config.read("config.ini") def encode_img(image): _, buffer = cv2.imencode('.jpg', image) enc_buff = base64.b64e...
0.159217
0.137706
import numpy as np from skimage.transform import AffineTransform, warp from skimage.util import pad, img_as_ubyte from typing import List from dataset.interpolate.InterpolateDatasetLoader import InterpolateDatasetLoader from dataset.loader.DatasetLoader import DatasetLoader from dataset.interpolate.InterpolateSubdatas...
src/dataset/interpolate/process/CreateTransformedInterpolateData.py
import numpy as np from skimage.transform import AffineTransform, warp from skimage.util import pad, img_as_ubyte from typing import List from dataset.interpolate.InterpolateDatasetLoader import InterpolateDatasetLoader from dataset.loader.DatasetLoader import DatasetLoader from dataset.interpolate.InterpolateSubdatas...
0.872075
0.403861
import speech_recognition as sr import re import philips_hue as ph import soundclassify as sc import pyaudio import wave from jesica4 import create_dashboard from jesica4 import command_light from jesica4 import command_SoundSystem from jesica4 import command_Door from jesica4 import command_detectsound command_light...
speechrecog/__main__.py
import speech_recognition as sr import re import philips_hue as ph import soundclassify as sc import pyaudio import wave from jesica4 import create_dashboard from jesica4 import command_light from jesica4 import command_SoundSystem from jesica4 import command_Door from jesica4 import command_detectsound command_light...
0.175185
0.120413
import argparse import os import torch import torch.nn as nn import torch.utils.data as data class Configs(object): @staticmethod def base_config(): parser = argparse.ArgumentParser() parser.add_argument("--classifier", type=str, default="vdpwi", choices=["vdpwi", "resnet"]) parser.add...
vdpwi/data.py
import argparse import os import torch import torch.nn as nn import torch.utils.data as data class Configs(object): @staticmethod def base_config(): parser = argparse.ArgumentParser() parser.add_argument("--classifier", type=str, default="vdpwi", choices=["vdpwi", "resnet"]) parser.add...
0.659624
0.128416
import os import shutil import argparse from abc import ABCMeta, abstractmethod from typing import List, Dict, Iterable, Iterator, Optional, Any from .util import Namespace from .instance import Instance from .package import Package from .parallel import Pool class Target(metaclass=ABCMeta): """ Abstract base...
infra/target.py
import os import shutil import argparse from abc import ABCMeta, abstractmethod from typing import List, Dict, Iterable, Iterator, Optional, Any from .util import Namespace from .instance import Instance from .package import Package from .parallel import Pool class Target(metaclass=ABCMeta): """ Abstract base...
0.897893
0.442637
import enum import ipaddress from typing import Optional from sqlalchemy import Column, String, Enum, text from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy_utils import UUIDType, generic_repr, IPAddressType, ArrowType from ingredients_db.database import Base from ingredients_db.models.network_port imp...
ingredients_db/models/network.py
import enum import ipaddress from typing import Optional from sqlalchemy import Column, String, Enum, text from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy_utils import UUIDType, generic_repr, IPAddressType, ArrowType from ingredients_db.database import Base from ingredients_db.models.network_port imp...
0.746046
0.101322
from IPython.core.pylabtools import print_figure from IPython.core.display import display, HTML, Math, Latex from sympy import Matrix, latex import numpy as np def limitprec(m, prec=3): '''Silly function to limit the maximum number of decimal places for a matrix of floats. m: np.ndarray input ...
notebookutils.py
from IPython.core.pylabtools import print_figure from IPython.core.display import display, HTML, Math, Latex from sympy import Matrix, latex import numpy as np def limitprec(m, prec=3): '''Silly function to limit the maximum number of decimal places for a matrix of floats. m: np.ndarray input ...
0.692954
0.580709
import os import re import numpy as np import scipy.optimize from ledsa.core.model import target_function from ledsa.core.LEDAnalysisData import LEDAnalysisData import time sep = os.path.sep def generate_led_analysis_data(conf, channel, data, debug, iled, img_filename, led_array_idx, search_areas, ...
ledsa/core/_led_helper_functions_s3.py
import os import re import numpy as np import scipy.optimize from ledsa.core.model import target_function from ledsa.core.LEDAnalysisData import LEDAnalysisData import time sep = os.path.sep def generate_led_analysis_data(conf, channel, data, debug, iled, img_filename, led_array_idx, search_areas, ...
0.267408
0.196961
from git import Repo, RemoteReference, TagReference, InvalidGitRepositoryError, GitCommandError from tempfile import NamedTemporaryFile import shutil import os class Git: def __init__(self, git_repo, repo_dir, pkey=None): self.git_repo = git_repo self.repo_dir = repo_dir self.repo = None ...
spug_api/libs/gitlib.py
from git import Repo, RemoteReference, TagReference, InvalidGitRepositoryError, GitCommandError from tempfile import NamedTemporaryFile import shutil import os class Git: def __init__(self, git_repo, repo_dir, pkey=None): self.git_repo = git_repo self.repo_dir = repo_dir self.repo = None ...
0.325628
0.072834
import numpy as np from manim import * import sympy as sp class Curve3D(): def __init__(self, name: str, t: sp.Symbol, vector_sym, init_t: float, color: str, speed=1, scale=1, offset=[0, 0, 0]): ## Symbolic attributes # Parameter self.t_sym = t * speed # Paramet...
part-1/Curve3D.py
import numpy as np from manim import * import sympy as sp class Curve3D(): def __init__(self, name: str, t: sp.Symbol, vector_sym, init_t: float, color: str, speed=1, scale=1, offset=[0, 0, 0]): ## Symbolic attributes # Parameter self.t_sym = t * speed # Paramet...
0.638272
0.428473
import time from common.scene import Scene from common.tool import load_resource from azurelane.assist import calculate_move_map ###自己添加 def siren_heavy_blue(prefix): return Scene("检测蓝色塞壬重巡",identify_image=load_resource("map_siren_heavy_blue.png", prefix)) #判断塞壬蓝色重巡 def siren_heavy_purple(prefix): ...
azurelane/scenes/enemy_search.py
import time from common.scene import Scene from common.tool import load_resource from azurelane.assist import calculate_move_map ###自己添加 def siren_heavy_blue(prefix): return Scene("检测蓝色塞壬重巡",identify_image=load_resource("map_siren_heavy_blue.png", prefix)) #判断塞壬蓝色重巡 def siren_heavy_purple(prefix): ...
0.26693
0.207435
"""Tests for the auto_forensicate script.""" from __future__ import unicode_literals import argparse import logging import os import StringIO import sys import tempfile import unittest import auto_acquire from auto_forensicate import errors from auto_forensicate import uploader from auto_forensicate.recipes import b...
auto_forensicate/tests/auto_forensicate_tests.py
"""Tests for the auto_forensicate script.""" from __future__ import unicode_literals import argparse import logging import os import StringIO import sys import tempfile import unittest import auto_acquire from auto_forensicate import errors from auto_forensicate import uploader from auto_forensicate.recipes import b...
0.580114
0.227405
import logging from pathlib import Path import sys import tempfile import beetools import displayfx _VERSION = "0.0.1" _path = Path(__file__) _name = _path.stem class TxtWrpr: '''A wrapper for fixed column text files This module copies a fixed column TXT file into a dictionary structure to manipulate and...
src/txtwrpr/txtwrpr.py
import logging from pathlib import Path import sys import tempfile import beetools import displayfx _VERSION = "0.0.1" _path = Path(__file__) _name = _path.stem class TxtWrpr: '''A wrapper for fixed column text files This module copies a fixed column TXT file into a dictionary structure to manipulate and...
0.397588
0.210381
import copy from typing import Any, Dict, List from pytest import lazy_fixture # type: ignore from pytest import fixture, mark, param from omegaconf import OmegaConf from omegaconf._utils import ValueKind, _is_missing_literal, get_value_kind def build_dict( d: Dict[str, Any], depth: int, width: int, leaf_value...
benchmark/benchmark.py
import copy from typing import Any, Dict, List from pytest import lazy_fixture # type: ignore from pytest import fixture, mark, param from omegaconf import OmegaConf from omegaconf._utils import ValueKind, _is_missing_literal, get_value_kind def build_dict( d: Dict[str, Any], depth: int, width: int, leaf_value...
0.687105
0.357147
import copy from rbkcli.base import CONSTANTS, RbkcliBase, RbkcliException from rbkcli.core.handlers.environment import EnvironmentHandler from rbkcli.core.handlers.inputs import InputHandler from rbkcli.core.handlers.outputs import OutputHandler class ApiTarget(RbkcliBase): """Define the Target to wh...
rbkcli/core/target.py
import copy from rbkcli.base import CONSTANTS, RbkcliBase, RbkcliException from rbkcli.core.handlers.environment import EnvironmentHandler from rbkcli.core.handlers.inputs import InputHandler from rbkcli.core.handlers.outputs import OutputHandler class ApiTarget(RbkcliBase): """Define the Target to wh...
0.704872
0.075448
import sys import random import time from math import isclose from string import ascii_lowercase from enum import Enum, IntFlag, auto from pulp import * START_TIME = time.time() DEFAULT_OPTIMISATION_ACCURACY = .15 ID_LOWER_BOUND = 10000000 ID_UPPER_BOUND = 99999999 NUMBER_OF_WORKDAYS = 7 MAXIMUM_CONSECUTIVE_WORKDAYS ...
workforce_scheduler.py
import sys import random import time from math import isclose from string import ascii_lowercase from enum import Enum, IntFlag, auto from pulp import * START_TIME = time.time() DEFAULT_OPTIMISATION_ACCURACY = .15 ID_LOWER_BOUND = 10000000 ID_UPPER_BOUND = 99999999 NUMBER_OF_WORKDAYS = 7 MAXIMUM_CONSECUTIVE_WORKDAYS ...
0.602412
0.170094
from firedrake import * import matplotlib.pyplot as plt parameters["pyop2_options"]["lazy_evaluation"] = False # Defining the mesh N = 15 use_quads = True mesh = UnitSquareMesh(N, N, quadrilateral=use_quads) # Function space declaration degree = 1 pressure_family = 'CG' velocity_family = 'CG' U = VectorFunctionSpace...
scripts/misc/ls_operator_condition_number_iterative.py
from firedrake import * import matplotlib.pyplot as plt parameters["pyop2_options"]["lazy_evaluation"] = False # Defining the mesh N = 15 use_quads = True mesh = UnitSquareMesh(N, N, quadrilateral=use_quads) # Function space declaration degree = 1 pressure_family = 'CG' velocity_family = 'CG' U = VectorFunctionSpace...
0.806548
0.464962
from .errors import * class Store: """ Store record Each postcode record contains basic information like name and coordinates in WGS84 geographic system """ def __init__(self, postcode: str, name: str, lon: float = None, lat: float = None): """ Create new store record. ...
src/stores/store.py
from .errors import * class Store: """ Store record Each postcode record contains basic information like name and coordinates in WGS84 geographic system """ def __init__(self, postcode: str, name: str, lon: float = None, lat: float = None): """ Create new store record. ...
0.935073
0.425665
import os from torch.utils.data import Dataset import numpy as np import torch import torch.nn.functional as F import re class TextDataset(Dataset): def __init__(self, txt_path, mode='train', seq_len=50, n_steps=50): assert os.path.exists(txt_path), f"File not found {txt_path}\n" with open(txt_pat...
engine/dataloader.py
import os from torch.utils.data import Dataset import numpy as np import torch import torch.nn.functional as F import re class TextDataset(Dataset): def __init__(self, txt_path, mode='train', seq_len=50, n_steps=50): assert os.path.exists(txt_path), f"File not found {txt_path}\n" with open(txt_pat...
0.54698
0.37439
import subprocess import os import tempfile from testbook import testbook from tempfile import TemporaryDirectory as tdir from ark.utils import notebooks_test_utils import pytest parametrize = pytest.mark.parametrize SEGMENT_IMAGE_DATA_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), ...
ark/utils/notebooks_test.py
import subprocess import os import tempfile from testbook import testbook from tempfile import TemporaryDirectory as tdir from ark.utils import notebooks_test_utils import pytest parametrize = pytest.mark.parametrize SEGMENT_IMAGE_DATA_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), ...
0.356559
0.249664
from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model import pprint import six class SpriteJpegConfig(object): @poscheck_model def __init__(self, quality=None): # type: (int) -> None self._quality = None ...
bitmovin_api_sdk/models/sprite_jpeg_config.py
from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model import pprint import six class SpriteJpegConfig(object): @poscheck_model def __init__(self, quality=None): # type: (int) -> None self._quality = None ...
0.870005
0.259843
from __future__ import absolute_import from __future__ import unicode_literals import markdown from markdown.util import etree import re class CollapseExtension(markdown.Extension): """ Collapse extension for Python-Markdown. """ def extendMarkdown(self, md, md_globals): """ Add Admonition to Markdown...
mdx_collapse.py
from __future__ import absolute_import from __future__ import unicode_literals import markdown from markdown.util import etree import re class CollapseExtension(markdown.Extension): """ Collapse extension for Python-Markdown. """ def extendMarkdown(self, md, md_globals): """ Add Admonition to Markdown...
0.527317
0.084078
import pytest import numpy as np import pandas as pd from scipy.io import loadmat from echopype import open_raw from echopype.testing import TEST_DATA_FOLDER @pytest.fixture def ek80_path(test_path): return test_path["EK80"] def pytest_generate_tests(metafunc): ek80_new_path = TEST_DATA_FOLDER / "ek80_new"...
echopype/tests/convert/test_convert_ek80.py
import pytest import numpy as np import pandas as pd from scipy.io import loadmat from echopype import open_raw from echopype.testing import TEST_DATA_FOLDER @pytest.fixture def ek80_path(test_path): return test_path["EK80"] def pytest_generate_tests(metafunc): ek80_new_path = TEST_DATA_FOLDER / "ek80_new"...
0.460532
0.437223
import unittest from ctypes import * from tests.annotations import Platform, skip_platform from pyglet import window from pyglet.gl import * @skip_platform(Platform.WINDOWS) # Causes crashes on Windows (issue #48) class ContextShareTest(unittest.TestCase): def create_context(self, share): display = wind...
tests/integration/window/test_context_share.py
import unittest from ctypes import * from tests.annotations import Platform, skip_platform from pyglet import window from pyglet.gl import * @skip_platform(Platform.WINDOWS) # Causes crashes on Windows (issue #48) class ContextShareTest(unittest.TestCase): def create_context(self, share): display = wind...
0.421671
0.456773
# In[1]: RunActualDB = True import sys import json import time import random import statistics import pprint import math print("Current Python version: ", sys.version_info[0],".",sys.version_info[1],".",sys.version_info[2]) _useAllTimes = False _print_raw = False _DB_mode = sys.argv[1] if _DB_mode != "AS" and _DB_m...
ConstraintTests.py
# In[1]: RunActualDB = True import sys import json import time import random import statistics import pprint import math print("Current Python version: ", sys.version_info[0],".",sys.version_info[1],".",sys.version_info[2]) _useAllTimes = False _print_raw = False _DB_mode = sys.argv[1] if _DB_mode != "AS" and _DB_m...
0.278944
0.188548
import os import shutil import tempfile import unittest from cros.factory.tools import install_symlinks FAKE_SYMLINKS = {'binaries': {'fullbin': 'full', 'minibin': 'mini'}} class TestInstallSymlinks(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp(prefix='install_symlinks_unittest.') ...
py/tools/install_symlinks_unittest.py
import os import shutil import tempfile import unittest from cros.factory.tools import install_symlinks FAKE_SYMLINKS = {'binaries': {'fullbin': 'full', 'minibin': 'mini'}} class TestInstallSymlinks(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp(prefix='install_symlinks_unittest.') ...
0.31785
0.253075
import json import os def dataPro01(path_source,path_target): rootpath = '../data/GodText/01/' path_source = os.path.join(rootpath,'godText_all1.json') with open(path_source,'r') as f: S0 = json.load(f) S1 = []#没有新年祝福 S2 = []#只有新年祝福 s = ['新年','新春','春节','元旦','鼠年','牛年','虎年','兔年','龙年','蛇年',...
data_godText/datapro.py
import json import os def dataPro01(path_source,path_target): rootpath = '../data/GodText/01/' path_source = os.path.join(rootpath,'godText_all1.json') with open(path_source,'r') as f: S0 = json.load(f) S1 = []#没有新年祝福 S2 = []#只有新年祝福 s = ['新年','新春','春节','元旦','鼠年','牛年','虎年','兔年','龙年','蛇年',...
0.023198
0.125762
from ..utils.log import Logger from collections import OrderedDict from os import path import csv class TSVModel: def __init__(self, directory): """ Load data from tab-separated values. Arguments: directory {str} -- Directory to open """ Logger.debug(__name__...
nottreal/models/m_tsv.py
from ..utils.log import Logger from collections import OrderedDict from os import path import csv class TSVModel: def __init__(self, directory): """ Load data from tab-separated values. Arguments: directory {str} -- Directory to open """ Logger.debug(__name__...
0.604866
0.13707
from __future__ import unicode_literals from django.db import migrations def delete_alert_email_user_options(apps, schema_editor): """ Processes user reports that are missing event data, and adds the appropriate data if the event exists in Clickhouse. """ from sentry.utils.query import RangeQuery...
src/sentry/migrations/0032_delete_alert_email.py
from __future__ import unicode_literals from django.db import migrations def delete_alert_email_user_options(apps, schema_editor): """ Processes user reports that are missing event data, and adds the appropriate data if the event exists in Clickhouse. """ from sentry.utils.query import RangeQuery...
0.670608
0.200342
# NOC modules from noc.core.datastream.base import DataStream from noc.main.models.pool import Pool from noc.main.models.timepattern import TimePattern from noc.sa.models.managedobject import ManagedObject class CfgPingDataStream(DataStream): name = "cfgping" clean_id = DataStream.clean_id_int @classmet...
services/datastream/streams/cfgping.py
# NOC modules from noc.core.datastream.base import DataStream from noc.main.models.pool import Pool from noc.main.models.timepattern import TimePattern from noc.sa.models.managedobject import ManagedObject class CfgPingDataStream(DataStream): name = "cfgping" clean_id = DataStream.clean_id_int @classmet...
0.651133
0.189615
import logging from splitio.models import splits from splitio.api import APIException from splitio.tasks import BaseSynchronizationTask from splitio.tasks.util.asynctask import AsyncTask class SplitSynchronizationTask(BaseSynchronizationTask): """Split Synchronization task class.""" def __init__(self, split...
splitio/tasks/split_sync.py
import logging from splitio.models import splits from splitio.api import APIException from splitio.tasks import BaseSynchronizationTask from splitio.tasks.util.asynctask import AsyncTask class SplitSynchronizationTask(BaseSynchronizationTask): """Split Synchronization task class.""" def __init__(self, split...
0.780453
0.292317
from configs.wfmconfig import tool_tokeniser from configs.wfmconfig import tool_translator class Translator: def __init__(self): pass def is_contains_list_of_paragraphs(self, task_output): if isinstance(task_output["output"], list): if len(task_output["output"]) > 0 and isinstance...
anuvaad-etl/anuvaad-workflow-mgr/etl-wf-manager/tools/translator.py
from configs.wfmconfig import tool_tokeniser from configs.wfmconfig import tool_translator class Translator: def __init__(self): pass def is_contains_list_of_paragraphs(self, task_output): if isinstance(task_output["output"], list): if len(task_output["output"]) > 0 and isinstance...
0.483405
0.168686
import os import torch, torchaudio import itertools from shutil import copyfile class BasePreprocessor: def __init__(self, data_dir, output_dir, overwrite_files, bulk_process, extensions = None): # organization self.data_dir = data_dir self.output_dir = output_dir self.overwrite_fi...
base/base_preprocessor.py
import os import torch, torchaudio import itertools from shutil import copyfile class BasePreprocessor: def __init__(self, data_dir, output_dir, overwrite_files, bulk_process, extensions = None): # organization self.data_dir = data_dir self.output_dir = output_dir self.overwrite_fi...
0.287768
0.137822
import tempfile from six import integer_types from mock import patch, Mock from unittest import TestCase from termius.core.models.terminal import ( Host, SshConfig, Identity, SshKey, Group ) from termius.core.exceptions import DoesNotExistException from termius.core.storage.strategies import ( GetStrategy, Save...
tests/unit/core/storage/storage_test.py
import tempfile from six import integer_types from mock import patch, Mock from unittest import TestCase from termius.core.models.terminal import ( Host, SshConfig, Identity, SshKey, Group ) from termius.core.exceptions import DoesNotExistException from termius.core.storage.strategies import ( GetStrategy, Save...
0.490236
0.228071
from pprint import pprint import pytest from tests import validate_error_response class TestKeyManagement: def test_create_key_failure_key_usage(self, kms_client): code, content = kms_client.post( 'CreateKey', { "KeyUsage": "SIGN_VERIFY", }, ) ...
tests/functional/tests/cmk/test_key_management.py
from pprint import pprint import pytest from tests import validate_error_response class TestKeyManagement: def test_create_key_failure_key_usage(self, kms_client): code, content = kms_client.post( 'CreateKey', { "KeyUsage": "SIGN_VERIFY", }, ) ...
0.625438
0.418875
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Secteur from formulaire.serializers import SecteurSerializer SECTEURS_URL = reverse('formulaire:secteur...
app/formulaire/tests/test_secteurs_api.py
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Secteur from formulaire.serializers import SecteurSerializer SECTEURS_URL = reverse('formulaire:secteur...
0.551574
0.243182
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, User, Category, Item # Connect to Database and create database session engine = create_engine('postgresql://catalog:catalog@localhost/catalog') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine...
database_seed.py
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, User, Category, Item # Connect to Database and create database session engine = create_engine('postgresql://catalog:catalog@localhost/catalog') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine...
0.438064
0.161386
import argparse import os import sys import datetime import filecmp import logging from urllib.error import URLError from urllib.request import urlopen from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.triggers.cron import CronTrigger URL = 'https://viewer.by/img/client/{}/1/view01.jpg' ...
snapshotter.py
import argparse import os import sys import datetime import filecmp import logging from urllib.error import URLError from urllib.request import urlopen from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.triggers.cron import CronTrigger URL = 'https://viewer.by/img/client/{}/1/view01.jpg' ...
0.254602
0.068257
if __name__ == '__main__': import collectd_fake as collectd else: import collectd from pyroute2 import IPRoute import socket import collectd_base as base NAME = 'vrrp' class VrrpPlugin(base.Base): def __init__(self, *args, **kwargs): super(VrrpPlugin, self).__init__(*args, **kwargs) se...
files/collectd-modules/collectd_vrrp.py
if __name__ == '__main__': import collectd_fake as collectd else: import collectd from pyroute2 import IPRoute import socket import collectd_base as base NAME = 'vrrp' class VrrpPlugin(base.Base): def __init__(self, *args, **kwargs): super(VrrpPlugin, self).__init__(*args, **kwargs) se...
0.452536
0.089137
import re import sys import getopt from extractors import * from lpIO import * from converters import * """ Author <NAME> (https://github.com/Leajian) Program name Linear Problem Parser (lpp) Version 2.2 """ def main(argv): # Initialize varibales. inputFile = '' outp...
lpp.py
import re import sys import getopt from extractors import * from lpIO import * from converters import * """ Author <NAME> (https://github.com/Leajian) Program name Linear Problem Parser (lpp) Version 2.2 """ def main(argv): # Initialize varibales. inputFile = '' outp...
0.276007
0.196884
import uuid from stdnet.backends.base import BaseBackend, ImproperlyConfigured, novalue from stdnet.backends.structures.structcouchdb import List,Set,HashTable,Map try: import couchdb except: raise ImproperlyConfigured("CouchDB backend requires the 'couchdb-python' library. Do easy_install couchdb-python") R...
stdnet/backends/couchdbb.py
import uuid from stdnet.backends.base import BaseBackend, ImproperlyConfigured, novalue from stdnet.backends.structures.structcouchdb import List,Set,HashTable,Map try: import couchdb except: raise ImproperlyConfigured("CouchDB backend requires the 'couchdb-python' library. Do easy_install couchdb-python") R...
0.40157
0.059866
import numpy as np import math import torch def _t2n(x): """Convert torch tensor to a numpy array.""" return x.detach().cpu().numpy() def check(input): if type(input) == np.ndarray: return torch.from_numpy(input) def get_gard_norm(it): sum_grad = 0 for x in it: if x.grad i...
MAModule/utils/util.py
import numpy as np import math import torch def _t2n(x): """Convert torch tensor to a numpy array.""" return x.detach().cpu().numpy() def check(input): if type(input) == np.ndarray: return torch.from_numpy(input) def get_gard_norm(it): sum_grad = 0 for x in it: if x.grad i...
0.841272
0.596933
import matplotlib.pyplot as plt import h5py from deoxys_image import normalize, gaussian_noise, change_brightness from deoxys_image import change_contrast, gaussian_blur def load_images(index=0): with h5py.File( '../../hn_perf/3d_unet_32/prediction/prediction.030.h5', 'r') as f: image = f['x']...
examples/point_operation_3d.py
import matplotlib.pyplot as plt import h5py from deoxys_image import normalize, gaussian_noise, change_brightness from deoxys_image import change_contrast, gaussian_blur def load_images(index=0): with h5py.File( '../../hn_perf/3d_unet_32/prediction/prediction.030.h5', 'r') as f: image = f['x']...
0.557966
0.475666
from config import load_config import sys import numpy as np import re import tensorflow as tf import BERT_Model as brt import utils as utl tf.set_random_seed(42) np.random.seed(42) def get_predict(result, output): result = np.argmax(result, axis=1) max_index = -1 max_pro = 0.0 for i in...
main.py
from config import load_config import sys import numpy as np import re import tensorflow as tf import BERT_Model as brt import utils as utl tf.set_random_seed(42) np.random.seed(42) def get_predict(result, output): result = np.argmax(result, axis=1) max_index = -1 max_pro = 0.0 for i in...
0.331012
0.248363
from wiremock._compat import add_metaclass from wiremock.base import BaseEntity, JsonProperty, BaseAbstractEntity, BaseEntityMetaType class HttpMethods(object): ANY = "ANY" GET = "GET" POST = "POST" PUT = "PUT" PATCH = "PATCH" DELETE = "DELETE" OPTIONS = "OPTIONS" HEAD = "HEAD" class...
wiremock/resources/mappings/models.py
from wiremock._compat import add_metaclass from wiremock.base import BaseEntity, JsonProperty, BaseAbstractEntity, BaseEntityMetaType class HttpMethods(object): ANY = "ANY" GET = "GET" POST = "POST" PUT = "PUT" PATCH = "PATCH" DELETE = "DELETE" OPTIONS = "OPTIONS" HEAD = "HEAD" class...
0.611962
0.071559
import csv import json import operator import sys, os from typing import List, Dict sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))) class Pivot: def __init__(self, file_list: List[str], header_list: List[str], strict: bool, ...
json2rst/pivot.py
import csv import json import operator import sys, os from typing import List, Dict sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))) class Pivot: def __init__(self, file_list: List[str], header_list: List[str], strict: bool, ...
0.464902
0.226035
import os import argparse from glob import glob from functools import partial import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt import cv2 from PIL import Image import wandb import jax import jax.numpy as jnp import flax import torch import torchvision.transforms as transforms import tensorf...
old/dcgan-selfie-old.py
import os import argparse from glob import glob from functools import partial import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt import cv2 from PIL import Image import wandb import jax import jax.numpy as jnp import flax import torch import torchvision.transforms as transforms import tensorf...
0.775945
0.383093
import numpy as np import matplotlib.pyplot as plt import tools def plotData(input_file, output_file, plot_dir, title, column_indices, xlim, ylim, drawMean): verbose = False tools.makeDir(plot_dir) data = tools.getData(input_file) output_png = "{0}/{1}.png".format(plot_dir, output_file) output_pdf...
EyeDiagrams/python/plotComparison.py
import numpy as np import matplotlib.pyplot as plt import tools def plotData(input_file, output_file, plot_dir, title, column_indices, xlim, ylim, drawMean): verbose = False tools.makeDir(plot_dir) data = tools.getData(input_file) output_png = "{0}/{1}.png".format(plot_dir, output_file) output_pdf...
0.53048
0.651133
from selenium import webdriver import time import os from datetime import datetime import json """" Directory to globals file """ GLOBALS_FILE = "./globals/globals.json" def load_globals(): """ Read content from globals file Returns: dict: fDictionary containing the content of the globals file ...
transform/transform/scrapers/utils.py
from selenium import webdriver import time import os from datetime import datetime import json """" Directory to globals file """ GLOBALS_FILE = "./globals/globals.json" def load_globals(): """ Read content from globals file Returns: dict: fDictionary containing the content of the globals file ...
0.609292
0.209814
"""Helps define a foreign key relationship between two models.""" from typing import Any, Mapping, Type import dataclasses from spanner_orm import registry @dataclasses.dataclass class ForeignKeyRelationshipConstraint: columns: Mapping[str, str] referenced_table_name: str referenced_table: Type[Any] class F...
spanner_orm/foreign_key_relationship.py
"""Helps define a foreign key relationship between two models.""" from typing import Any, Mapping, Type import dataclasses from spanner_orm import registry @dataclasses.dataclass class ForeignKeyRelationshipConstraint: columns: Mapping[str, str] referenced_table_name: str referenced_table: Type[Any] class F...
0.962143
0.545649
from CLIF_Framework.framework import event from CLIF_Framework.framework import tools from os import system from time import sleep from time import time from threading import Thread import socket event = event() tools = tools() class Main: def __init__(selfie, console): global self global var self = selfie v...
modules/l4/main.py
from CLIF_Framework.framework import event from CLIF_Framework.framework import tools from os import system from time import sleep from time import time from threading import Thread import socket event = event() tools = tools() class Main: def __init__(selfie, console): global self global var self = selfie v...
0.13408
0.093927
from collections import OrderedDict import arviz as az import numpy as np import pytest from matplotlib import pyplot as pl from matplotlib.testing.decorators import image_comparison import corner try: import pandas as pd except ImportError: pd = None try: import scipy # noqa except ImportError: s...
tests/test_corner.py
from collections import OrderedDict import arviz as az import numpy as np import pytest from matplotlib import pyplot as pl from matplotlib.testing.decorators import image_comparison import corner try: import pandas as pd except ImportError: pd = None try: import scipy # noqa except ImportError: s...
0.636466
0.439086
import colectica from colectica import ColecticaObject import api import pandas as pd import os import numpy as np def get_all_series(C): """ Get a list of all series """ all_series = C.general_search(C.item_code('Series'),'',MaxResults=0)['Results'] return all_series def from_series_get_study(C...
get_mode_collection.py
import colectica from colectica import ColecticaObject import api import pandas as pd import os import numpy as np def get_all_series(C): """ Get a list of all series """ all_series = C.general_search(C.item_code('Series'),'',MaxResults=0)['Results'] return all_series def from_series_get_study(C...
0.35209
0.345188
import logging import random from typing import List, Union import discord from discord.ext import commands from naotimes.bot import naoTimesBot from naotimes.context import naoTimesContext from naotimes.paginator import DiscordPaginatorUI from naotimes.utils import complex_walk, cutoff_text IMAGEBOORU_SCHEMAS = """...
cogs/bahaya/booru.py
import logging import random from typing import List, Union import discord from discord.ext import commands from naotimes.bot import naoTimesBot from naotimes.context import naoTimesContext from naotimes.paginator import DiscordPaginatorUI from naotimes.utils import complex_walk, cutoff_text IMAGEBOORU_SCHEMAS = """...
0.698227
0.187411
import pytest import numpy as np import dowhy.api from dowhy.causal_estimators.propensity_score_weighting_estimator import PropensityScoreWeightingEstimator from .base import TestEstimator from sklearn.linear_model import LinearRegression class TestPropensityScoreMatchingEstimator(object): @pytest.mark.parametr...
tests/causal_estimators/test_propensity_score_weighting_estimator.py
import pytest import numpy as np import dowhy.api from dowhy.causal_estimators.propensity_score_weighting_estimator import PropensityScoreWeightingEstimator from .base import TestEstimator from sklearn.linear_model import LinearRegression class TestPropensityScoreMatchingEstimator(object): @pytest.mark.parametr...
0.695131
0.545891
from collections import namedtuple import pickle import sys from os.path import exists from http.cookiejar import LWPCookieJar from copy import copy import json import requests from greencache.simple_cache import SimpleCache from htmq.html_query import htmq g_debug = True Option = namedtuple('Option', ['title', 'va...
vote/straw_poll.py
from collections import namedtuple import pickle import sys from os.path import exists from http.cookiejar import LWPCookieJar from copy import copy import json import requests from greencache.simple_cache import SimpleCache from htmq.html_query import htmq g_debug = True Option = namedtuple('Option', ['title', 'va...
0.15588
0.053775
__author__ = 'kzhao' from pyparsing import Word, nums, Combine, OneOrMore, Forward, Suppress, alphanums, Optional from utils import Singleton from type import TypeSystem, ComplexType, TypeEnv from lambda_expr import Variable, Constant, App, Lambda, TypeInferer _TS = TypeSystem() class LambdaExprParser(object): ...
code/NLPCode/TISP/lambda_expr/lambda_expr_parser.py
__author__ = 'kzhao' from pyparsing import Word, nums, Combine, OneOrMore, Forward, Suppress, alphanums, Optional from utils import Singleton from type import TypeSystem, ComplexType, TypeEnv from lambda_expr import Variable, Constant, App, Lambda, TypeInferer _TS = TypeSystem() class LambdaExprParser(object): ...
0.654784
0.178615
import asyncio import os import sqlite3 from concurrent.futures import ThreadPoolExecutor from datetime import datetime class Backend: def __init__(self): """ Used to connect to the database and create required tables if they don't exist yet. """ self.executor = ThreadPoolExecutor...
modbus_client/db/backend.py
import asyncio import os import sqlite3 from concurrent.futures import ThreadPoolExecutor from datetime import datetime class Backend: def __init__(self): """ Used to connect to the database and create required tables if they don't exist yet. """ self.executor = ThreadPoolExecutor...
0.715325
0.182608
import tensorflow as tf import time import os from utils import ( input_setup1, input_setup2, checkpoint_dir, checkpoint_dir1, read_data1, merge, #checkimage, imsave ) class SRCNN(object): def __init__(self,sess, image_size, label_size,c_dim): self.sess = sess self....
model.py
import tensorflow as tf import time import os from utils import ( input_setup1, input_setup2, checkpoint_dir, checkpoint_dir1, read_data1, merge, #checkimage, imsave ) class SRCNN(object): def __init__(self,sess, image_size, label_size,c_dim): self.sess = sess self....
0.61451
0.275501
import argparse import os from pathlib import Path import matplotlib.pyplot as plt import pandas as pd import tikzplotlib def plot_data(input_dir, output_dir, main_scenario, show_plot): """plot SA evaluation data""" sa_df = pd.read_csv(input_dir.joinpath(main_scenario)) bag_frequency = 0.05 sa_df["t...
awareness_detector/util/plot_sa.py
import argparse import os from pathlib import Path import matplotlib.pyplot as plt import pandas as pd import tikzplotlib def plot_data(input_dir, output_dir, main_scenario, show_plot): """plot SA evaluation data""" sa_df = pd.read_csv(input_dir.joinpath(main_scenario)) bag_frequency = 0.05 sa_df["t...
0.519278
0.667663
from __future__ import print_function, unicode_literals, division, absolute_import import codecs from asyncenocean.protocol.eep import EEP ROW_FORMAT = '|{:8s}|{:50s}|{:8s}|{:70s}|\n' eep = EEP() with codecs.open('SUPPORTED_PROFILES.md', 'w', 'utf-8') as f_handle: f_handle.write('# Supported profiles\n') f_...
generate_supported_profiles.py
from __future__ import print_function, unicode_literals, division, absolute_import import codecs from asyncenocean.protocol.eep import EEP ROW_FORMAT = '|{:8s}|{:50s}|{:8s}|{:70s}|\n' eep = EEP() with codecs.open('SUPPORTED_PROFILES.md', 'w', 'utf-8') as f_handle: f_handle.write('# Supported profiles\n') f_...
0.398172
0.148355
import unittest class Solution: @staticmethod def lengthOfLongestSubstring(s: str) -> int: """ Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with ...
python/longest_substring_without_repeating_characters.py
import unittest class Solution: @staticmethod def lengthOfLongestSubstring(s: str) -> int: """ Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with ...
0.789437
0.702103
from enum import Enum, auto class OperatorPrecedence(Enum): """ Represents the precedence of an operator. """ LOWEST = 0 # Unary minus. PLUS = auto() # Either + or -. MUL = auto() # Either * or /. POW = auto() # Power (**). ADDROF = auto() # Address-of operator ...
examples/starkex-cairo/starkware/python/expression_string.py
from enum import Enum, auto class OperatorPrecedence(Enum): """ Represents the precedence of an operator. """ LOWEST = 0 # Unary minus. PLUS = auto() # Either + or -. MUL = auto() # Either * or /. POW = auto() # Power (**). ADDROF = auto() # Address-of operator ...
0.893181
0.521227
from __future__ import print_function import os import csv from subprocess import check_call from django.db import transaction, connection from django.core.management import call_command from .base import BaseCommand, CommandError from pupa.models import Division OCDID_REPO = 'https://github.com/opencivicdata/ocd-di...
pupa/cli/commands/dbinit.py
from __future__ import print_function import os import csv from subprocess import check_call from django.db import transaction, connection from django.core.management import call_command from .base import BaseCommand, CommandError from pupa.models import Division OCDID_REPO = 'https://github.com/opencivicdata/ocd-di...
0.359364
0.063106
from typing import Optional, Union import attr import pendulum from procrastinate import exceptions class BaseRetryStrategy: """ If you want to implement your own retry strategy, you can inherit from this class. Children classes only need to implement `get_schedule_in`. """ def get_retry_except...
procrastinate/retry.py
from typing import Optional, Union import attr import pendulum from procrastinate import exceptions class BaseRetryStrategy: """ If you want to implement your own retry strategy, you can inherit from this class. Children classes only need to implement `get_schedule_in`. """ def get_retry_except...
0.949693
0.357483
# stdlib imports from __future__ import print_function import logging import threading from datetime import datetime # third-party libraries from flask import Flask, request # application imports import olivaw.tasks as tasks import olivaw.telegram as telegram from olivaw.settings import secrets from olivaw.schedule imp...
olivaw/main.py
# stdlib imports from __future__ import print_function import logging import threading from datetime import datetime # third-party libraries from flask import Flask, request # application imports import olivaw.tasks as tasks import olivaw.telegram as telegram from olivaw.settings import secrets from olivaw.schedule imp...
0.514644
0.052328
import random from biosim.animal import Herbivore, Carnivore class Island: """The Island object collects all landscape cells in the map and keeps track of animals. :param map_str: The representation of cell types in the simulation :type map_str: str :Example: .. code-block:: python ...
biosim/landscape.py
import random from biosim.animal import Herbivore, Carnivore class Island: """The Island object collects all landscape cells in the map and keeps track of animals. :param map_str: The representation of cell types in the simulation :type map_str: str :Example: .. code-block:: python ...
0.750736
0.557364
from contextlib import contextmanager import ast import sys @contextmanager def parse_source(path): with open(path) as f: content = f.read() yield SourceCode(content) def bold(s): s = '\033[1m' + str(s) + '\033[0m' return s def grepfunc(): query = sys.argv[1] path = sys.argv[2]...
pygrep.py
from contextlib import contextmanager import ast import sys @contextmanager def parse_source(path): with open(path) as f: content = f.read() yield SourceCode(content) def bold(s): s = '\033[1m' + str(s) + '\033[0m' return s def grepfunc(): query = sys.argv[1] path = sys.argv[2]...
0.289171
0.144752
import marshmallow from commercetools import helpers, types from commercetools.schemas._common import ( BaseResourceSchema, ReferenceSchema, ResourceIdentifierSchema, ) from commercetools.schemas._type import FieldContainerField __all__ = [ "InventoryEntryAddQuantityActionSchema", "InventoryEntry...
src/commercetools/schemas/_inventory.py
import marshmallow from commercetools import helpers, types from commercetools.schemas._common import ( BaseResourceSchema, ReferenceSchema, ResourceIdentifierSchema, ) from commercetools.schemas._type import FieldContainerField __all__ = [ "InventoryEntryAddQuantityActionSchema", "InventoryEntry...
0.661704
0.175414
"""Test the TcEx Batch Module.""" from datetime import datetime import re import pytest # pylint: disable=R0201,W0201 class TestUtils: """Test the TcEx Batch Module.""" def setup_class(self): """Configure setup before all tests.""" @pytest.mark.parametrize( 'date,tz,results', [ ...
tests/utils/test_date_methods.py
"""Test the TcEx Batch Module.""" from datetime import datetime import re import pytest # pylint: disable=R0201,W0201 class TestUtils: """Test the TcEx Batch Module.""" def setup_class(self): """Configure setup before all tests.""" @pytest.mark.parametrize( 'date,tz,results', [ ...
0.511473
0.411702
import torch import torch.nn as nn import torch.nn.functional as F # Define model architecture class SetConv2(nn.Module): def __init__(self, sample_feats, predicate_feats, join_feats, scard_feats, hid_units): super(SetConv2, self).__init__() self.sample_mlp1 = nn.Linear(sample_feats, hid_units) ...
code/model/model2.py
import torch import torch.nn as nn import torch.nn.functional as F # Define model architecture class SetConv2(nn.Module): def __init__(self, sample_feats, predicate_feats, join_feats, scard_feats, hid_units): super(SetConv2, self).__init__() self.sample_mlp1 = nn.Linear(sample_feats, hid_units) ...
0.780662
0.465934