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 oslo_config import cfg from oslo_log import log as logging from oslo_utils import timeutils from taskflow import task from karbor.common import constants from karbor.services.protection.flows import utils from karbor.services.protection import resource_flow CONF = cfg.CONF LOG = logging.getLogger(__name__) ...
karbor-1.3.0/karbor/services/protection/flows/verify.py
from oslo_config import cfg from oslo_log import log as logging from oslo_utils import timeutils from taskflow import task from karbor.common import constants from karbor.services.protection.flows import utils from karbor.services.protection import resource_flow CONF = cfg.CONF LOG = logging.getLogger(__name__) ...
0.438545
0.083329
try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin import requests import tornado import ujson import pandas as pd import pyEX as p import string from trading_calendars import get_calendar from datetime import datetime, timedelta, date from dateutil.relativedelta import rela...
hedgedata/utils.py
try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin import requests import tornado import ujson import pandas as pd import pyEX as p import string from trading_calendars import get_calendar from datetime import datetime, timedelta, date from dateutil.relativedelta import rela...
0.382949
0.103839
from nbt import nbt import xlsxwriter import subprocess import time from sys import exit import os servers = "/root/of/spigot/servers" sharePath = "/where/to/save/reports/" def findUsers(): subprocess.call('rm %s*' %(sharePath), shell=True) for dir in os.listdir(servers): serverName = "" if os.path.isfile(se...
playerlist.py
from nbt import nbt import xlsxwriter import subprocess import time from sys import exit import os servers = "/root/of/spigot/servers" sharePath = "/where/to/save/reports/" def findUsers(): subprocess.call('rm %s*' %(sharePath), shell=True) for dir in os.listdir(servers): serverName = "" if os.path.isfile(se...
0.054777
0.054727
import spot import sys # ---------------------------------------------------------------------- a = spot.formula.ap('a') b = spot.formula.ap('b') c = spot.formula.ap('c') c2 = spot.formula.ap('c') assert c == c2 op = spot.formula.And([a, b]) op2 = spot.formula.And([op, c]) op3 = spot.formula.And([a, c, b]) assert ...
lib/spot-2.8.1/tests/python/ltlsimple.py
import spot import sys # ---------------------------------------------------------------------- a = spot.formula.ap('a') b = spot.formula.ap('b') c = spot.formula.ap('c') c2 = spot.formula.ap('c') assert c == c2 op = spot.formula.And([a, b]) op2 = spot.formula.And([op, c]) op3 = spot.formula.And([a, c, b]) assert ...
0.435661
0.550909
import pytest import windows import windows.generated_def as gdef from windows.pycompat import basestring from .pfwtest import * ## This comment was in test_system.py: still revelant ? # Well, pytest initialize COM with its own parameters # It might make our own com.init() in WMI fail and therefore not call # CoInit...
tests/test_wmi.py
import pytest import windows import windows.generated_def as gdef from windows.pycompat import basestring from .pfwtest import * ## This comment was in test_system.py: still revelant ? # Well, pytest initialize COM with its own parameters # It might make our own com.init() in WMI fail and therefore not call # CoInit...
0.475849
0.434281
import io import unittest import unittest.mock as mock from unittest.mock import patch from unittest import TestCase from ETCetera.util.parsing.parser_nonlinear_systems import parse_from_file class TestParserFileRead(TestCase): @unittest.mock.patch('sys.stdout', new_callable=io.StringIO) def assert_stdout(se...
tests/parser_tests/nonlinear_systems/test_nonlinear_read_from_file.py
import io import unittest import unittest.mock as mock from unittest.mock import patch from unittest import TestCase from ETCetera.util.parsing.parser_nonlinear_systems import parse_from_file class TestParserFileRead(TestCase): @unittest.mock.patch('sys.stdout', new_callable=io.StringIO) def assert_stdout(se...
0.525369
0.547948
import asyncio import requests import os from pyppeteer import launch from pyppeteer.page import Page import colorsys layer_keys = [ 'mini_base', 'pet', 'cloak', 'off_hand', 'body', 'hair', 'face', 'legs', 'feet', 'chest', 'head', 'head_2', 'waist', 'hands', 'main_hand', 'horns', 'wings', 'tattoo', 'ears',...
rerollExtractor.py
import asyncio import requests import os from pyppeteer import launch from pyppeteer.page import Page import colorsys layer_keys = [ 'mini_base', 'pet', 'cloak', 'off_hand', 'body', 'hair', 'face', 'legs', 'feet', 'chest', 'head', 'head_2', 'waist', 'hands', 'main_hand', 'horns', 'wings', 'tattoo', 'ears',...
0.33546
0.204898
import itertools import textwrap from django.conf import settings from django.contrib.gis.db import models as gis_models from django.core.cache import cache from django.db import models from django.db import IntegrityError from django.db.models.signals import post_save from django.dispatch import receiver from django ...
backent/api/models.py
import itertools import textwrap from django.conf import settings from django.contrib.gis.db import models as gis_models from django.core.cache import cache from django.db import models from django.db import IntegrityError from django.db.models.signals import post_save from django.dispatch import receiver from django ...
0.58676
0.075312
from abra.config import DEFAULT_ALPHA, DEFAULT_BAYESIAN_INFERENCE_METHOD from abra.inference.inference_base import InferenceProcedure from abra.stats import Samples from abra.vis import Traces from abra.inference.bayesian import get_stan_model, get_model_datatype, get_model_data from abra.inference.bayesian.results imp...
abra/inference/bayesian/delta.py
from abra.config import DEFAULT_ALPHA, DEFAULT_BAYESIAN_INFERENCE_METHOD from abra.inference.inference_base import InferenceProcedure from abra.stats import Samples from abra.vis import Traces from abra.inference.bayesian import get_stan_model, get_model_datatype, get_model_data from abra.inference.bayesian.results imp...
0.917873
0.465873
from flask_restplus import reqparse, inputs group_by_model = reqparse.RequestParser() group_by_model.add_argument('granularity', type=str, choices=['day', 'month', 'year'], default='month') group_by_model.add_argument('label', type=int, default=None) group_by_model.add_argument('keyword', action='append', default=lamb...
backend/db/db_models.py
from flask_restplus import reqparse, inputs group_by_model = reqparse.RequestParser() group_by_model.add_argument('granularity', type=str, choices=['day', 'month', 'year'], default='month') group_by_model.add_argument('label', type=int, default=None) group_by_model.add_argument('keyword', action='append', default=lamb...
0.419886
0.042029
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, transforms, models from torch.utils.data import DataLoader, random_split from torch.utils.data.sampler import SubsetRandomSampler train_transforms = transforms.Compose([ transforms.Resi...
models/matt/second.py
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, transforms, models from torch.utils.data import DataLoader, random_split from torch.utils.data.sampler import SubsetRandomSampler train_transforms = transforms.Compose([ transforms.Resi...
0.824638
0.65071
import numpy as np import pandas as pd class RelationalDataBase(): def __init__(self): self._dic = {} self._label_dic = {} self.merge_dic = {} def _read_as_list(self,file_name): l = [] with open(file_name,"r") as f: for line in f: ...
LIDG_v0.2/lidg/database.py
import numpy as np import pandas as pd class RelationalDataBase(): def __init__(self): self._dic = {} self._label_dic = {} self.merge_dic = {} def _read_as_list(self,file_name): l = [] with open(file_name,"r") as f: for line in f: ...
0.146026
0.183392
from datetime import datetime from corehq.apps.locations.models import SQLLocation from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn from corehq.apps.reports.filters.fixtures import AsyncLocationFilter from corehq.apps.reports.filters.select import MonthFilter, YearFilter from custom.ilsgate...
custom/ilsgateway/tanzania/reports/supervision.py
from datetime import datetime from corehq.apps.locations.models import SQLLocation from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn from corehq.apps.reports.filters.fixtures import AsyncLocationFilter from corehq.apps.reports.filters.select import MonthFilter, YearFilter from custom.ilsgate...
0.637934
0.127734
from models.convnets import ConvolutionalNet from keras.models import load_model from keras.preprocessing import sequence from preprocessors.preprocess_text import clean import sys import string import re import numpy as np from sklearn.metrics import confusion_matrix, accuracy_score, f1_score MATCH_MULTIPLE_SPACES = ...
examples/pplm_clickbait/ClickBaticDetector.py
from models.convnets import ConvolutionalNet from keras.models import load_model from keras.preprocessing import sequence from preprocessors.preprocess_text import clean import sys import string import re import numpy as np from sklearn.metrics import confusion_matrix, accuracy_score, f1_score MATCH_MULTIPLE_SPACES = ...
0.534127
0.274344
import os import yaml from shutil import copy import argparse import confgenerator.generator as gen # sys.tracebacklimit = 0 # no traceback PKG_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) class bypass_confgen_cli(): """The CLI of the bypass configuration generator.""" def __init__(self,...
deployment/confgenerator/confgenerator/cli.py
import os import yaml from shutil import copy import argparse import confgenerator.generator as gen # sys.tracebacklimit = 0 # no traceback PKG_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) class bypass_confgen_cli(): """The CLI of the bypass configuration generator.""" def __init__(self,...
0.391173
0.051869
from flask import Flask, jsonify, render_template from flask_limiter import Limiter from flask_limiter.util import get_remote_address from utils import retrieve_arb_pred, retrieve_tr_pred from display import display_tr_pred, display_arb_pred application = Flask(__name__) # default limit for each route limiter = Limi...
api_source_code/flask_app/application.py
from flask import Flask, jsonify, render_template from flask_limiter import Limiter from flask_limiter.util import get_remote_address from utils import retrieve_arb_pred, retrieve_tr_pred from display import display_tr_pred, display_arb_pred application = Flask(__name__) # default limit for each route limiter = Limi...
0.749087
0.203055
import pprint import re # noqa: F401 import six class Bond(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name ...
sdk/lusid/models/bond.py
import pprint import re # noqa: F401 import six class Bond(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name ...
0.836888
0.24801
import os.path import sys import time import numbers import signal import ConfigParser cfg = ConfigParser.ConfigParser() cfg.read('teckit.conf') cfg.sections() if cfg.get('teckit', 'interface', 1) == 'gpib': import Gpib elif cfg.get('teckit', 'interface', 1) == 'vxi': import vxi11 else: print "No interface...
devices/f5720a.py
import os.path import sys import time import numbers import signal import ConfigParser cfg = ConfigParser.ConfigParser() cfg.read('teckit.conf') cfg.sections() if cfg.get('teckit', 'interface', 1) == 'gpib': import Gpib elif cfg.get('teckit', 'interface', 1) == 'vxi': import vxi11 else: print "No interface...
0.151216
0.124505
import argparse import traceback from config import Config from main import trace_most_fit, train_same_games, training_overview, visualize_genome from population.population import Population from process_killer import main as process_killer from utils.dictionary import * def main(gru, reproduce, tr...
run_distance_only.py
import argparse import traceback from config import Config from main import trace_most_fit, train_same_games, training_overview, visualize_genome from population.population import Population from process_killer import main as process_killer from utils.dictionary import * def main(gru, reproduce, tr...
0.660391
0.330215
from kigo.bpmn.elements.element import Element class Task(Element): item_name = "bpmn:task" def __init__(self, eid=None, name=None, incoming=[], outgoing=[]): self.eid = eid self.name = name self.incoming = incoming self.outgoing = outgoing def __repr__(self): retu...
kigo/bpmn/elements/tasks.py
from kigo.bpmn.elements.element import Element class Task(Element): item_name = "bpmn:task" def __init__(self, eid=None, name=None, incoming=[], outgoing=[]): self.eid = eid self.name = name self.incoming = incoming self.outgoing = outgoing def __repr__(self): retu...
0.588889
0.066448
import os from miscellanies.platform_style_path import join_path from .manipulator import VideoDatasetManipulator from datasets.types.specialized_dataset import SpecializedVideoDatasetType from datasets.base.common.dataset import _BaseDataset, _BaseDatasetObject __all__ = ['VideoDataset'] __version__ = 1 class Video...
datasets/base/video/dataset.py
import os from miscellanies.platform_style_path import join_path from .manipulator import VideoDatasetManipulator from datasets.types.specialized_dataset import SpecializedVideoDatasetType from datasets.base.common.dataset import _BaseDataset, _BaseDatasetObject __all__ = ['VideoDataset'] __version__ = 1 class Video...
0.66628
0.262416
import asyncio import os import logging from keep_alive import keep_alive as flask_keep_alive import main, db, economy import settings import click logger = logging.getLogger('run') @click.group() def cli(): pass @cli.command() @click.option('--keep-alive', is_flag=True, help='Run flask thread to keep Repl al...
run.py
import asyncio import os import logging from keep_alive import keep_alive as flask_keep_alive import main, db, economy import settings import click logger = logging.getLogger('run') @click.group() def cli(): pass @cli.command() @click.option('--keep-alive', is_flag=True, help='Run flask thread to keep Repl al...
0.483892
0.04982
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, std_headers, sanitize_filename, int_or_none, js_to_json ) import httpx import traceback import sys import json import time import random from urllib.parse import unquote...
yt_dlp/extractor/gay0day.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, std_headers, sanitize_filename, int_or_none, js_to_json ) import httpx import traceback import sys import json import time import random from urllib.parse import unquote...
0.191668
0.064447
from flask_wtf import ( FlaskForm ) from wtforms import ( IntegerField, SelectField ) class TimesheetForm(FlaskForm): pass hh_beg_01 = IntegerField(default='09') mm_beg_01 = IntegerField(default='00') ap_beg_01 = SelectField(choices=[('0', 'a'), ('12', 'p')]) hh_fin_01 = IntegerField(defau...
jam/timesheet/forms.py
from flask_wtf import ( FlaskForm ) from wtforms import ( IntegerField, SelectField ) class TimesheetForm(FlaskForm): pass hh_beg_01 = IntegerField(default='09') mm_beg_01 = IntegerField(default='00') ap_beg_01 = SelectField(choices=[('0', 'a'), ('12', 'p')]) hh_fin_01 = IntegerField(defau...
0.460046
0.18838
_multiprocess_can_split_ = False from init import setUp setUp() from unittest import TestCase from mock import patch import mock SERVICE_KEY = 'test_generated_key.pem' SERVICE_EMAIL = '<EMAIL>' USER_EMAIL = '<EMAIL>' USER2_EMAIL = '<EMAIL>' class DictObject(object): def __init__(self, **properties): s...
tests/test_oauth.py
_multiprocess_can_split_ = False from init import setUp setUp() from unittest import TestCase from mock import patch import mock SERVICE_KEY = 'test_generated_key.pem' SERVICE_EMAIL = '<EMAIL>' USER_EMAIL = '<EMAIL>' USER2_EMAIL = '<EMAIL>' class DictObject(object): def __init__(self, **properties): s...
0.535341
0.1291
import fairseq from fairseq.data import Dictionary, encoders import csv from argparse import Namespace import torch class AdditionalDataset: @classmethod def from_tsv(cls, file, key, bpe_tokenizer=None, pre_tokenizer=None): data = [] with open(file, 'r') as file: reader = csv.Dict...
s3prl/downstream/speech_translation/AdditionalDataset.py
import fairseq from fairseq.data import Dictionary, encoders import csv from argparse import Namespace import torch class AdditionalDataset: @classmethod def from_tsv(cls, file, key, bpe_tokenizer=None, pre_tokenizer=None): data = [] with open(file, 'r') as file: reader = csv.Dict...
0.698946
0.152852
from __future__ import print_function from keras.models import Sequential from keras.layers import Dense, Activation from keras.layers import LSTM from keras.layers import TimeDistributed from keras.optimizers import RMSprop import numpy as np import random import sys path = "./jdk-tokens.txt" filetext = open(path).re...
lstm_ai_coder_token_many2many.py
from __future__ import print_function from keras.models import Sequential from keras.layers import Dense, Activation from keras.layers import LSTM from keras.layers import TimeDistributed from keras.optimizers import RMSprop import numpy as np import random import sys path = "./jdk-tokens.txt" filetext = open(path).re...
0.609524
0.248968
import psycopg2 import ujson as json import datetime def database_connection(): postgresconn = psycopg2.connect("dbname='prop' user='CHANGEME' password='<PASSWORD>' host='CHANGEME'") postgresconn.autocommit = True postgrescur = postgresconn.cursor() return postgrescur, postgresconn def hashtag_exists...
3-ANALYZE/review_raw_data.py
import psycopg2 import ujson as json import datetime def database_connection(): postgresconn = psycopg2.connect("dbname='prop' user='CHANGEME' password='<PASSWORD>' host='CHANGEME'") postgresconn.autocommit = True postgrescur = postgresconn.cursor() return postgrescur, postgresconn def hashtag_exists...
0.105671
0.064036
from .fplEntity import FplEntity class FplProjectedBillSensor(FplEntity): def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Projected Bill") @property def state(self): budget = self.getData("budget_bill") budget_billing_projected_bil...
custom_components/fpl/sensor_ProjectedBillSensor.py
from .fplEntity import FplEntity class FplProjectedBillSensor(FplEntity): def __init__(self, coordinator, config, account): super().__init__(coordinator, config, account, "Projected Bill") @property def state(self): budget = self.getData("budget_bill") budget_billing_projected_bil...
0.856377
0.09628
import json import numpy as np import tensorflow as tf from kafka import KafkaProducer def publish_message(producer_instance, topic_name, key, value): try: key_bytes = bytes(key, encoding="utf-8") value_bytes = bytes(value, encoding="utf-8") producer_instance.send(topic_name, key=key_byt...
mlmodels/model_tf/misc/tf_serving/13.text-classification-kafka/producer.py
import json import numpy as np import tensorflow as tf from kafka import KafkaProducer def publish_message(producer_instance, topic_name, key, value): try: key_bytes = bytes(key, encoding="utf-8") value_bytes = bytes(value, encoding="utf-8") producer_instance.send(topic_name, key=key_byt...
0.265499
0.10235
import json from lib import components, dockerfile class Command: def __init__(self, components, dockerfile_instruction): self.components = components self.dockerfile_instruction = dockerfile_instruction def get_lines(self): pass def get_tools(self): return [component for...
generator/lib/commands.py
import json from lib import components, dockerfile class Command: def __init__(self, components, dockerfile_instruction): self.components = components self.dockerfile_instruction = dockerfile_instruction def get_lines(self): pass def get_tools(self): return [component for...
0.420124
0.108803
class FeatureBroker: """ Feature Borker """ def __init__(self, allowReplace=False): self.providers = {} self.allowReplace = allowReplace def provide(self, feature, provider, *args, **kwargs): if not self.allowReplace: assert not self.providers.has_key(feature), 'Dupl...
IOC/IOC.py
class FeatureBroker: """ Feature Borker """ def __init__(self, allowReplace=False): self.providers = {} self.allowReplace = allowReplace def provide(self, feature, provider, *args, **kwargs): if not self.allowReplace: assert not self.providers.has_key(feature), 'Dupl...
0.694406
0.443781
import cv2 import sys import os sys.path.append('../') from lib import fileTool as FT from lib.pwcNet.pwcNet import PWCDCNet from lib.forwardWarpTorch.forwardWarp import forwadWarp import torch from pathlib import Path from DVSTool20.DVSBase import ESIMReader import numpy as np import pickle from tqdm import tqdm fro...
DVSTool/drawevent.py
import cv2 import sys import os sys.path.append('../') from lib import fileTool as FT from lib.pwcNet.pwcNet import PWCDCNet from lib.forwardWarpTorch.forwardWarp import forwadWarp import torch from pathlib import Path from DVSTool20.DVSBase import ESIMReader import numpy as np import pickle from tqdm import tqdm fro...
0.244183
0.152064
import sys, datetime, jieba, jieba.analyse, MySQLdb from gensim import corpora, models, similarities from mysql_config import DBConfig reload(sys) sys.setdefaultencoding('utf8') date_list = [2016,9,22] date = date_list[0]*10000 + date_list[1]*100 + date_list[2] today_date = (datetime.datetime.now().year)*10000 + (dat...
data_analyse/file_updater.py
import sys, datetime, jieba, jieba.analyse, MySQLdb from gensim import corpora, models, similarities from mysql_config import DBConfig reload(sys) sys.setdefaultencoding('utf8') date_list = [2016,9,22] date = date_list[0]*10000 + date_list[1]*100 + date_list[2] today_date = (datetime.datetime.now().year)*10000 + (dat...
0.151498
0.081191
import numpy as np from quantiacsToolbox import stats def fillnans(data): """ Fill in (column-wise) value gaps with the most recent non-nan value. Leading nan's remain in place. The gaps are filled in only after the first non-nan entry. Args: data: Input data to be un-nanned. Returns: ...
rnn_portfolio/quantiacs_code.py
import numpy as np from quantiacsToolbox import stats def fillnans(data): """ Fill in (column-wise) value gaps with the most recent non-nan value. Leading nan's remain in place. The gaps are filled in only after the first non-nan entry. Args: data: Input data to be un-nanned. Returns: ...
0.781247
0.737944
import numpy as np import numpy.ma as ma from Xdrop.dropletizem import dropimgood_sel import time import pickle import re from matplotlib import pyplot as plt def dropletizedata(data, pars, mask=None, dark=None, savdir="./", savname=None): # print(dropimgood_sel.__doc__) dim = data.shape mshape = dim[-2:]...
Xana/Xdrop/DropletizeData.py
import numpy as np import numpy.ma as ma from Xdrop.dropletizem import dropimgood_sel import time import pickle import re from matplotlib import pyplot as plt def dropletizedata(data, pars, mask=None, dark=None, savdir="./", savname=None): # print(dropimgood_sel.__doc__) dim = data.shape mshape = dim[-2:]...
0.168651
0.418816
from django.apps import AppConfig from baserow.core.registries import plugin_registry, application_type_registry from .views.registries import view_type_registry, view_filter_type_registry from .fields.registries import field_type_registry, field_converter_registry class DatabaseConfig(AppConfig): name = 'baser...
backend/src/baserow/contrib/database/config.py
from django.apps import AppConfig from baserow.core.registries import plugin_registry, application_type_registry from .views.registries import view_type_registry, view_filter_type_registry from .fields.registries import field_type_registry, field_converter_registry class DatabaseConfig(AppConfig): name = 'baser...
0.629775
0.274886
import unittest import mock from perfkitbenchmarker import flags from perfkitbenchmarker import pkb from perfkitbenchmarker import stages FLAGS = flags.FLAGS FLAGS.mark_as_parsed() class TestCreateFailedRunSampleFlag(unittest.TestCase): def PatchPkbFunction(self, function_name): patcher = mock.patch(pkb.__nam...
tests/pkb_test.py
import unittest import mock from perfkitbenchmarker import flags from perfkitbenchmarker import pkb from perfkitbenchmarker import stages FLAGS = flags.FLAGS FLAGS.mark_as_parsed() class TestCreateFailedRunSampleFlag(unittest.TestCase): def PatchPkbFunction(self, function_name): patcher = mock.patch(pkb.__nam...
0.580114
0.338706
import datetime import uuid import pytest from dataclasses_avroschema import fields from . import consts @pytest.mark.parametrize( "python_type,avro_type,logical_type", consts.LOGICAL_TYPES_AND_DEFAULTS ) def test_logical_types(python_type, avro_type, logical_type): name = "a logical type" python_type ...
tests/fields/test_logical_types.py
import datetime import uuid import pytest from dataclasses_avroschema import fields from . import consts @pytest.mark.parametrize( "python_type,avro_type,logical_type", consts.LOGICAL_TYPES_AND_DEFAULTS ) def test_logical_types(python_type, avro_type, logical_type): name = "a logical type" python_type ...
0.721743
0.505554
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_in...
mtcnn_pb2.py
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_in...
0.177811
0.120516
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys import six from paddlehub.commands.base_command import BaseCommand, ENTRY from paddlehub.io.parser import yaml_parser, txt_parser from paddlehub.module.manager import def...
paddlehub/commands/run.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys import six from paddlehub.commands.base_command import BaseCommand, ENTRY from paddlehub.io.parser import yaml_parser, txt_parser from paddlehub.module.manager import def...
0.424531
0.097993
import structlog from discord_webhook import DiscordWebhook as Webhook from notifiers.utils import NotifierUtils __max_message_size__ = 2000 class DiscordNotifier(NotifierUtils): """Class for handling Discord notifications """ def __init__(self, webhook, username, avatar=None): """Initialize Di...
app/notifiers/discord_client.py
import structlog from discord_webhook import DiscordWebhook as Webhook from notifiers.utils import NotifierUtils __max_message_size__ = 2000 class DiscordNotifier(NotifierUtils): """Class for handling Discord notifications """ def __init__(self, webhook, username, avatar=None): """Initialize Di...
0.565419
0.05163
import json import logging import os import re from pathlib import Path from typing import List from common import utilities from models.phrase import Phrase from models.phrase_group import PhraseGroup from models.phrase_encoding import PhraseEncoding from phrase_encoder_decoder import PhraseEncoderDecoder ## Config ...
modules/phrases/phrase_file_manager.py
import json import logging import os import re from pathlib import Path from typing import List from common import utilities from models.phrase import Phrase from models.phrase_group import PhraseGroup from models.phrase_encoding import PhraseEncoding from phrase_encoder_decoder import PhraseEncoderDecoder ## Config ...
0.489015
0.13966
import os, sys, datetime import environ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,os.path.join(BASE_DIR,"apps")) root = environ.Path(BASE_DIR) public_root = root.path('public/') # Quick-start developme...
loveshare/settings.py
import os, sys, datetime import environ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,os.path.join(BASE_DIR,"apps")) root = environ.Path(BASE_DIR) public_root = root.path('public/') # Quick-start developme...
0.291182
0.070464
import os import numpy as np from .base_data import Dataset, Sequence from ..utils import read_file from ..builder import BENCHMARKS @BENCHMARKS.register_module class VOT(Dataset): def __init__(self, name='vot', vot_root='data/benchmark/vot17/', zip_mode=False)...
siam_tracker/benchmarks/data/vot.py
import os import numpy as np from .base_data import Dataset, Sequence from ..utils import read_file from ..builder import BENCHMARKS @BENCHMARKS.register_module class VOT(Dataset): def __init__(self, name='vot', vot_root='data/benchmark/vot17/', zip_mode=False)...
0.475605
0.144903
import datetime import io import logging import os import shlex import signal import tempfile import pytest import gemato.cli from gemato.compression import open_potentially_compressed_path from gemato.exceptions import ( ManifestUnsignedData, ManifestSyntaxError, OpenPGPNoImplementation, OpenPGPVeri...
tests/test_openpgp.py
import datetime import io import logging import os import shlex import signal import tempfile import pytest import gemato.cli from gemato.compression import open_potentially_compressed_path from gemato.exceptions import ( ManifestUnsignedData, ManifestSyntaxError, OpenPGPNoImplementation, OpenPGPVeri...
0.230313
0.056548
import unittest from .context import src from src import customer as cust from src import product as prod class TestCustomer(unittest.TestCase): def setUp(self): self.customer = cust.Customer(3.00, 4.2) self.random_customers = [] self.n_rand = 10000 ...
Mathematics/Statistics/Statistics and Probability Python Notebooks/Probability and Stats --PyDataNYC2019 /tests/test_customer.py
import unittest from .context import src from src import customer as cust from src import product as prod class TestCustomer(unittest.TestCase): def setUp(self): self.customer = cust.Customer(3.00, 4.2) self.random_customers = [] self.n_rand = 10000 ...
0.477311
0.622172
from __future__ import absolute_import, division, print_function, unicode_literals from fuse.components import Component class Celery(Component): component_type = 'taskrunner' def project_home(self, payload): self.context['project_home'] = payload def project_identifier(self, payload): s...
fuse/components/celery.py
from __future__ import absolute_import, division, print_function, unicode_literals from fuse.components import Component class Celery(Component): component_type = 'taskrunner' def project_home(self, payload): self.context['project_home'] = payload def project_identifier(self, payload): s...
0.556882
0.10217
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ('structure', '0001_initial'), ('se...
mrmap/service/migrations/0002_auto_20210413_0935.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ('structure', '0001_initial'), ('se...
0.546254
0.093761
import pandas as pd import inflection import math import datetime import pickle import numpy as np class House(object): def __init__(self): self.year_built_scaler = pickle.load(open('/home/andre/repos/House-Prices/parameter/year_built_scaler.pkl', 'rb')) self.ms_sub_class_scaler = pickle.load...
api/house/House.py
import pandas as pd import inflection import math import datetime import pickle import numpy as np class House(object): def __init__(self): self.year_built_scaler = pickle.load(open('/home/andre/repos/House-Prices/parameter/year_built_scaler.pkl', 'rb')) self.ms_sub_class_scaler = pickle.load...
0.108827
0.039416
import torch def criterion(p, s): return torch.mean(-torch.exp(-(p - s)**2), dim=2) def resnet_weights(device, c_in, kernel_size, c_out=None): if c_out is None: c_out = c_in * 2 w0 = torch.empty(c_out, c_in, 1, 1, device=device, requires_grad=True) torch.nn.init.xavier_normal_(w0) b0 =...
compare.py
import torch def criterion(p, s): return torch.mean(-torch.exp(-(p - s)**2), dim=2) def resnet_weights(device, c_in, kernel_size, c_out=None): if c_out is None: c_out = c_in * 2 w0 = torch.empty(c_out, c_in, 1, 1, device=device, requires_grad=True) torch.nn.init.xavier_normal_(w0) b0 =...
0.859354
0.589628
from .basedownload import BaseDownload from sqlalchemy import Column, Integer, String, Float, DateTime from typing import Optional from sqlalchemy import MetaData, Table, create_engine from datetime import datetime class TencentQuotation(BaseDownload): def __init__(self, stock_num: int = 400, ...
easyquotation_enhance/tencent.py
from .basedownload import BaseDownload from sqlalchemy import Column, Integer, String, Float, DateTime from typing import Optional from sqlalchemy import MetaData, Table, create_engine from datetime import datetime class TencentQuotation(BaseDownload): def __init__(self, stock_num: int = 400, ...
0.767994
0.316066
import logging import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from functools import wraps from pathlib import Path from typing import List, Optional, Union import click from .configuration import WorkspaceConfig from .configuration.discovery import ...
src/remote/entrypoints.py
import logging import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from functools import wraps from pathlib import Path from typing import List, Optional, Union import click from .configuration import WorkspaceConfig from .configuration.discovery import ...
0.531209
0.159185
from battle.battles.rounds import run_round from battle.battles.email import result_battle from pokemon.models import Pokemon from pokemon.helpers import get_pokemon_from_api def run_battle(battle): teams = list(battle.teams.all()) assert len(teams) == 2, "Unexpected error. Battle has more than two teams." ...
backend/battle/battles/battle.py
from battle.battles.rounds import run_round from battle.battles.email import result_battle from pokemon.models import Pokemon from pokemon.helpers import get_pokemon_from_api def run_battle(battle): teams = list(battle.teams.all()) assert len(teams) == 2, "Unexpected error. Battle has more than two teams." ...
0.419767
0.331877
from pyramid_nested_ner.utils.text import default_tokenizer from torch.nn.utils.rnn import pad_sequence import torch class PyramidLabelEncoder(object): """ Label encoder class responsible for transforming entity annotations into torch.Tensors. The `transform` API returns two tensors: one fo- r the py...
pyramid_nested_ner/vectorizers/labels/__init__.py
from pyramid_nested_ner.utils.text import default_tokenizer from torch.nn.utils.rnn import pad_sequence import torch class PyramidLabelEncoder(object): """ Label encoder class responsible for transforming entity annotations into torch.Tensors. The `transform` API returns two tensors: one fo- r the py...
0.849847
0.523664
import os import sys import numpy as np import pandas as pd import pybedtools import re import pyBigWig as pbw import time import urllib.request import matplotlib.pyplot as plt imputed_urls_path="../configs/Imputed_urls.txt" observed_urls_path="../configs/Observed_urls.txt" Enhancer_urls=pd.read_csv("../configs/enha...
scripts/Process_epimap_data.py
import os import sys import numpy as np import pandas as pd import pybedtools import re import pyBigWig as pbw import time import urllib.request import matplotlib.pyplot as plt imputed_urls_path="../configs/Imputed_urls.txt" observed_urls_path="../configs/Observed_urls.txt" Enhancer_urls=pd.read_csv("../configs/enha...
0.251096
0.123868
from tests.common.utilities import wait_until from tests.common.devices.eos import EosHost from macsec_helper import * def set_macsec_profile(host, profile_name, priority, cipher_suite, primary_cak, primary_ckn, policy, send_sci): if isinstance(host, EosHost): eos_cipher_suite = { "GCM-AES-128...
tests/macsec/macsec_config_helper.py
from tests.common.utilities import wait_until from tests.common.devices.eos import EosHost from macsec_helper import * def set_macsec_profile(host, profile_name, priority, cipher_suite, primary_cak, primary_ckn, policy, send_sci): if isinstance(host, EosHost): eos_cipher_suite = { "GCM-AES-128...
0.512693
0.127002
import tensorflow as tf from tensorflow.keras import layers, Model import numpy as np from collections.abc import Iterable from dl_playground.networks.utils import ( config_to_regularizer, ActivityMonitor, activation_function, ) class MLP(layers.Layer): """Multi-layer perceptron. Parameters ...
networks/layers/mlp.py
import tensorflow as tf from tensorflow.keras import layers, Model import numpy as np from collections.abc import Iterable from dl_playground.networks.utils import ( config_to_regularizer, ActivityMonitor, activation_function, ) class MLP(layers.Layer): """Multi-layer perceptron. Parameters ...
0.895088
0.504822
import argparse import logging import matplotlib.pyplot as plt import numpy as np import torch.utils.data from hardware.camera import RealSenseCamera from hardware.device import get_device from inference.post_process import post_process_output from utils.data.camera_data import CameraData from utils.visualisation.plo...
run_realtime.py
import argparse import logging import matplotlib.pyplot as plt import numpy as np import torch.utils.data from hardware.camera import RealSenseCamera from hardware.device import get_device from inference.post_process import post_process_output from utils.data.camera_data import CameraData from utils.visualisation.plo...
0.786459
0.160825
import logging import rpyc from paramiko.client import AutoAddPolicy from plumbum import ProcessExecutionError from plumbum.machines.paramiko_machine import ParamikoMachine from rpyc.core.service import VoidService from rpyc.core.stream import SocketStream from rpyc.lib.compat import BYTES_LITERAL import signal def...
bnb/remote/deploy.py
import logging import rpyc from paramiko.client import AutoAddPolicy from plumbum import ProcessExecutionError from plumbum.machines.paramiko_machine import ParamikoMachine from rpyc.core.service import VoidService from rpyc.core.stream import SocketStream from rpyc.lib.compat import BYTES_LITERAL import signal def...
0.328206
0.103658
import click from Bio import AlignIO @click.group() def cli(): pass # https://www.biostars.org/p/326044/ def column(alignment): '''Generator for getting list of characters in each column in the alignment''' for i in range(alignment.get_alignment_length()): c = [] for record in alignment:...
align.py
import click from Bio import AlignIO @click.group() def cli(): pass # https://www.biostars.org/p/326044/ def column(alignment): '''Generator for getting list of characters in each column in the alignment''' for i in range(alignment.get_alignment_length()): c = [] for record in alignment:...
0.502197
0.312134
import csv import demoji import json import logging import math import re import requests from datetime import datetime exclude_list = [] def preprocess_and_split_text(text): text_without_emojis = demoji.replace_with_desc(text, sep=" ") result = text_without_emojis.split() return result def remove_non_...
parser.py
import csv import demoji import json import logging import math import re import requests from datetime import datetime exclude_list = [] def preprocess_and_split_text(text): text_without_emojis = demoji.replace_with_desc(text, sep=" ") result = text_without_emojis.split() return result def remove_non_...
0.202917
0.116613
import diagnostic_msgs import diagnostic_updater import roboclaw_driver as roboclaw import rospy from motion_control.msg import RoboclawCommand class Node: def __init__(self): self.ERRORS = {0x0000: (diagnostic_msgs.msg.DiagnosticStatus.OK, "Normal"), 0x0001: (diagnostic_msgs.msg.Di...
src/RoboclawNodeCustom.py
import diagnostic_msgs import diagnostic_updater import roboclaw_driver as roboclaw import rospy from motion_control.msg import RoboclawCommand class Node: def __init__(self): self.ERRORS = {0x0000: (diagnostic_msgs.msg.DiagnosticStatus.OK, "Normal"), 0x0001: (diagnostic_msgs.msg.Di...
0.275227
0.129458
import os import pytest import time from benchengine.db import DatabaseDriver from benchengine.user.manager import UserManager import benchengine.error as err import benchtmpl.util.core as util class TestUserManager(object): """Test user registration and password reset.""" def connect(self, base_dir): ...
tests/user/test_user_manager.py
import os import pytest import time from benchengine.db import DatabaseDriver from benchengine.user.manager import UserManager import benchengine.error as err import benchtmpl.util.core as util class TestUserManager(object): """Test user registration and password reset.""" def connect(self, base_dir): ...
0.39129
0.240685
import logging import os from pathlib import Path import re from typing import Any from typing import List from typing import Optional from typing import Tuple import numpy as np import requests from urllib.parse import urlparse DEFAULT_NON_SPEECH_THRESHOLD_FRACTION = 0.5 ALL_SURAHS = None NUM_SURAHS = 114 NO_FRAMES_...
utils/recording.py
import logging import os from pathlib import Path import re from typing import Any from typing import List from typing import Optional from typing import Tuple import numpy as np import requests from urllib.parse import urlparse DEFAULT_NON_SPEECH_THRESHOLD_FRACTION = 0.5 ALL_SURAHS = None NUM_SURAHS = 114 NO_FRAMES_...
0.816662
0.248637
import numpy as np import netCDF4 import pandas as pd import xarray as xr from pylab import * import cartopy.crs as ccrs from matplotlib import pyplot as plt import seaborn as sns import os from scipy.interpolate import griddata from datetime import datetime from datetime import timedelta from dateutil i...
PostProcessing.py
import numpy as np import netCDF4 import pandas as pd import xarray as xr from pylab import * import cartopy.crs as ccrs from matplotlib import pyplot as plt import seaborn as sns import os from scipy.interpolate import griddata from datetime import datetime from datetime import timedelta from dateutil i...
0.31384
0.408454
import unittest import psycopg2 from relately.select import Select from . import RelatelyTest class TestQuery(RelatelyTest): def test_star_from_table(self): r = self.engine.select({ "columns":'*', "target":"world.city" }) self.assertEqual(len(r), 4079) s...
test/test_query.py
import unittest import psycopg2 from relately.select import Select from . import RelatelyTest class TestQuery(RelatelyTest): def test_star_from_table(self): r = self.engine.select({ "columns":'*', "target":"world.city" }) self.assertEqual(len(r), 4079) s...
0.360939
0.50952
import pandas as pd import math as mt import re data_dir = 'E:/data/2019_patent_novelty_aux_files/' # Original data directory out_dir = 'E:/data/2020_research_policy_replicate_results/' # Output directory # Input files claims_file = data_dir+'claim_full_till2018.csv' title_abstract_file = data_dir+'patent_title_abs...
step_01_concatenate_patents.py
import pandas as pd import math as mt import re data_dir = 'E:/data/2019_patent_novelty_aux_files/' # Original data directory out_dir = 'E:/data/2020_research_policy_replicate_results/' # Output directory # Input files claims_file = data_dir+'claim_full_till2018.csv' title_abstract_file = data_dir+'patent_title_abs...
0.24726
0.114393
import sys, Image, ImageDraw, ImageFont from optparse import OptionParser import os import StringIO def get_font_info(chars, font): img = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) draw = ImageDraw.Draw(img) height_prefer = 0 width_min = 0xffff width_max = 0 for ch, _, _ in chars: width, height = draw.texts...
make_font.py
import sys, Image, ImageDraw, ImageFont from optparse import OptionParser import os import StringIO def get_font_info(chars, font): img = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) draw = ImageDraw.Draw(img) height_prefer = 0 width_min = 0xffff width_max = 0 for ch, _, _ in chars: width, height = draw.texts...
0.11181
0.163079
from sonar.core.include.utilities import extractNumber def strToInt(packet): packetArgs = packet[1:-1].split(",") intVal = 0 if packetArgs[0] == "AMHeader": assert (len(packetArgs) == 7),"Invalid number of arguments for AMHeader" if ":" not in packetArgs[1]: argSrc = packetArgs...
GAScore/testbench/sonar_strToInt.py
from sonar.core.include.utilities import extractNumber def strToInt(packet): packetArgs = packet[1:-1].split(",") intVal = 0 if packetArgs[0] == "AMHeader": assert (len(packetArgs) == 7),"Invalid number of arguments for AMHeader" if ":" not in packetArgs[1]: argSrc = packetArgs...
0.17621
0.309663
import argparse from sys import stdout, exit, stderr from simtk.openmm.app import * from simtk.openmm import * from simtk.unit import * def parse_args(): parser = argparse.ArgumentParser(description="Generate and equilibrate a water box") parser.add_argument("-T", "--temperature", action="store", default=298....
scripts/prepare-water-box.py
import argparse from sys import stdout, exit, stderr from simtk.openmm.app import * from simtk.openmm import * from simtk.unit import * def parse_args(): parser = argparse.ArgumentParser(description="Generate and equilibrate a water box") parser.add_argument("-T", "--temperature", action="store", default=298....
0.483648
0.239505
""" Functions for generating the output yaml """ import compose.config import sys from compose.config import serialize, environment import yaml import compose_mode _FILE_LIST_PREFIX = '# ' HEADER_TEMPLATE = """ # ============================================================================== # !! DO NOT EDIT !! #...
compose_mode/generate.py
""" Functions for generating the output yaml """ import compose.config import sys from compose.config import serialize, environment import yaml import compose_mode _FILE_LIST_PREFIX = '# ' HEADER_TEMPLATE = """ # ============================================================================== # !! DO NOT EDIT !! #...
0.524151
0.194616
import re from typing import Any, Dict, Iterable, List import unicodedata # ============================================================================= # Finding # ============================================================================= def find_nth(s: str, x: str, n: int = 0, overlap: bool = False) -> int: ...
cardinal_pythonlib/stringfunc.py
import re from typing import Any, Dict, Iterable, List import unicodedata # ============================================================================= # Finding # ============================================================================= def find_nth(s: str, x: str, n: int = 0, overlap: bool = False) -> int: ...
0.838151
0.477554
import gzip import os import re import pandas as pd # CalN50 total_length = [] number_contigs = [] nx_lx = [] ## Process individual files for s in snakemake.params.samples: fn = f"{snakemake.params.caln50_dir}/{s}-{snakemake.params.assembler}.caln" nl = [] with open(fn, "rt") as caln50file: for l...
workflow/scripts/summary.py
import gzip import os import re import pandas as pd # CalN50 total_length = [] number_contigs = [] nx_lx = [] ## Process individual files for s in snakemake.params.samples: fn = f"{snakemake.params.caln50_dir}/{s}-{snakemake.params.assembler}.caln" nl = [] with open(fn, "rt") as caln50file: for l...
0.216094
0.165121
from ament_index_python.packages import get_package_share_path from launch_ros.actions import Node from launch import LaunchDescription from launch.actions import Shutdown from slamcore_ros2_examples.configuration import Configuration from slamcore_ros2_examples.utils import add_all_actions def generate_launch_descr...
src/slamcore_ros2_examples/launch/kobuki_setup_comms_launch.py
from ament_index_python.packages import get_package_share_path from launch_ros.actions import Node from launch import LaunchDescription from launch.actions import Shutdown from slamcore_ros2_examples.configuration import Configuration from slamcore_ros2_examples.utils import add_all_actions def generate_launch_descr...
0.405449
0.203252
from typing import Dict, Iterator, List, Tuple def adjacent_digits(n: int, digits: str) -> List[str]: """List of all adjacent digits of `n` length in `digits`.""" adjacents = [] while len(digits) >= n: adjacents.append(digits[:n]) digits = digits[1:] return adjacents def fibo(nth: in...
euler/main.py
from typing import Dict, Iterator, List, Tuple def adjacent_digits(n: int, digits: str) -> List[str]: """List of all adjacent digits of `n` length in `digits`.""" adjacents = [] while len(digits) >= n: adjacents.append(digits[:n]) digits = digits[1:] return adjacents def fibo(nth: in...
0.903361
0.572125
import re from typing import List, Tuple import discord from cachetools import TTLCache from discord.ext import commands from bot.bot import PeaceBot from bot.utils.mixins.better_cog import BetterCog from models import AutoResponseModel class AutoResponseError(commands.CommandError): pass class AutoResponseHa...
bot/utils/autoresponse_handler.py
import re from typing import List, Tuple import discord from cachetools import TTLCache from discord.ext import commands from bot.bot import PeaceBot from bot.utils.mixins.better_cog import BetterCog from models import AutoResponseModel class AutoResponseError(commands.CommandError): pass class AutoResponseHa...
0.705379
0.116236
from __future__ import absolute_import, division, print_function from google.cloud import bigquery from .utilities.utility_functions import dictionary_key_exists def create_google_client_connection(project): # Construct a BigQuery client object. client = bigquery.Client( project=project ) re...
get-gbq-permissions/gcp_utilities/gbq.py
from __future__ import absolute_import, division, print_function from google.cloud import bigquery from .utilities.utility_functions import dictionary_key_exists def create_google_client_connection(project): # Construct a BigQuery client object. client = bigquery.Client( project=project ) re...
0.446857
0.163145
import os import subprocess as sp from shlex import split from pathlib import Path __version__ = '0.3' GITHUB_EVENT_NAME = os.environ['GITHUB_EVENT_NAME'] # Set repository CURRENT_REPOSITORY = os.environ.get('GITHUB_REPOSITORY', '') # TODO: How about PRs from forks? TARGET_REPO = os.environ.get('INPUT_TARGET_REPOSI...
src/entrypoint.py
import os import subprocess as sp from shlex import split from pathlib import Path __version__ = '0.3' GITHUB_EVENT_NAME = os.environ['GITHUB_EVENT_NAME'] # Set repository CURRENT_REPOSITORY = os.environ.get('GITHUB_REPOSITORY', '') # TODO: How about PRs from forks? TARGET_REPO = os.environ.get('INPUT_TARGET_REPOSI...
0.145813
0.045395
import io import math from collections import Counter from tqdm import tqdm import tensorflow as tf # TF 2.0 FILE_PATH = './data/' def create_dataset(path, limit_size=None): lines = io.open(path, encoding='UTF-8').read().strip().split('\n') lines = ['<s> ' + line + ' </s>' for line in tqdm(lines[:limit_si...
utils.py
import io import math from collections import Counter from tqdm import tqdm import tensorflow as tf # TF 2.0 FILE_PATH = './data/' def create_dataset(path, limit_size=None): lines = io.open(path, encoding='UTF-8').read().strip().split('\n') lines = ['<s> ' + line + ' </s>' for line in tqdm(lines[:limit_si...
0.511717
0.224682
import random from faker import Faker from .models import User, Post, Comment, Widget, Role fake = Faker('zh_CN') def fake_admin(): user = User(username='admin', name='waynerv', email='<EMAIL>', role='admin', bio='Hello guys.') user.set_passwo...
app/originblog/fake.py
import random from faker import Faker from .models import User, Post, Comment, Widget, Role fake = Faker('zh_CN') def fake_admin(): user = User(username='admin', name='waynerv', email='<EMAIL>', role='admin', bio='Hello guys.') user.set_passwo...
0.327991
0.054828
import keras from keras.applications.resnet50 import ResNet50 from keras.layers import Dense, GlobalAveragePooling2D from keras.models import Model from keras.optimizers import Adam import os from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorB...
checkbox/train.py
import keras from keras.applications.resnet50 import ResNet50 from keras.layers import Dense, GlobalAveragePooling2D from keras.models import Model from keras.optimizers import Adam import os from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorB...
0.70619
0.219547
import json import string # The paths need to be updated visdial_train_data_file = 'visdial_0.9_train.json' visdial_val_data_file = 'visdial_0.9_val.json' vdtrain_questions_file = 'v2_OpenEnded_mscoco_vdtrain_questions.json' vdval_questions_file = 'v2_OpenEnded_mscoco_vdval_questions.json' vdtrain_annotations_fil...
tools/convert_VD_to_COCO_qa.py
import json import string # The paths need to be updated visdial_train_data_file = 'visdial_0.9_train.json' visdial_val_data_file = 'visdial_0.9_val.json' vdtrain_questions_file = 'v2_OpenEnded_mscoco_vdtrain_questions.json' vdval_questions_file = 'v2_OpenEnded_mscoco_vdval_questions.json' vdtrain_annotations_fil...
0.127938
0.095392
import tkinter as tk from tkinter import font as tkfont import sys , os , getpass , socket , subprocess from datetime import datetime from pathlib import Path import ctypes def check_elevate(): if ctypes.windll.shell32.IsUserAnAdmin(): return "Administrator: " else: return "" root...
shell_main.py
import tkinter as tk from tkinter import font as tkfont import sys , os , getpass , socket , subprocess from datetime import datetime from pathlib import Path import ctypes def check_elevate(): if ctypes.windll.shell32.IsUserAnAdmin(): return "Administrator: " else: return "" root...
0.158826
0.069668
import unittest.mock as mock import builtins import json import socket # 3rd party imports import pytest # two1 imorts from two1.commands.util import bitcoin_computer # String to use as the content of the mocked file UUID_STR = "12345678-1234-1234-1234-123456789012" @pytest.mark.parametrize("mock_file, side_effect...
tests/commands/util/test_bitcoin_computer.py
import unittest.mock as mock import builtins import json import socket # 3rd party imports import pytest # two1 imorts from two1.commands.util import bitcoin_computer # String to use as the content of the mocked file UUID_STR = "12345678-1234-1234-1234-123456789012" @pytest.mark.parametrize("mock_file, side_effect...
0.73659
0.371365
import torch from typing import Dict def true_negative(prediction: torch.Tensor, label: torch.Tensor) -> float: """ Return sum of all true negative pixel. :param prediction: Predicted tensor. :param label: Label tensor. :return: True negative count. """ return torch.sum(~prediction & ~lab...
validation/metrics.py
import torch from typing import Dict def true_negative(prediction: torch.Tensor, label: torch.Tensor) -> float: """ Return sum of all true negative pixel. :param prediction: Predicted tensor. :param label: Label tensor. :return: True negative count. """ return torch.sum(~prediction & ~lab...
0.936176
0.939803
# %% from warnings import warn from biosteam.utils import MissingStream from . import Stream __all__ = ('SanStream', 'MissingSanStream') setattr = object.__setattr__ class SanStream(Stream): ''' A subclass of :class:`thermosteam.Stream` with additional attributes for environmental impacts. .. note:...
qsdsan/_sanstream.py
# %% from warnings import warn from biosteam.utils import MissingStream from . import Stream __all__ = ('SanStream', 'MissingSanStream') setattr = object.__setattr__ class SanStream(Stream): ''' A subclass of :class:`thermosteam.Stream` with additional attributes for environmental impacts. .. note:...
0.785884
0.314958
from edgedb.lang.edgeql import ast as qlast from . import delta as sd from . import derivable from . import inheriting from . import name as sn from . import named from . import objects as so from . import referencing class Action(inheriting.InheritingObject): _type = 'action' class ActionSet(so.ObjectSet, t...
edgedb/lang/schema/policy.py
from edgedb.lang.edgeql import ast as qlast from . import delta as sd from . import derivable from . import inheriting from . import name as sn from . import named from . import objects as so from . import referencing class Action(inheriting.InheritingObject): _type = 'action' class ActionSet(so.ObjectSet, t...
0.603581
0.175679
import unittest from sistema_clasico_cuantico import canicas_clicks, probabilistico_clicks, cuantico_clicks, grafico class sistema_clasico_cualtico(unittest.TestCase): def testcanicas_clicks(self): matriz_booleana = [[True, True, False, False, True, False], [True, True, False, True, False, False], ...
test_cuantico.py
import unittest from sistema_clasico_cuantico import canicas_clicks, probabilistico_clicks, cuantico_clicks, grafico class sistema_clasico_cualtico(unittest.TestCase): def testcanicas_clicks(self): matriz_booleana = [[True, True, False, False, True, False], [True, True, False, True, False, False], ...
0.377885
0.568476
from django.core.management.base import BaseCommand from Product.models import Product, Category, Store from .api_get import Api_get class Command(BaseCommand): help = "initialize database" def handle(self, *args, **kwargs): """retrieve a list of products in JSON format through Open Food Fact ...
Product/management/commands/create_db.py
from django.core.management.base import BaseCommand from Product.models import Product, Category, Store from .api_get import Api_get class Command(BaseCommand): help = "initialize database" def handle(self, *args, **kwargs): """retrieve a list of products in JSON format through Open Food Fact ...
0.527803
0.126596
import argparse from intern.remote.boss import BossRemote from intern.resource.boss.resource import * import json import os # Name of group to assign read-only privileges to. GOV_TEAM = 'gov_team' def create_collection(config, rmt): """ Ensure collection exists. Args: config (dict): rmt ...
ingestclient/prep_ingest.py
import argparse from intern.remote.boss import BossRemote from intern.resource.boss.resource import * import json import os # Name of group to assign read-only privileges to. GOV_TEAM = 'gov_team' def create_collection(config, rmt): """ Ensure collection exists. Args: config (dict): rmt ...
0.620162
0.134321
import re import os import datetime from functools import partial import pandas as pd import numpy as np from collections import defaultdict # ------------------------------- # dataframe on disk caching layer # ------------------------------- class DataFrameToCSVCache: """ Dict-like API CSV based cache to store d...
jupyter/swan.py
import re import os import datetime from functools import partial import pandas as pd import numpy as np from collections import defaultdict # ------------------------------- # dataframe on disk caching layer # ------------------------------- class DataFrameToCSVCache: """ Dict-like API CSV based cache to store d...
0.628749
0.185412
# template file: justice_py_sdk_codegen/__main__.py # justice-iam-service (5.10.1) # pylint: disable=duplicate-code # pylint: disable=line-too-long # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=too-many-arguments # pylint: disable=too-many-branches # pylint...
accelbyte_py_sdk/api/iam/models/model_link_request.py
# template file: justice_py_sdk_codegen/__main__.py # justice-iam-service (5.10.1) # pylint: disable=duplicate-code # pylint: disable=line-too-long # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=too-many-arguments # pylint: disable=too-many-branches # pylint...
0.535827
0.097691
from __future__ import annotations from typing import List import numpy as np from nncg.allocation import Allocation from nncg.nodes.expressions import Variable from nncg.nodes.misc import Node from nncg.writer import Writer class CHeaderNode(Node): """ Class for writing everything in a C file that is above t...
nncg/nodes/language.py
from __future__ import annotations from typing import List import numpy as np from nncg.allocation import Allocation from nncg.nodes.expressions import Variable from nncg.nodes.misc import Node from nncg.writer import Writer class CHeaderNode(Node): """ Class for writing everything in a C file that is above t...
0.561335
0.24931
from __future__ import print_function, unicode_literals, division, absolute_import import os, sys, io, locale, threading from io import TextIOWrapper from contextlib import contextmanager from collections import MutableMapping try: sys_encoding = locale.getdefaultlocale()[1] or "UTF-8" except Exception: sys_...
src/python/dxpy/compat.py
from __future__ import print_function, unicode_literals, division, absolute_import import os, sys, io, locale, threading from io import TextIOWrapper from contextlib import contextmanager from collections import MutableMapping try: sys_encoding = locale.getdefaultlocale()[1] or "UTF-8" except Exception: sys_...
0.326808
0.053059
import os, sys, argparse, logging, boto3 from io import BytesIO from time import sleep from picamera import PiCamera from ftplib import FTP def acquire_image(log, args): output_stream = BytesIO() try: camera = PiCamera() camera.resolution = (args.res_width, args.res_height) # Camera warm-up time for automatic...
berrycam/berrycam.py
import os, sys, argparse, logging, boto3 from io import BytesIO from time import sleep from picamera import PiCamera from ftplib import FTP def acquire_image(log, args): output_stream = BytesIO() try: camera = PiCamera() camera.resolution = (args.res_width, args.res_height) # Camera warm-up time for automatic...
0.267026
0.152347
from __future__ import absolute_import, division, print_function, unicode_literals from transitions import Machine from socks5.exception import ProtocolError from ._reader import read_auth_request, read_auth_response from ._writer import write_auth_request, write_auth_response class _ClientConnection(object): s...
socks5/auth/rfc1929/connection.py
from __future__ import absolute_import, division, print_function, unicode_literals from transitions import Machine from socks5.exception import ProtocolError from ._reader import read_auth_request, read_auth_response from ._writer import write_auth_request, write_auth_response class _ClientConnection(object): s...
0.649467
0.2027
import redis import hiredis import pickle from redis.sentinel import Sentinel from Globals import Packet as pack class RedisDB_Wrapper: def __init__(self, db_number, host_IP='127.0.0.1', port=6379): self._isDbConnectionActive = False self._hostIP = host_IP self._port = port self._db...
DB/Redis_DB_Controller.py
import redis import hiredis import pickle from redis.sentinel import Sentinel from Globals import Packet as pack class RedisDB_Wrapper: def __init__(self, db_number, host_IP='127.0.0.1', port=6379): self._isDbConnectionActive = False self._hostIP = host_IP self._port = port self._db...
0.219756
0.07208
from apiclient import errors import os import _config_ as _cfg import _dbms_ as _db import _logging_ as _log def get_labels(db, labels_obj, user_id='me'): results = labels_obj.list(userId='me').execute() labels = results.get('labels', []) if not labels: _log.logger.info("No labels found.") ...
_google_/gmail/__init__.py
from apiclient import errors import os import _config_ as _cfg import _dbms_ as _db import _logging_ as _log def get_labels(db, labels_obj, user_id='me'): results = labels_obj.list(userId='me').execute() labels = results.get('labels', []) if not labels: _log.logger.info("No labels found.") ...
0.573798
0.082697
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QInputDialog, QDialog from Business.PartAction import create_add_sketch_to_part, insert_sketch_in_part from GUI.Widgets.SimpleDialogs import SketchDialog from GUI.init import plugin_initializers, tr from GUI.Ribbon.RibbonButton import RibbonButton class PartSk...
GUI/Plugins/PartSketch.py
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QInputDialog, QDialog from Business.PartAction import create_add_sketch_to_part, insert_sketch_in_part from GUI.Widgets.SimpleDialogs import SketchDialog from GUI.init import plugin_initializers, tr from GUI.Ribbon.RibbonButton import RibbonButton class PartSk...
0.451085
0.104889