code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import logging from datetime import datetime from sqlalchemy import create_engine from sqlalchemy.sql import exists from sqlalchemy.orm import sessionmaker from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from orion.core.orms.mag_orm import FieldOfStudy, FosHierarchy, FosMetad...
orion/core/operators/mag_collect_task.py
import logging from datetime import datetime from sqlalchemy import create_engine from sqlalchemy.sql import exists from sqlalchemy.orm import sessionmaker from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from orion.core.orms.mag_orm import FieldOfStudy, FosHierarchy, FosMetad...
0.661158
0.216518
import inspect import os from abc import abstractmethod from typing import Any, Dict, Tuple, Optional, Type from unittest import TestCase from ._AbstractTestMeta import AbstractTestMeta from .serialisation import BytesSerialiser, StringSerialiser, RegressionSerialiser from ._functions import get_subject_args, get_skip...
src/wai/test/_AbstractTest.py
import inspect import os from abc import abstractmethod from typing import Any, Dict, Tuple, Optional, Type from unittest import TestCase from ._AbstractTestMeta import AbstractTestMeta from .serialisation import BytesSerialiser, StringSerialiser, RegressionSerialiser from ._functions import get_subject_args, get_skip...
0.845481
0.356699
import datetime import os import pycodestyle import unittest import faulthandler faulthandler.enable() # to debug seg faults and timeouts import cfdm class styleTest(unittest.TestCase): """Test all Python files against Python style conventions.""" def setUp(self): """Preparations called immediate...
cfdm/test/test_style.py
import datetime import os import pycodestyle import unittest import faulthandler faulthandler.enable() # to debug seg faults and timeouts import cfdm class styleTest(unittest.TestCase): """Test all Python files against Python style conventions.""" def setUp(self): """Preparations called immediate...
0.645008
0.25247
from stomp_message_controller import StompMessageController from stomp_message import StompMessage class MailDomainServiceController(StompMessageController): stomp_tasks = ["CreateVirtualMailbox", "RemoveVirtualMailbox", "EnableVirtualMailbox", "DisableVirtualMailbox", "SetVirtualMailboxPasswd", "CreateVirtualMailA...
virtual_mail_management_processor/mail_domain_service_controller.py
from stomp_message_controller import StompMessageController from stomp_message import StompMessage class MailDomainServiceController(StompMessageController): stomp_tasks = ["CreateVirtualMailbox", "RemoveVirtualMailbox", "EnableVirtualMailbox", "DisableVirtualMailbox", "SetVirtualMailboxPasswd", "CreateVirtualMailA...
0.087058
0.067639
import calendar from hashlib import md5 from datetime import datetime, timedelta import uuid from snuba import settings from snuba.datasets.factory import enforce_table_writer, get_dataset from snuba.clickhouse.native import ClickhousePool from snuba.redis import redis_client def wrap_raw_event(event): "Wrap a r...
tests/base.py
import calendar from hashlib import md5 from datetime import datetime, timedelta import uuid from snuba import settings from snuba.datasets.factory import enforce_table_writer, get_dataset from snuba.clickhouse.native import ClickhousePool from snuba.redis import redis_client def wrap_raw_event(event): "Wrap a r...
0.507568
0.244062
import os import pygame from labyrinth_generator import generate from random import randint from time import time, sleep import mazeFinder BLOCKSIZE = 16 WIDTH = 590 HEIGHT = 480 DELAY = 20 WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLACK = (0, 0, 0) # Class for the orange dude class Player(obje...
labyrinth_explorer.py
import os import pygame from labyrinth_generator import generate from random import randint from time import time, sleep import mazeFinder BLOCKSIZE = 16 WIDTH = 590 HEIGHT = 480 DELAY = 20 WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLACK = (0, 0, 0) # Class for the orange dude class Player(obje...
0.592667
0.355076
import copy from six.moves.urllib import parse as urlparse from testtools import matchers from watcherclient.tests.unit import utils import watcherclient.v1.audit_template AUDIT_TMPL1 = { 'id': 1, 'uuid': 'f8e47706-efcf-49a4-a5c4-af604eb492f2', 'name': 'Audit Template 1', 'description': 'Audit Templ...
watcherclient/tests/unit/v1/test_audit_template.py
import copy from six.moves.urllib import parse as urlparse from testtools import matchers from watcherclient.tests.unit import utils import watcherclient.v1.audit_template AUDIT_TMPL1 = { 'id': 1, 'uuid': 'f8e47706-efcf-49a4-a5c4-af604eb492f2', 'name': 'Audit Template 1', 'description': 'Audit Templ...
0.35421
0.153264
from django.db import models from django.contrib.postgres.fields import JSONField from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from ..data.models import Jurisdiction, LegislativeSession OBJECT_TYPES = ( ("jurisdiction", "Jurisdiction")...
openstates/reports/models.py
from django.db import models from django.contrib.postgres.fields import JSONField from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from ..data.models import Jurisdiction, LegislativeSession OBJECT_TYPES = ( ("jurisdiction", "Jurisdiction")...
0.566978
0.194387
from lark import Lark, Transformer, v_args from pecan.lang.optimizer.tools import * from pecan.lang.ir import * from pecan.lang.parser import PecanTransformer from pecan.lang.ast_to_ir import ASTToIR from pecan.lang.optimizer.redundant_variable_optimizer import RedundantVariableOptimizer from pecan.lang.optimizer.un...
test/test_optimizer_tools.py
from lark import Lark, Transformer, v_args from pecan.lang.optimizer.tools import * from pecan.lang.ir import * from pecan.lang.parser import PecanTransformer from pecan.lang.ast_to_ir import ASTToIR from pecan.lang.optimizer.redundant_variable_optimizer import RedundantVariableOptimizer from pecan.lang.optimizer.un...
0.732305
0.511534
from __future__ import print_function import logging import os import shutil import sys from cfn_flip import to_yaml from ..runway_command import RunwayCommand from ...cfngin.context import Context from ...env_mgr.tfenv import get_latest_tf_version LOGGER = logging.getLogger('runway') ROOT = os.path.dirname(os.path...
runway/commands/runway/gen_sample.py
from __future__ import print_function import logging import os import shutil import sys from cfn_flip import to_yaml from ..runway_command import RunwayCommand from ...cfngin.context import Context from ...env_mgr.tfenv import get_latest_tf_version LOGGER = logging.getLogger('runway') ROOT = os.path.dirname(os.path...
0.476336
0.183722
def docs(**kwargs): """ Annotate the decorated view function with the specified Swagger attributes. Usage: .. code-block:: python from aiohttp import web @docs(tags=['my_tag'], summary='Test method summary', description='Test method description', ...
aiohttp_apispec/decorators.py
def docs(**kwargs): """ Annotate the decorated view function with the specified Swagger attributes. Usage: .. code-block:: python from aiohttp import web @docs(tags=['my_tag'], summary='Test method summary', description='Test method description', ...
0.683842
0.350449
import os import sys from typing import Tuple import inquirer from cli.platform.error import CliError from winnow.pipeline.pipeline_context import PipelineContext from winnow.remote.connect import RepoConnector def ask_password( message, literal_pass: Tuple[str, str] = (None, None), file_pass: Tuple[str, str] =...
cli/cli/platform/arguments.py
import os import sys from typing import Tuple import inquirer from cli.platform.error import CliError from winnow.pipeline.pipeline_context import PipelineContext from winnow.remote.connect import RepoConnector def ask_password( message, literal_pass: Tuple[str, str] = (None, None), file_pass: Tuple[str, str] =...
0.525856
0.096578
from setuptools import setup, find_packages import grxtestassert desc = """ assertpy ======== Simple assertions library for unit testing in Python with a nice fluent API. Supports both Python 2 and 3. Usage ----- Just import the ``assert_that`` function, and away you go...:: from assertpy import assert_that ...
setup.py
from setuptools import setup, find_packages import grxtestassert desc = """ assertpy ======== Simple assertions library for unit testing in Python with a nice fluent API. Supports both Python 2 and 3. Usage ----- Just import the ``assert_that`` function, and away you go...:: from assertpy import assert_that ...
0.838746
0.653473
import random class HashTable(object): """Hash Table.""" def __init__(self, size=6, hash_type='additive'): """Instantiate empty hash table.""" hash_types = {'additive': self._additive, 'elf': self._elf} if hash_type not in hash_types: raise ValueErro...
src/hash.py
import random class HashTable(object): """Hash Table.""" def __init__(self, size=6, hash_type='additive'): """Instantiate empty hash table.""" hash_types = {'additive': self._additive, 'elf': self._elf} if hash_type not in hash_types: raise ValueErro...
0.719876
0.183118
from tkinter import messagebox, filedialog from tkinter import * from PIL import Image, ImageTk import numpy as np import xml.dom.minidom import xml.dom import glob import os # colors for the bboxes COLORS = ['red', 'orange', 'cyan', 'green', 'blue', 'purple', 'pink', 'black', 'gray'] # classes name CLASSES = ['aeropl...
main.py
from tkinter import messagebox, filedialog from tkinter import * from PIL import Image, ImageTk import numpy as np import xml.dom.minidom import xml.dom import glob import os # colors for the bboxes COLORS = ['red', 'orange', 'cyan', 'green', 'blue', 'purple', 'pink', 'black', 'gray'] # classes name CLASSES = ['aeropl...
0.466846
0.21869
import os import sys import numpy as np import time import pickle from queue import deque import torch import copy """ Hyperparameter tuning script. Runs jobs specified by a hyperparameter search space and launches them on GPUs. The script always checks if any jobs have been completed, and, if they have, immediately ...
tuning.py
import os import sys import numpy as np import time import pickle from queue import deque import torch import copy """ Hyperparameter tuning script. Runs jobs specified by a hyperparameter search space and launches them on GPUs. The script always checks if any jobs have been completed, and, if they have, immediately ...
0.519521
0.535584
NegativeTime = -1 ConditionNotSatisfied = -2 NoWorkerExists = -3 WrongBuildingName = -4 WrongUpgradeName = -5 WrongUnitName = -6 UnknownError = -7 WrongFlag = -8 SupplyBlocked = -9 NoBarrackExists = -10 NoOneGathersGasOrMineral = -11 MineralFieldsAreFull = -12 NoOneGathersGas = -13 GasLayersAreFull = -14 NotEnoughWorke...
error.py
NegativeTime = -1 ConditionNotSatisfied = -2 NoWorkerExists = -3 WrongBuildingName = -4 WrongUpgradeName = -5 WrongUnitName = -6 UnknownError = -7 WrongFlag = -8 SupplyBlocked = -9 NoBarrackExists = -10 NoOneGathersGasOrMineral = -11 MineralFieldsAreFull = -12 NoOneGathersGas = -13 GasLayersAreFull = -14 NotEnoughWorke...
0.301773
0.190705
import heterocl as hcl import os, sys import numpy as np import time hcl.init(hcl.Float()) def test_gemm_cpu(target=None): A = hcl.placeholder((32, 32), "A") B = hcl.placeholder((32, 32), "B") def gemm(A, B): k = hcl.reduce_axis(0, 32, "k") C = hcl.compute((32, 32), lambda i, j: ...
tests/mlir/hcl-mlir/test_gemm.py
import heterocl as hcl import os, sys import numpy as np import time hcl.init(hcl.Float()) def test_gemm_cpu(target=None): A = hcl.placeholder((32, 32), "A") B = hcl.placeholder((32, 32), "B") def gemm(A, B): k = hcl.reduce_axis(0, 32, "k") C = hcl.compute((32, 32), lambda i, j: ...
0.282097
0.270387
from pyfaidx import Fasta import sys import re if len(sys.argv)>=2: gen = sys.argv[1] chr = sys.argv[2] pos = sys.argv[3] desc = sys.argv[4] f = open("Ugene.txt", "a") if gen.upper() == "GB": genome = Fasta("H:/data/Gb/GB.fa") p = pos.split(":") f.write(">") ...
bio/Retrieve_seqs.py
from pyfaidx import Fasta import sys import re if len(sys.argv)>=2: gen = sys.argv[1] chr = sys.argv[2] pos = sys.argv[3] desc = sys.argv[4] f = open("Ugene.txt", "a") if gen.upper() == "GB": genome = Fasta("H:/data/Gb/GB.fa") p = pos.split(":") f.write(">") ...
0.084888
0.118819
import subprocess # cheap python 2/3 compatability try: unicode except NameError: unicode = str def _divider(divider): return { u'contents': divider, u'highlight_groups': ['window_status'] } def _segment(num_mails, search): try: icon = search['icon'] if icon != u""...
powerline_notmuch/segments.py
import subprocess # cheap python 2/3 compatability try: unicode except NameError: unicode = str def _divider(divider): return { u'contents': divider, u'highlight_groups': ['window_status'] } def _segment(num_mails, search): try: icon = search['icon'] if icon != u""...
0.526099
0.173428
#coding:utf-8 import System clr.ImportExtensions(System.Linq) from pycad.runtime import * @command(flags = acrx.CommandFlags.Redraw) def mycir(): with dbtrans(commit = True) as tr: btr = tr.opencurrspace(acdb.OpenMode.ForWrite) res = ed.GetPoint('\n输入一个点') if res.Status == aced...
Projects/Debug/pytest/cmds/__init__.py
#coding:utf-8 import System clr.ImportExtensions(System.Linq) from pycad.runtime import * @command(flags = acrx.CommandFlags.Redraw) def mycir(): with dbtrans(commit = True) as tr: btr = tr.opencurrspace(acdb.OpenMode.ForWrite) res = ed.GetPoint('\n输入一个点') if res.Status == aced...
0.201342
0.142799
from collections import OrderedDict import pytest from .. import * from .subroutines import ( findRecursionPoints, spillLocalSlotsDuringRecursion, resolveSubroutines, ) def test_findRecursionPoints_empty(): subroutines = dict() expected = dict() actual = findRecursionPoints(subroutines) ...
pyteal/compiler/subroutines_test.py
from collections import OrderedDict import pytest from .. import * from .subroutines import ( findRecursionPoints, spillLocalSlotsDuringRecursion, resolveSubroutines, ) def test_findRecursionPoints_empty(): subroutines = dict() expected = dict() actual = findRecursionPoints(subroutines) ...
0.728652
0.26491
__author__ = "<NAME>" __date__ = "3 May 2008" __version__ = "1.0" import datetime import wx #====================================================================== # Editor Registry # Module level variable _cellEditorRegistrySingleton = None def CellEditorRegistry(): """ Return the registry that is managing...
external/ObjectListView/CellEditor.py
__author__ = "<NAME>" __date__ = "3 May 2008" __version__ = "1.0" import datetime import wx #====================================================================== # Editor Registry # Module level variable _cellEditorRegistrySingleton = None def CellEditorRegistry(): """ Return the registry that is managing...
0.621081
0.23926
__all__ = [ 'HookPriority', 'HookEntry', 'HookList', ] class HookPriority(object): """ Pre-defined hook priorities for :class:`~tfsnippet.trainer.BaseTrainer` and :class:`~tfsnippet.trainer.Evaluator`. Smaller values take higher priorities. """ EVALUATION = VALIDATION = 500 DEFAULT =...
tfsnippet/trainer/hooks.py
__all__ = [ 'HookPriority', 'HookEntry', 'HookList', ] class HookPriority(object): """ Pre-defined hook priorities for :class:`~tfsnippet.trainer.BaseTrainer` and :class:`~tfsnippet.trainer.Evaluator`. Smaller values take higher priorities. """ EVALUATION = VALIDATION = 500 DEFAULT =...
0.950076
0.402921
import sys import os from bitcoin.bip39 import mnemonic_from_bytes, mnemonic_to_seed from bitcoin.bip32 import HDKey, parse_path from bitcoin.hashes import hash160 from bitcoin.networks import NETWORKS import hashlib import pyb from hardware_wallet.classes.psbt import PSBT from hardware_wallet.classes.psbt_validator ...
hardware_wallet/controller.py
import sys import os from bitcoin.bip39 import mnemonic_from_bytes, mnemonic_to_seed from bitcoin.bip32 import HDKey, parse_path from bitcoin.hashes import hash160 from bitcoin.networks import NETWORKS import hashlib import pyb from hardware_wallet.classes.psbt import PSBT from hardware_wallet.classes.psbt_validator ...
0.449634
0.281103
## Índices dos valores máximos ou mínimos * Os métodos **idxmin()** e **idxmax()** retornam o *index* cuja entrada fornece o valor mínimo ou máximo da *Serie* ou *DataFrame*. * Se houverem múltiplas ocorrências de mínimos ou máximos, o método retorna a primeira ocorrência. import numpy as np import pandas as pd imp...
_build/jupyter_execute/ipynb/06b-intro-pandas2.py
def verifica_final_do(palavra): return palavra.lower()[-2:] == 'do' dados_covid_PB.loc[(dados_covid_PB.obitosNovos>25) & (dados_covid_PB.casosNovos>1500)]
0.415966
0.426919
from sklearn.ensemble import AdaBoostClassifier from sklearn.linear_model import LogisticRegression import numpy as np __author__ = '<NAME>' class LogisticAdaBoost(AdaBoostClassifier): """ This class implements AdaBoost with a logistic regression for each class, in order to fine tune the voting weights o...
linear/__init__.py
from sklearn.ensemble import AdaBoostClassifier from sklearn.linear_model import LogisticRegression import numpy as np __author__ = '<NAME>' class LogisticAdaBoost(AdaBoostClassifier): """ This class implements AdaBoost with a logistic regression for each class, in order to fine tune the voting weights o...
0.951051
0.84916
import os from praatio import textgrid from datetime import datetime from tqdm import tqdm def main(args): current_time = datetime.now().strftime("%H%M%S") libri_path = args.LibriTTS train_path_list = ['train-clean-100', 'train-clean-360', 'train-other-500', 'dev-clean', 'dev-other', 'test-clean', 'test-ot...
pytorch/diora/speech/preprocessing/check.py
import os from praatio import textgrid from datetime import datetime from tqdm import tqdm def main(args): current_time = datetime.now().strftime("%H%M%S") libri_path = args.LibriTTS train_path_list = ['train-clean-100', 'train-clean-360', 'train-other-500', 'dev-clean', 'dev-other', 'test-clean', 'test-ot...
0.062245
0.07221
import os import zipfile from os import path from subprocess import check_call import platform import tarfile try: from urllib.request import urlopen, HTTPError except ImportError: from urllib2 import urlopen, HTTPError class SnapshotNotFound(BaseException): pass SOURCE = "https://dl.dropboxuserconten...
ws/snapshot.py
import os import zipfile from os import path from subprocess import check_call import platform import tarfile try: from urllib.request import urlopen, HTTPError except ImportError: from urllib2 import urlopen, HTTPError class SnapshotNotFound(BaseException): pass SOURCE = "https://dl.dropboxuserconten...
0.318167
0.052449
# -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown he...
Docs/source/conf.py
# -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown he...
0.364551
0.075995
from aetherling.modules.hydrate import Hydrate, Dehydrate from aetherling.modules.map_fully_parallel_sequential import MapParallel from magma.simulator.coreir_simulator import CoreIRSimulator import coreir from magma.scope import Scope from aetherling.helpers.image_RAM import * from aetherling.modules.upsample import U...
tests/test_updown.py
from aetherling.modules.hydrate import Hydrate, Dehydrate from aetherling.modules.map_fully_parallel_sequential import MapParallel from magma.simulator.coreir_simulator import CoreIRSimulator import coreir from magma.scope import Scope from aetherling.helpers.image_RAM import * from aetherling.modules.upsample import U...
0.47171
0.338514
import os import os.path as osp import pandas as pd from ..load_sim import LoadSim from ..util.units import Units from .hst import Hst from .dust_pol import DustPol class LoadSimFeedbackTest(LoadSim, Hst, DustPol): """LoadSim class for analyzing LoadSimFeedbackTest simulations. """ def __init__(self...
pyathena/feedback_test/load_sim_feedback_test.py
import os import os.path as osp import pandas as pd from ..load_sim import LoadSim from ..util.units import Units from .hst import Hst from .dust_pol import DustPol class LoadSimFeedbackTest(LoadSim, Hst, DustPol): """LoadSim class for analyzing LoadSimFeedbackTest simulations. """ def __init__(self...
0.623148
0.223271
import unittest2 import json from consts.award_type import AwardType from datafeeds.usfirst_event_awards_parser import UsfirstEventAwardsParser def convert_to_comparable(data): """ Converts jsons to dicts so that elements can be more easily compared """ if type(data) == list: return [convert_...
tests/test_usfirst_event_awards_parser.py
import unittest2 import json from consts.award_type import AwardType from datafeeds.usfirst_event_awards_parser import UsfirstEventAwardsParser def convert_to_comparable(data): """ Converts jsons to dicts so that elements can be more easily compared """ if type(data) == list: return [convert_...
0.575827
0.525491
import torch class LSTM_Music(torch.nn.Module): def __init__(self, vocab_size, embed_size, hidden_size, latent_size, num_layers=1): super(LSTM_Music, self).__init__() self.device = "cuda" if torch.cuda.is_available() else "cpu" # Variables self.num_layers = num_layers self.lstm_factor = num...
model.py
import torch class LSTM_Music(torch.nn.Module): def __init__(self, vocab_size, embed_size, hidden_size, latent_size, num_layers=1): super(LSTM_Music, self).__init__() self.device = "cuda" if torch.cuda.is_available() else "cpu" # Variables self.num_layers = num_layers self.lstm_factor = num...
0.754825
0.450118
from datetime import datetime from decimal import Decimal import pytest from byceps.services.shop.order.models.orderer import Orderer from byceps.services.shop.order import service as order_service from byceps.services.shop.order.transfer.models import ( Order, OrderNumber, OrderState, PaymentState, )...
tests/unit/services/shop/order/test_order_state.py
from datetime import datetime from decimal import Decimal import pytest from byceps.services.shop.order.models.orderer import Orderer from byceps.services.shop.order import service as order_service from byceps.services.shop.order.transfer.models import ( Order, OrderNumber, OrderState, PaymentState, )...
0.69181
0.224331
import numpy as np from akg.utils import kernel_exec as utils from tests.common.test_op.ascend import SecondOrder_diag_combine_matrix from tests.common.gen_random import random_gaussian def diag_combine_matrix_run(shape, dtype, attrs): """ ops run func. """ if len(shape) == 1: shape = shape[0]...
tests/common/test_run/ascend/SecondOrder_diag_combine_matrix_run.py
import numpy as np from akg.utils import kernel_exec as utils from tests.common.test_op.ascend import SecondOrder_diag_combine_matrix from tests.common.gen_random import random_gaussian def diag_combine_matrix_run(shape, dtype, attrs): """ ops run func. """ if len(shape) == 1: shape = shape[0]...
0.447219
0.535402
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import json import os import tensorflow as tf import tensorflowjs as tfjs INDEX_FROM = 3 # Offset in word index. Used during word index lookup and reverse lookup. def get_word_index(reverse...
sentiment/python/imdb.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import json import os import tensorflow as tf import tensorflowjs as tfjs INDEX_FROM = 3 # Offset in word index. Used during word index lookup and reverse lookup. def get_word_index(reverse...
0.839734
0.553807
from __future__ import annotations import logging from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ICON, ATTR_ID, ATTR_NAME, ATTR_STATE, ATTR_UNIT_OF_MEASUREMEN...
custom_components/plugwise/sensor.py
from __future__ import annotations import logging from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ICON, ATTR_ID, ATTR_NAME, ATTR_STATE, ATTR_UNIT_OF_MEASUREMEN...
0.771843
0.09739
import pylab import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.pyplot import MultipleLocator import numpy as np import math legend_font = {'family' : 'Times New Roman', 'weight' : 'bold', 'size' : 5, } label_font = {'family' : 'Times New Roman', 'weight' : 'normal', 'size' : 6.5, ...
exp/dag_drawer.py
import pylab import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.pyplot import MultipleLocator import numpy as np import math legend_font = {'family' : 'Times New Roman', 'weight' : 'bold', 'size' : 5, } label_font = {'family' : 'Times New Roman', 'weight' : 'normal', 'size' : 6.5, ...
0.398758
0.435181
from datetime import datetime import numpy as np import pandas as pd from gensim.models import Doc2Vec from keras.layers.core import Dense, Dropout, Activation from keras.models import Sequential from keras.utils import np_utils from sklearn.cross_validation import KFold import cfg # -----------------------load dat...
dm_nn_stack.py
from datetime import datetime import numpy as np import pandas as pd from gensim.models import Doc2Vec from keras.layers.core import Dense, Dropout, Activation from keras.models import Sequential from keras.utils import np_utils from sklearn.cross_validation import KFold import cfg # -----------------------load dat...
0.501709
0.238839
import subprocess import time import os from urllib import request import requests from bs4 import BeautifulSoup def get_all_species(): """Create dictionary with available Marine Mammal species in the Watkins database. The database can be found here https://cis.whoi.edu/science/B/whalesounds/index.cfm ...
seasounds/get_data.py
import subprocess import time import os from urllib import request import requests from bs4 import BeautifulSoup def get_all_species(): """Create dictionary with available Marine Mammal species in the Watkins database. The database can be found here https://cis.whoi.edu/science/B/whalesounds/index.cfm ...
0.661704
0.239027
from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.test import TestCase, override_settings from flags.conditions.validators import ( validate_boolean, validate_date, validate_parameter, validate_path_re, validate_user, ) class ValidatePar...
flags/tests/test_conditions_validators.py
from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.test import TestCase, override_settings from flags.conditions.validators import ( validate_boolean, validate_date, validate_parameter, validate_path_re, validate_user, ) class ValidatePar...
0.68637
0.442998
from __future__ import annotations from collections.abc import Sequence from time import time from discord.ext import commands import discord from core import Cog, RT, t, DatabaseManager, cursor from rtlib.common.json import dumps, loads from rtlib.common.cacher import Cacher from data import ROLE_NOTFOUND, FORB...
cogs/server-management/role_keeper.py
from __future__ import annotations from collections.abc import Sequence from time import time from discord.ext import commands import discord from core import Cog, RT, t, DatabaseManager, cursor from rtlib.common.json import dumps, loads from rtlib.common.cacher import Cacher from data import ROLE_NOTFOUND, FORB...
0.576184
0.116714
import threading import serial import time from serial import Serial class Ev3: class _MsgType: class Mode: def __init__(self, first, second): self.second = second self.first = first Speed = Mode(10, 165) Start = Mode(8, 166) Stop = Mode...
ev3/ev3.py
import threading import serial import time from serial import Serial class Ev3: class _MsgType: class Mode: def __init__(self, first, second): self.second = second self.first = first Speed = Mode(10, 165) Start = Mode(8, 166) Stop = Mode...
0.451327
0.16238
import unittest import hashlib from blockdag import build_block_dag def _hashfunc(value): return hashlib.sha256(value).hexdigest() def _gen_simple_dag(): data = { "a": {"data": 5}, "b": {"data": "potato"}, "c": {"data": [1, 2, "three", [4]]}, "d": {"not_data": 4}, } e...
tests/test_blockdag.py
import unittest import hashlib from blockdag import build_block_dag def _hashfunc(value): return hashlib.sha256(value).hexdigest() def _gen_simple_dag(): data = { "a": {"data": 5}, "b": {"data": "potato"}, "c": {"data": [1, 2, "three", [4]]}, "d": {"not_data": 4}, } e...
0.705379
0.756537
from pathlib import Path from typing import List from itertools import product import sys import numpy as np # type: ignore import pandas as pd # type: ignore from src.util import ( read_parquet, write_parquet, WIND_DIRS, WIND_VELS, RAINS, ) TIME_RANGES = {"2020": [2020], "2016-2020": [2016, 2017...
prep/s3_aggregate_data.py
from pathlib import Path from typing import List from itertools import product import sys import numpy as np # type: ignore import pandas as pd # type: ignore from src.util import ( read_parquet, write_parquet, WIND_DIRS, WIND_VELS, RAINS, ) TIME_RANGES = {"2020": [2020], "2016-2020": [2016, 2017...
0.489259
0.510558
BASIC_EBS_OFFER_SKU = 'HY3BZPP2B6K8MSJF' BASIC_IOPS_OFFER_SKU = 'D8RDVC722HKNR55G' BASIC_EBS_OFFER_DATA = { 'HY3BZPP2B6K8MSJF': { 'serviceCode': 'AmazonEC2', 'product': { 'productFamily': 'Storage', 'sku' : 'HY3BZPP2B6K8MSJF', 'attributes' : { 'ser...
tests/data/ebs_offer.py
BASIC_EBS_OFFER_SKU = 'HY3BZPP2B6K8MSJF' BASIC_IOPS_OFFER_SKU = 'D8RDVC722HKNR55G' BASIC_EBS_OFFER_DATA = { 'HY3BZPP2B6K8MSJF': { 'serviceCode': 'AmazonEC2', 'product': { 'productFamily': 'Storage', 'sku' : 'HY3BZPP2B6K8MSJF', 'attributes' : { 'ser...
0.501221
0.258092
import networkx as nx import numpy as np import os import time import pandas as pd from sscd import SSCD from ssnmf import SSNMF import scipy.sparse as ssp """Functions definitions""" def generate_synthetic_graph(n_node_par_com, n_com=2, p_in=0.1, p_out=0.001): sizes = [n_node_par_com] * n_com g = nx.random_p...
compare_time.py
import networkx as nx import numpy as np import os import time import pandas as pd from sscd import SSCD from ssnmf import SSNMF import scipy.sparse as ssp """Functions definitions""" def generate_synthetic_graph(n_node_par_com, n_com=2, p_in=0.1, p_out=0.001): sizes = [n_node_par_com] * n_com g = nx.random_p...
0.550366
0.341967
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ... import meta as _meta __all__ = [ 'CrossVersionObjectReference', 'HorizontalPodAutoscaler', 'HorizontalPodAutoscalerSpec', '...
sdk/python/pulumi_kubernetes/autoscaling/v1/outputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ... import meta as _meta __all__ = [ 'CrossVersionObjectReference', 'HorizontalPodAutoscaler', 'HorizontalPodAutoscalerSpec', '...
0.905713
0.087291
import asyncio import contextlib import ipaddress import logging import urllib.parse import ssl import socket from aiodnsresolver import ( TYPES, DnsError, Resolver, ResolverLoggerAdapter, ) class HttpError(Exception): pass class HttpConnectionError(HttpError): pass class HttpDnsError(Htt...
lowhaio.py
import asyncio import contextlib import ipaddress import logging import urllib.parse import ssl import socket from aiodnsresolver import ( TYPES, DnsError, Resolver, ResolverLoggerAdapter, ) class HttpError(Exception): pass class HttpConnectionError(HttpError): pass class HttpDnsError(Htt...
0.404743
0.070336
from dataclasses import dataclass import numpy as np @dataclass class VentLine: """Class for storing Hydrothermal vent_line data. The coordinates are zero-indexed!""" x_start: int x_end: int y_start: int y_end: int def is_diagonal(self): y_dif = abs(self.y_start - self.y_end) ...
2021/Day 05/Src/__main__.py
from dataclasses import dataclass import numpy as np @dataclass class VentLine: """Class for storing Hydrothermal vent_line data. The coordinates are zero-indexed!""" x_start: int x_end: int y_start: int y_end: int def is_diagonal(self): y_dif = abs(self.y_start - self.y_end) ...
0.68056
0.613294
from collections import UserDict from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock, Mock, patch import flask import pytest import requests import responses import main # Create a fake "app" for generating test request contexts. @pytest.fixture(scope="module") def app(): ret...
functions/tips/main_test.py
from collections import UserDict from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock, Mock, patch import flask import pytest import requests import responses import main # Create a fake "app" for generating test request contexts. @pytest.fixture(scope="module") def app(): ret...
0.737442
0.18954
import os from pathlib import Path from random import SystemRandom import subprocess import sys import time from urllib.request import pathname2url import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk gi.require_version('Gst', '1.0') from gi.repository import Gst VOLUME_LEVEL_PERCENT = .6 SNOOZE_...
alarm.py
import os from pathlib import Path from random import SystemRandom import subprocess import sys import time from urllib.request import pathname2url import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk gi.require_version('Gst', '1.0') from gi.repository import Gst VOLUME_LEVEL_PERCENT = .6 SNOOZE_...
0.354545
0.0704
import re from bs4 import BeautifulSoup from collections import namedtuple from .errors import LeakedError from .requests import get_search_results class Provider(object): """Base class for all providers.""" def __init__(self, name): self.name = name def build_module_query_url(self, module): ...
leaked/providers.py
import re from bs4 import BeautifulSoup from collections import namedtuple from .errors import LeakedError from .requests import get_search_results class Provider(object): """Base class for all providers.""" def __init__(self, name): self.name = name def build_module_query_url(self, module): ...
0.621426
0.228834
import json import time import logging import pandas as pd from anytree import Node, PreOrderIter from pandas import json_normalize from stix_shifter.stix_translation import stix_translation from stix_shifter.stix_transmission import stix_transmission class StixShifterDataFrame(object): def __init__(self): ...
pyclient/stix_shifter_dataframe.py
import json import time import logging import pandas as pd from anytree import Node, PreOrderIter from pandas import json_normalize from stix_shifter.stix_translation import stix_translation from stix_shifter.stix_transmission import stix_transmission class StixShifterDataFrame(object): def __init__(self): ...
0.253491
0.104706
import pickle from abc import ABC, abstractmethod import numpy as np from keras.layers import Dense, Reshape from keras.models import Sequential from keras.regularizers import l2 import shorttext.utils.classification_exceptions as e import shorttext.utils.kerasmodel_io as kerasio from shorttext.utils.compactmodel_io ...
shorttext/stack/stacking.py
import pickle from abc import ABC, abstractmethod import numpy as np from keras.layers import Dense, Reshape from keras.models import Sequential from keras.regularizers import l2 import shorttext.utils.classification_exceptions as e import shorttext.utils.kerasmodel_io as kerasio from shorttext.utils.compactmodel_io ...
0.941698
0.61202
from confmodel.fields import ConfigList from vumi.middleware import BaseMiddleware from vumi.middleware.base import BaseMiddlewareConfig from vumi.config import ConfigServerEndpoint from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from twisted.cred import portal from twisted.co...
vumi/middleware/manhole.py
from confmodel.fields import ConfigList from vumi.middleware import BaseMiddleware from vumi.middleware.base import BaseMiddlewareConfig from vumi.config import ConfigServerEndpoint from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from twisted.cred import portal from twisted.co...
0.738198
0.065845
from vector_solver import IqSolver from numpy import array, zeros from abc import abstractmethod from sklearn.pipeline import Pipeline from sklearn.svm import SVC from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer import re import os import json def l(s): s = s.lower() ...
deprecated/PUTIq.01/PUTIq/putiq/putiq/question_processor_core.py
from vector_solver import IqSolver from numpy import array, zeros from abc import abstractmethod from sklearn.pipeline import Pipeline from sklearn.svm import SVC from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer import re import os import json def l(s): s = s.lower() ...
0.590543
0.325279
import numpy as np import logging import warnings class FeatureInfo: def __init__(self): self.name = None # include empty self.ma = None # note the second last is for empty, the last is for special value # counter self.ctr = None # counter for positive label ...
src/data_tool/feature.py
import numpy as np import logging import warnings class FeatureInfo: def __init__(self): self.name = None # include empty self.ma = None # note the second last is for empty, the last is for special value # counter self.ctr = None # counter for positive label ...
0.249905
0.320409
import time classesMap = {"fresh_phys":"Freshman Physics", "ap_phys_b":"AP Physics B", "ap_phys_c":"AP Physics C", "conc_chem":"Conceptual Chemistry", "accel_chem":"Accelerated Chemistry", "ap_chem":"AP Chemistry", "o_chem":"Organic Chemistry", "bio":"Biology", "at_bio":"AT Biology", "anat_and_phys":...
app/mshc_lib.py
import time classesMap = {"fresh_phys":"Freshman Physics", "ap_phys_b":"AP Physics B", "ap_phys_c":"AP Physics C", "conc_chem":"Conceptual Chemistry", "accel_chem":"Accelerated Chemistry", "ap_chem":"AP Chemistry", "o_chem":"Organic Chemistry", "bio":"Biology", "at_bio":"AT Biology", "anat_and_phys":...
0.303629
0.349533
import os import moxing as mox # 华为自研模块moxing,本地机器无法安装,仅可在华为云ModelArts平台上使用, # moxing文档请查看 https://github.com/huaweicloud/ModelArts-Lab/tree/master/docs/moxing_api_doc import tensorflow as tf from keras import backend from keras.optimizers import adam from train import model_fn def load_weights(model, weighs_file_p...
keras/baseline/src/save_model.py
import os import moxing as mox # 华为自研模块moxing,本地机器无法安装,仅可在华为云ModelArts平台上使用, # moxing文档请查看 https://github.com/huaweicloud/ModelArts-Lab/tree/master/docs/moxing_api_doc import tensorflow as tf from keras import backend from keras.optimizers import adam from train import model_fn def load_weights(model, weighs_file_p...
0.413714
0.145267
import numpy as np import pickle import os from data.dataset import Dataset from config import Config def read_split(train_num: int, num_segmented: int, fold: int, kind: str): fn = f"KSDD/split_{train_num}_{num_segmented}.pyb" with open(f"splits/{fn}", "rb") as f: train_samples, test_samples = pickle....
data/input_ksdd.py
import numpy as np import pickle import os from data.dataset import Dataset from config import Config def read_split(train_num: int, num_segmented: int, fold: int, kind: str): fn = f"KSDD/split_{train_num}_{num_segmented}.pyb" with open(f"splits/{fn}", "rb") as f: train_samples, test_samples = pickle....
0.421314
0.307735
import os import datetime import time #Local imports import cfg import rf_uart as ser import json import logging as log on_broadcast = None on_message = None on_cmd_response = None on_log = None nodes_config = os.getenv('ROVER_NODES_CONFIG','D:\\Dev\\nRF52_Mesh\\applications\\nodes.json') log.info("using ROVER_NODES_C...
rover/py_rf_serial/mesh.py
import os import datetime import time #Local imports import cfg import rf_uart as ser import json import logging as log on_broadcast = None on_message = None on_cmd_response = None on_log = None nodes_config = os.getenv('ROVER_NODES_CONFIG','D:\\Dev\\nRF52_Mesh\\applications\\nodes.json') log.info("using ROVER_NODES_C...
0.218003
0.240786
import unittest # Third party packages pass # Local packages from ccat.model.exchange.order import Order ''' ------------------------------------------------------------------------ CLASSES ------------------------------------------------------------------------ ''' class Test_model_exchange_order(unittest.Te...
test/LEGACY_test_ccat_model_exchange_order.py
import unittest # Third party packages pass # Local packages from ccat.model.exchange.order import Order ''' ------------------------------------------------------------------------ CLASSES ------------------------------------------------------------------------ ''' class Test_model_exchange_order(unittest.Te...
0.237046
0.327158
import unittest import gdal import numpy as np from fire_rs.geodata.environment import World, CORINELANDCOVER_TO_FUELMODEL_REMAP class WorldTest(unittest.TestCase): def setUp(self): pass def test_get_elevation(self): world = World() world.get_elevation([475060.0, 6200074.0]) ...
python/fire_rs/geodata/test_environment.py
import unittest import gdal import numpy as np from fire_rs.geodata.environment import World, CORINELANDCOVER_TO_FUELMODEL_REMAP class WorldTest(unittest.TestCase): def setUp(self): pass def test_get_elevation(self): world = World() world.get_elevation([475060.0, 6200074.0]) ...
0.579995
0.524029
import argparse import base64 import json import logging import re import subprocess import sys import tty from datetime import datetime, timedelta from os import path from time import sleep, time import feedparser as fp import requests import termios NAME = 'gh-watch.py' TIMEOUT = 10 RETRY = 30 SEARCH_API_BASE =...
gh-watch.py
import argparse import base64 import json import logging import re import subprocess import sys import tty from datetime import datetime, timedelta from os import path from time import sleep, time import feedparser as fp import requests import termios NAME = 'gh-watch.py' TIMEOUT = 10 RETRY = 30 SEARCH_API_BASE =...
0.269902
0.095518
import random import geomstats.backend as gs from geomstats.geometry.stratified.spider import Spider, SpiderMetric, SpiderPoint from tests.data_generation import ( _PointMetricTestData, _PointSetTestData, _PointTestData, ) class SpiderTestData(_PointSetTestData): _Point = SpiderPoint _PointSet =...
tests/data/spider_data.py
import random import geomstats.backend as gs from geomstats.geometry.stratified.spider import Spider, SpiderMetric, SpiderPoint from tests.data_generation import ( _PointMetricTestData, _PointSetTestData, _PointTestData, ) class SpiderTestData(_PointSetTestData): _Point = SpiderPoint _PointSet =...
0.679285
0.763374
import os import sys import json import requests from tabulate import tabulate import textwrap import yaml import argparse arg_parser = argparse.ArgumentParser() arg_parser.add_argument("--config", action="store", dest="config_file", default="/opt/yair/config/config.yaml", help="Config file location. Defaults to ...
yair.py
import os import sys import json import requests from tabulate import tabulate import textwrap import yaml import argparse arg_parser = argparse.ArgumentParser() arg_parser.add_argument("--config", action="store", dest="config_file", default="/opt/yair/config/config.yaml", help="Config file location. Defaults to ...
0.156652
0.077134
from __future__ import unicode_literals import logging from ...docker_api import INSECURE_REGISTRIES from ..action import ImageAction from ..input import ItemType from .utils import update_kwargs log = logging.getLogger(__name__) def _check_insecure_registry(kwargs): insecure_registry = kwargs.pop('insecure_re...
dockermap/map/runner/image.py
from __future__ import unicode_literals import logging from ...docker_api import INSECURE_REGISTRIES from ..action import ImageAction from ..input import ItemType from .utils import update_kwargs log = logging.getLogger(__name__) def _check_insecure_registry(kwargs): insecure_registry = kwargs.pop('insecure_re...
0.590189
0.065455
import unittest from carball.analysis.analysis_manager import AnalysisManager from carball.tests.utils import run_analysis_test_on_replay, get_specific_replays, get_specific_answers, \ assertNearlyEqual, get_raw_replays class Test_Boost(): def test_1_small_pad_collected(self, replay_cache): def tes...
carball/tests/stats/boost_test.py
import unittest from carball.analysis.analysis_manager import AnalysisManager from carball.tests.utils import run_analysis_test_on_replay, get_specific_replays, get_specific_answers, \ assertNearlyEqual, get_raw_replays class Test_Boost(): def test_1_small_pad_collected(self, replay_cache): def tes...
0.505615
0.429908
try: import matplotlib.pyplot as plt from matplotlib import gridspec except ImportError: # mpl is optional pass import numpy as np from pymc3.diagnostics import gelman_rubin from pymc3.stats import quantiles, hpd, dict2pd from .utils import identity_transform, get_default_varnames def _var_str(name, shape...
pymc3/plots/forestplot.py
try: import matplotlib.pyplot as plt from matplotlib import gridspec except ImportError: # mpl is optional pass import numpy as np from pymc3.diagnostics import gelman_rubin from pymc3.stats import quantiles, hpd, dict2pd from .utils import identity_transform, get_default_varnames def _var_str(name, shape...
0.810479
0.674107
import numpy as np import cv2 import os import random import pandas as pd class ImageDataLoader(): def __init__(self, data_path, gt_path, shuffle=False, batch_size = 1): self.data_path = data_path self.gt_path = gt_path self.batch_size = batch_size self.data_files = [filename for f...
architecture/data_loader.py
import numpy as np import cv2 import os import random import pandas as pd class ImageDataLoader(): def __init__(self, data_path, gt_path, shuffle=False, batch_size = 1): self.data_path = data_path self.gt_path = gt_path self.batch_size = batch_size self.data_files = [filename for f...
0.177954
0.164785
import redis import json from utils.get_configure import env_file_conf from utils.apollo_handler import apollo_envs_conf, apo_client from utils.console_logger import Logger log = Logger() logger = log.get_logger() def redis_conf(apollo_client,): """ 从apollo获取缓存配置 :return: dict """ ...
utils/redis_handler.py
import redis import json from utils.get_configure import env_file_conf from utils.apollo_handler import apollo_envs_conf, apo_client from utils.console_logger import Logger log = Logger() logger = log.get_logger() def redis_conf(apollo_client,): """ 从apollo获取缓存配置 :return: dict """ ...
0.339828
0.092319
from . import db from . import login_manager from flask_login import UserMixin from werkzeug.security import generate_password_hash,check_password_hash from datetime import datetime @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(UserMixin,db.Model): __tablen...
app/models.py
from . import db from . import login_manager from flask_login import UserMixin from werkzeug.security import generate_password_hash,check_password_hash from datetime import datetime @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(UserMixin,db.Model): __tablen...
0.378804
0.047936
import azure.cognitiveservices.speech as speechsdk import sys import re import io def transcribe_streaming(stream_file, result_file): """Streams transcription of the given audio file.""" import time # Microsoft authentication - add your API key on the line below. Using 'uksouth' as I am in the UK. ...
asr-msoft/transcribe-azure.py
import azure.cognitiveservices.speech as speechsdk import sys import re import io def transcribe_streaming(stream_file, result_file): """Streams transcription of the given audio file.""" import time # Microsoft authentication - add your API key on the line below. Using 'uksouth' as I am in the UK. ...
0.499756
0.232288
import os import pickle import numpy as np from vbdiar.features.segments import get_time_from_frames from vbdiar.utils import mkdir_p def extract_embeddings(features_dict, embedding_extractor): """ Extract embeddings from multiple segments. Args: features_dict (Dict): dictionary with segment range ...
vbdiar/embeddings/embedding.py
import os import pickle import numpy as np from vbdiar.features.segments import get_time_from_frames from vbdiar.utils import mkdir_p def extract_embeddings(features_dict, embedding_extractor): """ Extract embeddings from multiple segments. Args: features_dict (Dict): dictionary with segment range ...
0.782829
0.29419
import csv import os import platform import sys from os import listdir from pathlib import Path import pdfkit from jinja2 import Template MAC_ALIAS = 'macos' WIN_ALIAS = 'win' OS_MAPPING = { 'Darwin': MAC_ALIAS, 'Windows': WIN_ALIAS } ARCH_MAPPING = { MAC_ALIAS: { '64bit': '64' }, WIN_AL...
safaricsv2pdf.py
import csv import os import platform import sys from os import listdir from pathlib import Path import pdfkit from jinja2 import Template MAC_ALIAS = 'macos' WIN_ALIAS = 'win' OS_MAPPING = { 'Darwin': MAC_ALIAS, 'Windows': WIN_ALIAS } ARCH_MAPPING = { MAC_ALIAS: { '64bit': '64' }, WIN_AL...
0.257859
0.098469
__version__ = "0.3.3" __author__ = "<NAME>" __license__ = "MIT" import click from gitx import Gitx CONTEXT_SETTINGS = dict(help_option_names=['-h']) @click.command(short_help="Add file contents to the index") @click.argument("pathspec", nargs=-1, metavar='<pathspec>') @click.option("-x", '--exclude', ...
cli.py
__version__ = "0.3.3" __author__ = "<NAME>" __license__ = "MIT" import click from gitx import Gitx CONTEXT_SETTINGS = dict(help_option_names=['-h']) @click.command(short_help="Add file contents to the index") @click.argument("pathspec", nargs=-1, metavar='<pathspec>') @click.option("-x", '--exclude', ...
0.560253
0.236748
import logging import json from typing import Optional from datetime import timedelta import voluptuous as vol from homeassistant.core import callback from homeassistant.components import sensor from homeassistant.components.mqtt import ( ATTR_DISCOVERY_HASH, CONF_QOS, CONF_STATE_TOPIC, MqttAttributes,...
homeassistant/components/ais_device_search_mqtt/sensor.py
import logging import json from typing import Optional from datetime import timedelta import voluptuous as vol from homeassistant.core import callback from homeassistant.components import sensor from homeassistant.components.mqtt import ( ATTR_DISCOVERY_HASH, CONF_QOS, CONF_STATE_TOPIC, MqttAttributes,...
0.661923
0.051296
import wx from wxueye.wxVidWindow import wxVidWindow from wxueye.wxVidConfig import wxVidConfig import ueye # begin wxGlade: extracode # end wxGlade class wxVidFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: wxVidFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE ...
wxVidCap.py
import wx from wxueye.wxVidWindow import wxVidWindow from wxueye.wxVidConfig import wxVidConfig import ueye # begin wxGlade: extracode # end wxGlade class wxVidFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: wxVidFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE ...
0.274157
0.041327
__author__ = 'wenqihe' from SVM import SVM class MulticlassSVM: def __init__(self, feature_size, label_size, lambda_reg=0.1, max_iter=5000, mode='ova'): self._feature_size = feature_size self._label_size = label_size self._lambda_reg = lambda_reg self._max_iter = max_iter ...
code/Classifier/MulticlassSVM.py
__author__ = 'wenqihe' from SVM import SVM class MulticlassSVM: def __init__(self, feature_size, label_size, lambda_reg=0.1, max_iter=5000, mode='ova'): self._feature_size = feature_size self._label_size = label_size self._lambda_reg = lambda_reg self._max_iter = max_iter ...
0.303113
0.272157
from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import csv342 as csv from django.core.management import BaseCommand from corehq.apps.hqcase.utils import bulk_update_cases from corehq.form_processor.interfaces.dbaccessors import CaseAccessors from ...
corehq/apps/case_importer/management/commands/update_case_property.py
from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import csv342 as csv from django.core.management import BaseCommand from corehq.apps.hqcase.utils import bulk_update_cases from corehq.form_processor.interfaces.dbaccessors import CaseAccessors from ...
0.404978
0.109515
import boto from boto.sqs.message import Message import boto.ec2 import os import cPickle as pickle import subprocess import shlex import time import logging import socket HOSTNAME = str.join('_', socket.gethostname().split('.')) FUSE_MOUNT = "/tmp/snowflake" SERVER_DIR = "/tmp/snowflake_server" logging.getLogger('...
utils/aws.py
import boto from boto.sqs.message import Message import boto.ec2 import os import cPickle as pickle import subprocess import shlex import time import logging import socket HOSTNAME = str.join('_', socket.gethostname().split('.')) FUSE_MOUNT = "/tmp/snowflake" SERVER_DIR = "/tmp/snowflake_server" logging.getLogger('...
0.173148
0.054024
import util def print_field_order(roots, stats_file, args): data = {} cond_list = args['prefix'][:] r = util.collectByAttribute(roots, cond_list, "fieldn", ["sz"]) stats_file.write("\t<fieldOrderByName>\n") for k,v in r.items(): #k: main_attrib #v: [text, [other_attribs]] #count distinct of text orders = ...
powerstation/command_line_tool/controller_model_analysis/collect_status/print_field_stats.py
import util def print_field_order(roots, stats_file, args): data = {} cond_list = args['prefix'][:] r = util.collectByAttribute(roots, cond_list, "fieldn", ["sz"]) stats_file.write("\t<fieldOrderByName>\n") for k,v in r.items(): #k: main_attrib #v: [text, [other_attribs]] #count distinct of text orders = ...
0.063193
0.152127
import enum from dataclasses import dataclass, replace from simple_parsing import Serializable # NOTE(ycho): Required for dealing with `enum` registration from simple_parsing.helpers.serialization import encode, register_decoding_fn import torch as th from top.data.colored_cube_dataset import ColoredCubeDataset from ...
src/top/data/load.py
import enum from dataclasses import dataclass, replace from simple_parsing import Serializable # NOTE(ycho): Required for dealing with `enum` registration from simple_parsing.helpers.serialization import encode, register_decoding_fn import torch as th from top.data.colored_cube_dataset import ColoredCubeDataset from ...
0.623835
0.379551
import pyodbc from pyodbc import * # Make globals and exceptions visible in this module per PEP 249 def connect( host, port=443, database="default", http_path=None, token=None, user=None, password=None, driver_path=None, **kwargs, ): """Create an ODBC DBAPI connection to a Dat...
databricks_dbapi/odbc.py
import pyodbc from pyodbc import * # Make globals and exceptions visible in this module per PEP 249 def connect( host, port=443, database="default", http_path=None, token=None, user=None, password=None, driver_path=None, **kwargs, ): """Create an ODBC DBAPI connection to a Dat...
0.739799
0.198627
import os from .user import fun_user from .command import log import json async def fun_init_server(message, string_dir, client) : #STRING_DIR_NEW_S = os.path.abspath(os.path.join(sys.path[0], '..')) + '\\files\\servers' log(message, '[log][INIT] ####################') log(message, '[log][INIT] НАЧАЛО ИН...
old/src/src/init.py
import os from .user import fun_user from .command import log import json async def fun_init_server(message, string_dir, client) : #STRING_DIR_NEW_S = os.path.abspath(os.path.join(sys.path[0], '..')) + '\\files\\servers' log(message, '[log][INIT] ####################') log(message, '[log][INIT] НАЧАЛО ИН...
0.119139
0.118538
import sys sys.path.append(r'../shared') from numpy import * from geo import * from grid_3d import * from statistics import * from matplotlib import * from pylab import * from gslib import * # --------------------------------------------------- # Problem: # # Perform declustering and determine the rep...
src/sample-scripts/solved_problems/4.2. Bootstrap and Spatial Bootstrap/2_bootstrap.py
import sys sys.path.append(r'../shared') from numpy import * from geo import * from grid_3d import * from statistics import * from matplotlib import * from pylab import * from gslib import * # --------------------------------------------------- # Problem: # # Perform declustering and determine the rep...
0.329715
0.363647
import argparse import datetime import gym import numpy as np import itertools import sys sys.path.insert(0, '..') from torch.utils.tensorboard import SummaryWriter from collections import namedtuple import torch import torch.nn as nn from torch.nn import functional as F from torch.optim import Adam from torch.utils....
skeleton_graph_vae/train_vae.py
import argparse import datetime import gym import numpy as np import itertools import sys sys.path.insert(0, '..') from torch.utils.tensorboard import SummaryWriter from collections import namedtuple import torch import torch.nn as nn from torch.nn import functional as F from torch.optim import Adam from torch.utils....
0.630344
0.159217
import array import bz2 from django.db import models from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext_lazy as _ class AutoGrowingList(list): """ A class to hold auto growing lists with a configurable index offset """ EMPTY = -1 INDEX_OFFSET = 1 de...
compressedlistfield/fields.py
import array import bz2 from django.db import models from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext_lazy as _ class AutoGrowingList(list): """ A class to hold auto growing lists with a configurable index offset """ EMPTY = -1 INDEX_OFFSET = 1 de...
0.477311
0.171859
import discord import re from typing import Callable, ClassVar, List, Optional, Pattern, Sequence, Tuple, Union, cast from discord.ext import commands class MessagePredicate(Callable[[discord.Message], bool]): def __init__(self, predicate: Callable[["MessagePredicate", discord.Message], bool]) -> None: sel...
src/utilities/helpers/qrgenerator.py
import discord import re from typing import Callable, ClassVar, List, Optional, Pattern, Sequence, Tuple, Union, cast from discord.ext import commands class MessagePredicate(Callable[[discord.Message], bool]): def __init__(self, predicate: Callable[["MessagePredicate", discord.Message], bool]) -> None: sel...
0.917377
0.294507
import pytest from argsloader.base import ParseError, SkippedParseError, MultipleParseError, PValue, wrap_exception, \ wrap_exception_class @pytest.mark.unittest class TestBaseException: def test_parse_error(self): e = ParseError('This is message', 233, PValue(444, ('a', 0)), {'a': 1}) assert...
test/base/test_exception.py
import pytest from argsloader.base import ParseError, SkippedParseError, MultipleParseError, PValue, wrap_exception, \ wrap_exception_class @pytest.mark.unittest class TestBaseException: def test_parse_error(self): e = ParseError('This is message', 233, PValue(444, ('a', 0)), {'a': 1}) assert...
0.551091
0.574544
import qt import slicer import vtk from RVXLiverSegmentationLib import SegmentWidget, createButton, GeometryExporter, NodeBranches, removeNodeFromMRMLScene class VesselSegmentEditWidget(SegmentWidget): """ Class responsible for editing the vessel automatic segmentation """ def __init__(self, logic, treeWiza...
RVXLiverSegmentation/RVXLiverSegmentationLib/VesselSegmentEditWidget.py
import qt import slicer import vtk from RVXLiverSegmentationLib import SegmentWidget, createButton, GeometryExporter, NodeBranches, removeNodeFromMRMLScene class VesselSegmentEditWidget(SegmentWidget): """ Class responsible for editing the vessel automatic segmentation """ def __init__(self, logic, treeWiza...
0.671901
0.213418
import itertools import weetest def TestCycle(): want = [] got = [] for x in itertools.cycle(()): got.append(x) assert got == want, 'empty cycle yields no elements' arg = (0, 1, 2) want = (0, 1, 2) * 10 got = [] limit = 10 * len(arg) counter = 0 for x in itertools.cycle((0, 1, 2)): got...
lib/itertools_test.py
import itertools import weetest def TestCycle(): want = [] got = [] for x in itertools.cycle(()): got.append(x) assert got == want, 'empty cycle yields no elements' arg = (0, 1, 2) want = (0, 1, 2) * 10 got = [] limit = 10 * len(arg) counter = 0 for x in itertools.cycle((0, 1, 2)): got...
0.301773
0.462048
from pathlib import Path from tifffile import TiffFile from wsireg.reg_images import ( CziRegImage, SitkRegImage, NumpyRegImage, # AICSRegImage, ) from wsireg.utils.im_utils import ( TIFFFILE_EXTS, ARRAYLIKE_CLASSES, tifffile_to_arraylike, ome_tifffile_to_arraylike, ) def reg_image_loa...
wsireg/reg_images/loader.py
from pathlib import Path from tifffile import TiffFile from wsireg.reg_images import ( CziRegImage, SitkRegImage, NumpyRegImage, # AICSRegImage, ) from wsireg.utils.im_utils import ( TIFFFILE_EXTS, ARRAYLIKE_CLASSES, tifffile_to_arraylike, ome_tifffile_to_arraylike, ) def reg_image_loa...
0.554229
0.275002
import json import traceback from mod_recent_stat_config_main import ConfigMain from mod_recent_stat_config_wg_id import ConfigWgId from mod_recent_stat_container import PlayerData from mod_recent_stat_converter import formatBattlesToKiloBattles, getXWN8, isPlayerFake from mod_recent_stat_logging import logError from...
src/scripts/client/gui/mods/mod_recent_stat_wg_stats.py
import json import traceback from mod_recent_stat_config_main import ConfigMain from mod_recent_stat_config_wg_id import ConfigWgId from mod_recent_stat_container import PlayerData from mod_recent_stat_converter import formatBattlesToKiloBattles, getXWN8, isPlayerFake from mod_recent_stat_logging import logError from...
0.437824
0.121295
from collections import deque import simpy from simulator.core.DtnCore import Simulable class DtnLockException(Exception): pass class DtnLock(Simulable): """ This class implements a traditional lock in the Simpy world. In this version, there are not priorities. Usage examples: ...
simulator/core/DtnLock.py
from collections import deque import simpy from simulator.core.DtnCore import Simulable class DtnLockException(Exception): pass class DtnLock(Simulable): """ This class implements a traditional lock in the Simpy world. In this version, there are not priorities. Usage examples: ...
0.714927
0.296158
""" didispeech-2 dataset """ import os import re import sys import tarfile import tempfile import inflect import codecs import pandas from absl import logging from sklearn.model_selection import train_test_split from absl import logging from unidecode import unidecode import tensorflow as tf from athena import get_wav...
examples/asr/didispeech-2/local/prepare_data.py
""" didispeech-2 dataset """ import os import re import sys import tarfile import tempfile import inflect import codecs import pandas from absl import logging from sklearn.model_selection import train_test_split from absl import logging from unidecode import unidecode import tensorflow as tf from athena import get_wav...
0.201577
0.232288
import cv2 import numpy as np print(cv2.__version__) def crop_minAreaRect(img, rect): # rotate img angle = rect[2] rows,cols = img.shape[0], img.shape[1] M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1) img_rot = cv2.warpAffine(img,M,(cols,rows)) # rotate bounding box rect0 = (rect[0]...
old/test_rect.py
import cv2 import numpy as np print(cv2.__version__) def crop_minAreaRect(img, rect): # rotate img angle = rect[2] rows,cols = img.shape[0], img.shape[1] M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1) img_rot = cv2.warpAffine(img,M,(cols,rows)) # rotate bounding box rect0 = (rect[0]...
0.160529
0.412471
from flask import render_template, request, redirect, url_for, abort ,flash from ..models import User,Blog,Comment,Subscriber from flask_login import login_required, current_user from ..email import mail_message from .forms import UpdateProfile,Blogs from .. import db,photos from . import main import markdown2 from ...
app/main/views.py
from flask import render_template, request, redirect, url_for, abort ,flash from ..models import User,Blog,Comment,Subscriber from flask_login import login_required, current_user from ..email import mail_message from .forms import UpdateProfile,Blogs from .. import db,photos from . import main import markdown2 from ...
0.361052
0.056757