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 work_materials.globals import * import time, datetime class Trigger: def __init__(self, trigger_type, text): self.type = trigger_type self.text = text #Типы триггеров - 0 - текст, 1 - видео, 2 - аудио, 3 - фото, 4 - документ, 5 - стикер, 6 - войс def add_trigger(self, incoming, ...
libs/trigger.py
from work_materials.globals import * import time, datetime class Trigger: def __init__(self, trigger_type, text): self.type = trigger_type self.text = text #Типы триггеров - 0 - текст, 1 - видео, 2 - аудио, 3 - фото, 4 - документ, 5 - стикер, 6 - войс def add_trigger(self, incoming, ...
0.143893
0.102619
__all__ = [ 'make_bdist_zipapp', ] import distutils.core import distutils.errors import distutils.log import stat import tempfile import zipfile from pathlib import Path def make_bdist_zipapp( *, python='/usr/bin/env python3', main_optional=False, main=None ): # pylint: disable=too-many-statements c...
py/g1/devtools/buildtools/g1/devtools/buildtools/zipapps.py
__all__ = [ 'make_bdist_zipapp', ] import distutils.core import distutils.errors import distutils.log import stat import tempfile import zipfile from pathlib import Path def make_bdist_zipapp( *, python='/usr/bin/env python3', main_optional=False, main=None ): # pylint: disable=too-many-statements c...
0.226955
0.053477
import math import torch from catalyst.utils.metrics import mean_average_precision def test_mean_average_precision_weighted(): """ Tests for catalyst.utils.metrics.mean_average_precision metric. """ target = torch.Tensor([0, 1, 0, 1]) output = torch.Tensor([0.1, 0.2, 0.3, 4]) weight = torch....
catalyst/utils/metrics/tests/test_mean_average_precision.py
import math import torch from catalyst.utils.metrics import mean_average_precision def test_mean_average_precision_weighted(): """ Tests for catalyst.utils.metrics.mean_average_precision metric. """ target = torch.Tensor([0, 1, 0, 1]) output = torch.Tensor([0.1, 0.2, 0.3, 4]) weight = torch....
0.862858
0.659446
import json from io import StringIO import click from .. import rsf, xsv, Register, Blob, validator from ..exceptions import RegistersException from . import utils @click.group(name="blob") def blob_group(): """ Blob operations. For example, you can validate that a blob '{"country": "ZZ", "name": "Zeta"}...
registers/commands/blob.py
import json from io import StringIO import click from .. import rsf, xsv, Register, Blob, validator from ..exceptions import RegistersException from . import utils @click.group(name="blob") def blob_group(): """ Blob operations. For example, you can validate that a blob '{"country": "ZZ", "name": "Zeta"}...
0.478773
0.298964
import six from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib import exceptions as lib_exc from tempest import test import testtools from manila_tempest_tests.tests.api import base CONF = config.CONF class ManageNFSSnapshotTest(base.BaseSharesAdminTest): protocol = 'nfs...
manila_tempest_tests/tests/api/admin/test_snapshot_manage.py
import six from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib import exceptions as lib_exc from tempest import test import testtools from manila_tempest_tests.tests.api import base CONF = config.CONF class ManageNFSSnapshotTest(base.BaseSharesAdminTest): protocol = 'nfs...
0.40157
0.11422
from typing import Callable from wf_airtable_api_schema.models.educators_schools import * from wf_airtable_api_schema.models import educators_schools from . import response as response_models from . import educators as educators_models from . import schools as schools_models from ..airtable.base_school_db import ( ...
app/models/educators_schools.py
from typing import Callable from wf_airtable_api_schema.models.educators_schools import * from wf_airtable_api_schema.models import educators_schools from . import response as response_models from . import educators as educators_models from . import schools as schools_models from ..airtable.base_school_db import ( ...
0.665193
0.250363
import logging import os import click import shutil from deepfigures import settings from scripts import build, execute, detectfigures # Same module as in detectfigures.py in deepfigures_open # However, this proved to be easiest and least error prone way to use function def detectfigures( output_directory, ...
scripts/bulk_detectfigures.py
import logging import os import click import shutil from deepfigures import settings from scripts import build, execute, detectfigures # Same module as in detectfigures.py in deepfigures_open # However, this proved to be easiest and least error prone way to use function def detectfigures( output_directory, ...
0.47171
0.206414
import random """ none = 0 fruit = 1 head = 2 body = 3 """ def get_point(size, board): """Returns x,y in board which is empty,else None""" i = 0 # A max try of 20 chances for _ in range(20): x = random.randint(0, size - 1) y = random.randint(0, size - 1) if board[x][y] == 0: ...
snake/game.py
import random """ none = 0 fruit = 1 head = 2 body = 3 """ def get_point(size, board): """Returns x,y in board which is empty,else None""" i = 0 # A max try of 20 chances for _ in range(20): x = random.randint(0, size - 1) y = random.randint(0, size - 1) if board[x][y] == 0: ...
0.380759
0.302713
import pandas as pd from .core import BarPLot, HeatMap, ScatterPlot, TablePlot, BoxPlot from .finegrained import get_fine_grained_figure from .utils import recursive_update @pd.api.extensions.register_dataframe_accessor("iplot") class FrameIplotMethods(): """DataFrame interactive plotting accessor and method ...
plotlyink/register_pandas_accessors.py
import pandas as pd from .core import BarPLot, HeatMap, ScatterPlot, TablePlot, BoxPlot from .finegrained import get_fine_grained_figure from .utils import recursive_update @pd.api.extensions.register_dataframe_accessor("iplot") class FrameIplotMethods(): """DataFrame interactive plotting accessor and method ...
0.92406
0.375621
import types import operator import six class Field(object): getter_takes_serializer = False def __init__(self, attr=None, call=False, label=None, required=True): self.attr = attr self.call = call self.label = label self.required = required def to_value(self, value): ...
Back-End/Python/External Libraries/Serpy/Serpy-Mini/serpy_.py
import types import operator import six class Field(object): getter_takes_serializer = False def __init__(self, attr=None, call=False, label=None, required=True): self.attr = attr self.call = call self.label = label self.required = required def to_value(self, value): ...
0.654564
0.156523
from __future__ import print_function import datetime import dateutil.parser # available on PyPi as `python-dateutil` import mysql.connector # available on PyPi as `mysql-connector` import nba_py.league import nba_py.player from nba_py.constants import CURRENT_SEASON import os import sys from collections import named...
nba_update_censor.py
from __future__ import print_function import datetime import dateutil.parser # available on PyPi as `python-dateutil` import mysql.connector # available on PyPi as `mysql-connector` import nba_py.league import nba_py.player from nba_py.constants import CURRENT_SEASON import os import sys from collections import named...
0.409929
0.380299
from unittest.mock import call, patch import pytest from second_qualification import forms @pytest.fixture def form_data(): return { 'emt_id': 42, 'phone_number': '0000000000', 'arrange_callback': forms.ARRANGE_CALLBACK_CHOICES[0][0], } def test_second_qualification_form_required()...
second_qualification/tests/test_form.py
from unittest.mock import call, patch import pytest from second_qualification import forms @pytest.fixture def form_data(): return { 'emt_id': 42, 'phone_number': '0000000000', 'arrange_callback': forms.ARRANGE_CALLBACK_CHOICES[0][0], } def test_second_qualification_form_required()...
0.670177
0.362292
from objc import * from Foundation import * import cmd import os import logging import time from pprint import pformat try: from queue import Queue, Empty except: from Queue import Queue, Empty from pyble.patterns import LoggerObject class OSXCmd(cmd.Cmd, LoggerObject): def __init__(self, history_size=...
pyble/osx/console.py
from objc import * from Foundation import * import cmd import os import logging import time from pprint import pformat try: from queue import Queue, Empty except: from Queue import Queue, Empty from pyble.patterns import LoggerObject class OSXCmd(cmd.Cmd, LoggerObject): def __init__(self, history_size=...
0.233532
0.061848
import innertube import innertube.utils import innertube.enums import innertube.errors import requests import furl import json import re import urllib.parse from typing import \ ( Union, Optional, ) def watch \ ( *, video_id: Optional[str] = None, playlist_id: ...
youtube/operations.py
import innertube import innertube.utils import innertube.enums import innertube.errors import requests import furl import json import re import urllib.parse from typing import \ ( Union, Optional, ) def watch \ ( *, video_id: Optional[str] = None, playlist_id: ...
0.483405
0.147924
import sys import numpy as np np.random.seed(int(sys.argv[2])) import tensorflow as tf tf.set_random_seed(int(sys.argv[3])) import utils import models from keras.callbacks import EarlyStopping from keras.preprocessing.image import ImageDataGenerator from sklearn.model_selection import ShuffleSplit import matplotlib.pyp...
loyo_testing.py
import sys import numpy as np np.random.seed(int(sys.argv[2])) import tensorflow as tf tf.set_random_seed(int(sys.argv[3])) import utils import models from keras.callbacks import EarlyStopping from keras.preprocessing.image import ImageDataGenerator from sklearn.model_selection import ShuffleSplit import matplotlib.pyp...
0.379493
0.286543
import os import subprocess from unittest import mock from . import * from .... import * from mopack.builders.bfg9000 import Bfg9000Builder from mopack.config import Config from mopack.path import Path from mopack.sources import Package from mopack.sources.apt import AptPackage from mopack.sources.sdist import Tarbal...
test/unit/sources/sdist/test_tarball.py
import os import subprocess from unittest import mock from . import * from .... import * from mopack.builders.bfg9000 import Bfg9000Builder from mopack.config import Config from mopack.path import Path from mopack.sources import Package from mopack.sources.apt import AptPackage from mopack.sources.sdist import Tarbal...
0.467332
0.234144
from __future__ import division import time import numpy as np import trainer from params import params as P import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from functools import partial import logging import scipy.misc from parallel import ParallelBatchIterator from tqdm import tqdm import os.p...
src/deep/unet/unet_trainer.py
from __future__ import division import time import numpy as np import trainer from params import params as P import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from functools import partial import logging import scipy.misc from parallel import ParallelBatchIterator from tqdm import tqdm import os.p...
0.609989
0.147402
from mock import patch, Mock, call import unittest from pitmTemperature import pitmTemperature class TestStringMethods(unittest.TestCase): def setUp(self): self.subject = pitmTemperature() self.subject._log = Mock() @patch('time.sleep') @patch('pitmTemperature.pitmTemperature._read_tempe...
brewerslab-orig-slave/test/test_pitmTemperature.py
from mock import patch, Mock, call import unittest from pitmTemperature import pitmTemperature class TestStringMethods(unittest.TestCase): def setUp(self): self.subject = pitmTemperature() self.subject._log = Mock() @patch('time.sleep') @patch('pitmTemperature.pitmTemperature._read_tempe...
0.662251
0.283059
import os import pdb # noqa import shutil from typing import Any, List, Optional, Tuple import OpenGL.GL as GL import OpenGL.GLU as GLU import glfw import imageio import numpy as np import pygame.time from torch import Tensor from contactnets.interaction import PolyGeometry3D from contactnets.system import SimResult...
contactnets/vis/visualizer_3d.py
import os import pdb # noqa import shutil from typing import Any, List, Optional, Tuple import OpenGL.GL as GL import OpenGL.GLU as GLU import glfw import imageio import numpy as np import pygame.time from torch import Tensor from contactnets.interaction import PolyGeometry3D from contactnets.system import SimResult...
0.869202
0.533519
import re import numpy as np import copy import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons from matplotlib.lines import Line2D from matplotlib.cm import get_cmap LINE_STYLES = ['--', '-.', '--', ':'] COLORS = [i for i in get_cmap('tab20').colors] LEAPMOTION = 'Leap Motion' INTERPOLATION = '...
app/AnybodyResults.py
import re import numpy as np import copy import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons from matplotlib.lines import Line2D from matplotlib.cm import get_cmap LINE_STYLES = ['--', '-.', '--', ':'] COLORS = [i for i in get_cmap('tab20').colors] LEAPMOTION = 'Leap Motion' INTERPOLATION = '...
0.49585
0.435661
from django.contrib import admin from django.utils.html import format_html from reversion.admin import VersionAdmin from elections.models import Election, ElectionResult, PresidentCandidate, PresidentCandidateBiography, \ PresidentCandidatePoliticalExperience, PresidentCandidateWorkExperience, PresidentCandidateAr...
elections/admin.py
from django.contrib import admin from django.utils.html import format_html from reversion.admin import VersionAdmin from elections.models import Election, ElectionResult, PresidentCandidate, PresidentCandidateBiography, \ PresidentCandidatePoliticalExperience, PresidentCandidateWorkExperience, PresidentCandidateAr...
0.344333
0.125306
from functools import wraps from .inspect import TrueSight, shape_shift, WHITELISTED # If I'm raised, I probably didn't use a TrueSight obj where I needed to def ensure_truesight(_accessed, *args, **kwargs): if not _accessed == "__getattr__": return arg = args[0] if arg in WHITELISTED: ra...
mimics/record.py
from functools import wraps from .inspect import TrueSight, shape_shift, WHITELISTED # If I'm raised, I probably didn't use a TrueSight obj where I needed to def ensure_truesight(_accessed, *args, **kwargs): if not _accessed == "__getattr__": return arg = args[0] if arg in WHITELISTED: ra...
0.627951
0.098123
from django.test import TestCase from geokey.contributions.templatetags import kml_tags from geokey.categories.tests.model_factories import CategoryFactory class TemplateTagsTest(TestCase): def test_kml_name(self): name = kml_tags.kml_name({'display_field': {'value': 'Awesome pub'}}) self.asser...
geokey/contributions/tests/observations/test_templatetags.py
from django.test import TestCase from geokey.contributions.templatetags import kml_tags from geokey.categories.tests.model_factories import CategoryFactory class TemplateTagsTest(TestCase): def test_kml_name(self): name = kml_tags.kml_name({'display_field': {'value': 'Awesome pub'}}) self.asser...
0.475362
0.355439
import arcpy import os import sys import datetime import logging def copy_sotd_features(feat_list, stamp, log): for feat in feat_list: try: if arcpy.Exists(feat+'_'+stamp): pass else: arcpy.CopyFeatures_management(feat, feat+'_'+stamp) ...
state-of-the-data-for-production/src/backup_sotd_results.py
import arcpy import os import sys import datetime import logging def copy_sotd_features(feat_list, stamp, log): for feat in feat_list: try: if arcpy.Exists(feat+'_'+stamp): pass else: arcpy.CopyFeatures_management(feat, feat+'_'+stamp) ...
0.199776
0.144119
from abc import ABCMeta, abstractmethod import six @six.add_metaclass(ABCMeta) class Metric(object): REGISTRY_NAME = "metric" def __init__(self, *args, **kwargs): self._flag = self.__class__.__name__ @property def flag(self): return self._flag @flag.setter def flag(self, fl...
neurst/metrics/metric.py
from abc import ABCMeta, abstractmethod import six @six.add_metaclass(ABCMeta) class Metric(object): REGISTRY_NAME = "metric" def __init__(self, *args, **kwargs): self._flag = self.__class__.__name__ @property def flag(self): return self._flag @flag.setter def flag(self, fl...
0.914094
0.266068
import os import json from ast import literal_eval # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Load the configuration file (config.json, not config.py) config_file = os.path.join(BASE_DIR, "config.json") with open(c...
metadataset/settings.py
import os import json from ast import literal_eval # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Load the configuration file (config.json, not config.py) config_file = os.path.join(BASE_DIR, "config.json") with open(c...
0.385606
0.05848
import yaml import os from appium import webdriver global data class AppiumInit(object): """appium server""" def appium_init(self): """读取配置文件的数据""" global driver file = open('D:\AutoTest\config\config.yaml', 'r',encoding='utf-8') data = yaml.load(file) desired_caps = {} ...
comm/common.py
import yaml import os from appium import webdriver global data class AppiumInit(object): """appium server""" def appium_init(self): """读取配置文件的数据""" global driver file = open('D:\AutoTest\config\config.yaml', 'r',encoding='utf-8') data = yaml.load(file) desired_caps = {} ...
0.146911
0.102934
import torch import torch.nn as nn class Baselayer: def __init__(self, layername: str, id: int, input: int, output: int, statedict: list): self.layername = layername self.inputlayer = input self.outputlayer = output self.layerid = id self.inputchannel = 0 self.outpu...
model/prune/Block.py
import torch import torch.nn as nn class Baselayer: def __init__(self, layername: str, id: int, input: int, output: int, statedict: list): self.layername = layername self.inputlayer = input self.outputlayer = output self.layerid = id self.inputchannel = 0 self.outpu...
0.732496
0.388676
import random from typing import Any, Callable, Dict, List, Optional, Tuple, Set import storable import copy class FeatureFilter(storable.Storable): """ FeatureFilters accept a list of feature dictionaries. """ args: tuple kwargs: dict filter_name: str subfilters: list _filter_prefix...
src/feature_filter.py
import random from typing import Any, Callable, Dict, List, Optional, Tuple, Set import storable import copy class FeatureFilter(storable.Storable): """ FeatureFilters accept a list of feature dictionaries. """ args: tuple kwargs: dict filter_name: str subfilters: list _filter_prefix...
0.832169
0.195902
# ============================================================================= __version__ = '$Revision$' __author__ = '<NAME> <EMAIL>' __date__ = '2016-02-23' __all__ = ( 'Task' , ## the base class for task 'TaskManager' , ## task manager ) # ===============================================...
ostap/parallel/mp_pathos.py
# ============================================================================= __version__ = '$Revision$' __author__ = '<NAME> <EMAIL>' __date__ = '2016-02-23' __all__ = ( 'Task' , ## the base class for task 'TaskManager' , ## task manager ) # ===============================================...
0.276886
0.067087
# This file was generated by running `python -m dagster.grpc.compile` # Do not edit this file directly, and do not attempt to recompile it using # grpc_tools.protoc directly, as several changes must be made to the raw output # pylint: disable=protected-access # -*- coding: utf-8 -*- # Generated by the protocol buffe...
python_modules/dagster/dagster/grpc/__generated__/api_pb2.py
# This file was generated by running `python -m dagster.grpc.compile` # Do not edit this file directly, and do not attempt to recompile it using # grpc_tools.protoc directly, as several changes must be made to the raw output # pylint: disable=protected-access # -*- coding: utf-8 -*- # Generated by the protocol buffe...
0.365796
0.060585
import json import os import sched import threading import time from hashlib import sha256 import traceback import arrow import requests from ics import Calendar from tatsu.exceptions import FailedParse from tools.tools import horodate, process def cache(entry: dict, scheduler: sched.scheduler = None) -> None: "...
app/tools/caching.py
import json import os import sched import threading import time from hashlib import sha256 import traceback import arrow import requests from ics import Calendar from tatsu.exceptions import FailedParse from tools.tools import horodate, process def cache(entry: dict, scheduler: sched.scheduler = None) -> None: "...
0.451568
0.174059
from django import forms from portfolios.models import ( Skill, ProfessionalExperience, ProfessionalExperienceMedia, Education, EducationMedia, Certification, CertificationMedia, Project, ProjectMedia, Interest, Testimonial ) from portfolios.forms import ( SkillForm, ProfessionalExpe...
backend/portfolios/views.py
from django import forms from portfolios.models import ( Skill, ProfessionalExperience, ProfessionalExperienceMedia, Education, EducationMedia, Certification, CertificationMedia, Project, ProjectMedia, Interest, Testimonial ) from portfolios.forms import ( SkillForm, ProfessionalExpe...
0.530723
0.087876
from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 482769947 """ """ random actions, total chaos """ board = gamma_new(4, 5, 4, 4) assert board is...
z2/part3/updated_part2_batch/jm/parser_errors_2/482769947.py
from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 482769947 """ """ random actions, total chaos """ board = gamma_new(4, 5, 4, 4) assert board is...
0.828696
0.785761
import sys import io PY2 = (sys.version_info[0] == 2) if PY2: import unicodecsv unicodecsv.field_size_limit(sys.maxsize) def csvreader(file, encoding=None, **kwargs): ''' Pass encoding to unicodecsv ''' if encoding is not None: kwargs['encoding'] = encoding ...
openaddr/compat.py
import sys import io PY2 = (sys.version_info[0] == 2) if PY2: import unicodecsv unicodecsv.field_size_limit(sys.maxsize) def csvreader(file, encoding=None, **kwargs): ''' Pass encoding to unicodecsv ''' if encoding is not None: kwargs['encoding'] = encoding ...
0.266453
0.058346
from keras.models import Sequential,Model from keras.layers import LSTM, Dense, Dropout,Input,InputLayer,SpatialDropout1D,Conv1D,MaxPool1D,Flatten,concatenate from keras.layers.embeddings import Embedding def lstm(max_len,input_dim,output_dim=None,weight_matrix=None,input_type='wordindex',class_num=1): model = Seq...
fxy/model.py
from keras.models import Sequential,Model from keras.layers import LSTM, Dense, Dropout,Input,InputLayer,SpatialDropout1D,Conv1D,MaxPool1D,Flatten,concatenate from keras.layers.embeddings import Embedding def lstm(max_len,input_dim,output_dim=None,weight_matrix=None,input_type='wordindex',class_num=1): model = Seq...
0.7181
0.276825
from typing import List, Tuple import pytest from target_extraction.pos_taggers import stanford, spacy_tagger class TestPOSTaggers: def _en_emoji_sentence(self) -> Tuple[List[str], str]: return (['Hello', 'how', 'are', 'you', ',', 'with', 'other', "'s", ':)'], " Hello how are you, with...
tests/pos_taggers_test.py
from typing import List, Tuple import pytest from target_extraction.pos_taggers import stanford, spacy_tagger class TestPOSTaggers: def _en_emoji_sentence(self) -> Tuple[List[str], str]: return (['Hello', 'how', 'are', 'you', ',', 'with', 'other', "'s", ':)'], " Hello how are you, with...
0.662796
0.510192
from collections import namedtuple Customer = namedtuple('Customer', 'name is_88vip') Product = namedtuple('Product', 'name price') class Order: def __init__(self, customer, cart, promotion=None): """订单类 Args: customer (Customer): 该订单的顾客 cart (list): 购物车列表 pr...
src/python/practice/Discount.py
from collections import namedtuple Customer = namedtuple('Customer', 'name is_88vip') Product = namedtuple('Product', 'name price') class Order: def __init__(self, customer, cart, promotion=None): """订单类 Args: customer (Customer): 该订单的顾客 cart (list): 购物车列表 pr...
0.593374
0.162446
from py_dss_interface.models.Example.ExampleBase import ExampleBase dss = ExampleBase("13").dss # Integer methods print(45 * '=' + ' Integer Methods' + 45 * '=') print(f'dss.linecodes_count(): {dss.linecodes_count()}') print(f'dss.linecodes_first(): {dss.linecodes_first()}') print(f'dss.linecodes_next(): {dss.linecod...
examples/16_Example_LineCodes.py
from py_dss_interface.models.Example.ExampleBase import ExampleBase dss = ExampleBase("13").dss # Integer methods print(45 * '=' + ' Integer Methods' + 45 * '=') print(f'dss.linecodes_count(): {dss.linecodes_count()}') print(f'dss.linecodes_first(): {dss.linecodes_first()}') print(f'dss.linecodes_next(): {dss.linecod...
0.492188
0.211051
import logging from typing import Any, Dict from flask import Blueprint, request from bling.helpscout.mailboxes import MAILBOXES_BY_ID, MAILBOXES_BY_TWILIO_PHONE from bling.clients import ( twilio_transport, incoming_message_handler, outgoing_reply_handler, transport_for_type, ) from bling.transport...
bling/api.py
import logging from typing import Any, Dict from flask import Blueprint, request from bling.helpscout.mailboxes import MAILBOXES_BY_ID, MAILBOXES_BY_TWILIO_PHONE from bling.clients import ( twilio_transport, incoming_message_handler, outgoing_reply_handler, transport_for_type, ) from bling.transport...
0.564699
0.107063
import asyncio import ssl from typing import Iterator, Optional from checklisting.result import BaseTaskResult, TaskResult from checklisting.result.builder import MultiTaskResultBuilder from checklisting.result.status import TaskResultStatus from checklisting.task import BaseTask from checklisting.tasks.socket import ...
src/checklisting/tasks/services/zookeeper.py
import asyncio import ssl from typing import Iterator, Optional from checklisting.result import BaseTaskResult, TaskResult from checklisting.result.builder import MultiTaskResultBuilder from checklisting.result.status import TaskResultStatus from checklisting.task import BaseTask from checklisting.tasks.socket import ...
0.619817
0.11353
import os import torch import glob class Config(object): def __init__(self): self.target_task = ['qmsum-latent', # 0: qmsum-latent 'arxiv-latent', # 1: arxiv-latent 'govreport-latent', # 2: govreport-latent ][2] ...
config.py
import os import torch import glob class Config(object): def __init__(self): self.target_task = ['qmsum-latent', # 0: qmsum-latent 'arxiv-latent', # 1: arxiv-latent 'govreport-latent', # 2: govreport-latent ][2] ...
0.512205
0.343562
import requests import os from shutil import rmtree import tempfile from config import ensureConfig from subprocess import call from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend # print(os.env...
back-end/service.py
import requests import os from shutil import rmtree import tempfile from config import ensureConfig from subprocess import call from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend # print(os.env...
0.282889
0.086709
import warnings from extra.lists.queue import Queue class Deque(Queue): """ A deque, which is usually pronounced "deck", is a queue-like data structure that supports insertion and deletion at both the front and the back of the queue. Deque is a short for "double-ended queue". The deque is more general...
extra/lists/deque.py
import warnings from extra.lists.queue import Queue class Deque(Queue): """ A deque, which is usually pronounced "deck", is a queue-like data structure that supports insertion and deletion at both the front and the back of the queue. Deque is a short for "double-ended queue". The deque is more general...
0.933741
0.678919
import os import shutil from types import ModuleType from typing import List import sys import pytest from stubdoc import stubdoc from stubdoc.stubdoc import _get_callable_names_from_module def setup() -> None: _delete_test_modules_and_stubs() def teardown() -> None: _delete_test_modules_...
tests/test_stubdoc.py
import os import shutil from types import ModuleType from typing import List import sys import pytest from stubdoc import stubdoc from stubdoc.stubdoc import _get_callable_names_from_module def setup() -> None: _delete_test_modules_and_stubs() def teardown() -> None: _delete_test_modules_...
0.439747
0.372049
import geopandas class TileInfo: """ A class for working with tiling information """ def __init__(self, tile_file: str, catchment_polygon: geopandas.geodataframe.GeoDataFrame): self._tile_info = geopandas.read_file(tile_file) self.catchment_polygon = catchment_polygon self.file_name ...
src/geoapis/geometry.py
import geopandas class TileInfo: """ A class for working with tiling information """ def __init__(self, tile_file: str, catchment_polygon: geopandas.geodataframe.GeoDataFrame): self._tile_info = geopandas.read_file(tile_file) self.catchment_polygon = catchment_polygon self.file_name ...
0.711331
0.553988
from mics.segment.models.unet_parts import * import torch.nn as nn import torch.nn.functional as F class UNET(nn.Module): """ Implementation of UNET model as per the paper of Ronneberg when using default values. In case of skip being True the feature maps are passed through a convolutional layer before being ...
segment/models/models.py
from mics.segment.models.unet_parts import * import torch.nn as nn import torch.nn.functional as F class UNET(nn.Module): """ Implementation of UNET model as per the paper of Ronneberg when using default values. In case of skip being True the feature maps are passed through a convolutional layer before being ...
0.973544
0.819677
import json import logging import platform import types import os import signal import sys from time import sleep from logging.config import fileConfig from .constants import DEFAULT_LOGGING_PATH from typing import Optional, List from diagnostic.broker import Broker from inbm_lib.windows_service import WindowsService ...
inbm/diagnostic-agent/diagnostic/main.py
import json import logging import platform import types import os import signal import sys from time import sleep from logging.config import fileConfig from .constants import DEFAULT_LOGGING_PATH from typing import Optional, List from diagnostic.broker import Broker from inbm_lib.windows_service import WindowsService ...
0.554712
0.124107
import json import copy import urllib from django.shortcuts import get_object_or_404, render, redirect, reverse from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, Http404 from city_guide.models import Attraction, Category, Ticket, TicketType, Tour, Profile, Order, User, UserBreak from django.temp...
CityGuide/city_guide/views.py
import json import copy import urllib from django.shortcuts import get_object_or_404, render, redirect, reverse from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, Http404 from city_guide.models import Attraction, Category, Ticket, TicketType, Tour, Profile, Order, User, UserBreak from django.temp...
0.385028
0.061848
from __clrclasses__.System import Enum as _n_0_t_0 from __clrclasses__.System import IComparable as _n_0_t_1 from __clrclasses__.System import IFormattable as _n_0_t_2 from __clrclasses__.System import IConvertible as _n_0_t_3 from __clrclasses__.System import Array as _n_0_t_4 from __clrclasses__.System import Attribu...
extensions/.stubs/clrclasses/__clrclasses__/System/Security/Permissions/__init__.py
from __clrclasses__.System import Enum as _n_0_t_0 from __clrclasses__.System import IComparable as _n_0_t_1 from __clrclasses__.System import IFormattable as _n_0_t_2 from __clrclasses__.System import IConvertible as _n_0_t_3 from __clrclasses__.System import Array as _n_0_t_4 from __clrclasses__.System import Attribu...
0.685423
0.075858
import re, csv, string from pyspark import SparkConf, SparkContext from pyspark.sql import Row, SparkSession from pyspark.sql.functions import rand from pyspark.ml import Pipeline from pyspark.ml.feature import Tokenizer, StopWordsRemover, HashingTF from pyspark.ml.classification import LogisticRegression from p...
consumerTrump.py
import re, csv, string from pyspark import SparkConf, SparkContext from pyspark.sql import Row, SparkSession from pyspark.sql.functions import rand from pyspark.ml import Pipeline from pyspark.ml.feature import Tokenizer, StopWordsRemover, HashingTF from pyspark.ml.classification import LogisticRegression from p...
0.369884
0.190988
import requests import urllib3 import os from helper import bytes32 import time from config import debug urllib3.disable_warnings() class FullNodeClient(): def __init__(self, ssl_directory, host, port, logfile=None): self.cert_path = os.path.join(ssl_directory, 'full_node/private_full_node.crt') self.key_path = ...
full_node_client.py
import requests import urllib3 import os from helper import bytes32 import time from config import debug urllib3.disable_warnings() class FullNodeClient(): def __init__(self, ssl_directory, host, port, logfile=None): self.cert_path = os.path.join(ssl_directory, 'full_node/private_full_node.crt') self.key_path = ...
0.168139
0.1532
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = [ 'GetLogAnalyticsObjectCollectionRulesResult', 'AwaitableGetLogAnalyticsObjectCollectionRulesResult', '...
sdk/python/pulumi_oci/loganalytics/get_log_analytics_object_collection_rules.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = [ 'GetLogAnalyticsObjectCollectionRulesResult', 'AwaitableGetLogAnalyticsObjectCollectionRulesResult', '...
0.801819
0.155015
from operator import itemgetter from collections import Counter from pygments import highlight from pygments.lexers import BashLexer from pygments.formatters import TerminalFormatter LEXER = BashLexer() FORMATTER = TerminalFormatter() class Command(object): def __init__(self, cmd, line, idx, doc): self...
searchcmd/commands.py
from operator import itemgetter from collections import Counter from pygments import highlight from pygments.lexers import BashLexer from pygments.formatters import TerminalFormatter LEXER = BashLexer() FORMATTER = TerminalFormatter() class Command(object): def __init__(self, cmd, line, idx, doc): self...
0.457864
0.160102
import pymysql from dbutils.pooled_db import PooledDB from pymysql.connections import Connection from pymysql.cursors import DictCursor class MySQL(object): def __init__(self, **kwargs): self._pool = None self._connection = None self.options = kwargs def pool(self) -> ...
ZtjMySQL.py
import pymysql from dbutils.pooled_db import PooledDB from pymysql.connections import Connection from pymysql.cursors import DictCursor class MySQL(object): def __init__(self, **kwargs): self._pool = None self._connection = None self.options = kwargs def pool(self) -> ...
0.391406
0.112942
import importlib import os import tensorflow as tf import random as rn import matplotlib.pyplot as plt import hickle as hkl import numpy as np import pdb import argparse import math import datetime import pytz from keras import backend as K from keras.models import Model, model_from_json from keras.layers import In...
CODES_prediction/double_prong_model/train_t_1.py
import importlib import os import tensorflow as tf import random as rn import matplotlib.pyplot as plt import hickle as hkl import numpy as np import pdb import argparse import math import datetime import pytz from keras import backend as K from keras.models import Model, model_from_json from keras.layers import In...
0.752286
0.290978
import argparse def default(docstring: str, interactions: bool = False, areas: bool = False, places: bool = False, add_places_id: bool = True, add_interaction_strength: bool = True, ): """Create a default argument parser with docstring as mai...
mobilib/argparser.py
import argparse def default(docstring: str, interactions: bool = False, areas: bool = False, places: bool = False, add_places_id: bool = True, add_interaction_strength: bool = True, ): """Create a default argument parser with docstring as mai...
0.614394
0.151969
from lib.solutions.CHK.services.calculate_total_checkout_value_service import CalculateTotalCheckoutValueService from lib.solutions.CHK.models.stock_keeping_unit import StockKeepUnit from lib.solutions.CHK.models.special_offer import SpecialOffer from lib.solutions.CHK.models.supermarket import SuperMarket class Test...
test/solution_tests/CHK/services/test_calculate_total_checkout_value_service.py
from lib.solutions.CHK.services.calculate_total_checkout_value_service import CalculateTotalCheckoutValueService from lib.solutions.CHK.models.stock_keeping_unit import StockKeepUnit from lib.solutions.CHK.models.special_offer import SpecialOffer from lib.solutions.CHK.models.supermarket import SuperMarket class Test...
0.823293
0.531453
from django.test import TestCase ,Client from django.http import HttpRequest from django.urls import reverse from django.contrib.auth.models import User from practise.models import Info,feed import datetime from basicapp.models import UserProfileInfo class ListView_Testing(TestCase): @classmethod def setUpTest...
searchBar/practise/tests.py
from django.test import TestCase ,Client from django.http import HttpRequest from django.urls import reverse from django.contrib.auth.models import User from practise.models import Info,feed import datetime from basicapp.models import UserProfileInfo class ListView_Testing(TestCase): @classmethod def setUpTest...
0.390243
0.147248
import weakref import pickle import functools _cached_funcs = [] def process_invalidate_cache(): for f in _cached_funcs: f.cache_clear() Flyweight._cache.clear() def invalidate_cache(): from soap import logger from soap.common.parallel import pool process_invalidate_cache() pool.in...
soap/common/cache.py
import weakref import pickle import functools _cached_funcs = [] def process_invalidate_cache(): for f in _cached_funcs: f.cache_clear() Flyweight._cache.clear() def invalidate_cache(): from soap import logger from soap.common.parallel import pool process_invalidate_cache() pool.in...
0.439988
0.164852
import time import json import math class pyfeval: ''' pyeval stands for python fast evaluator This is an engine to evaluate a mathematical expression fast. The expression is a string in a certain format. For example the expression ((1+2)-(6x7)>-20) | (3==4) should be translated to 'OR(GT(SUB(ADD(1,2)...
main.py
import time import json import math class pyfeval: ''' pyeval stands for python fast evaluator This is an engine to evaluate a mathematical expression fast. The expression is a string in a certain format. For example the expression ((1+2)-(6x7)>-20) | (3==4) should be translated to 'OR(GT(SUB(ADD(1,2)...
0.395718
0.468243
# Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form mu...
universal_analytics/tracker.py
# Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form mu...
0.719285
0.097864
import argparse import curses import time import sys sys.path.append("../Dependencies/PythonSharedBuffers/src") sys.path.append("../../../DistributedSharedMemory") from Navigation import * from Serialization import * import pydsm SERVERID = 254 CLIENTID = 100 outputs = Outputs() for i in range(8): outputs.motor...
src/Visualization/NavigationViewer.py
import argparse import curses import time import sys sys.path.append("../Dependencies/PythonSharedBuffers/src") sys.path.append("../../../DistributedSharedMemory") from Navigation import * from Serialization import * import pydsm SERVERID = 254 CLIENTID = 100 outputs = Outputs() for i in range(8): outputs.motor...
0.257018
0.12408
from uniback.dictionary.uniback_exceptions import JobQueueFullException from uniback.dictionary.uniback_constants import JobStatus, JobStatusMap from threading import Lock from collections import deque from uniback import process_manager class JobQueue: _job_list = deque() # we implement thread locking so th...
uniback/tools/job_tools.py
from uniback.dictionary.uniback_exceptions import JobQueueFullException from uniback.dictionary.uniback_constants import JobStatus, JobStatusMap from threading import Lock from collections import deque from uniback import process_manager class JobQueue: _job_list = deque() # we implement thread locking so th...
0.670716
0.253948
# pylint: disable=no-self-use from typing import Any, Dict, Literal, Optional from optimade.models import Response from oteapi.models import ResourceConfig, SessionUpdate from pydantic import Field from oteapi_optimade.models.config import OPTIMADEConfig from oteapi_optimade.models.custom_types import OPTIMADEUrl c...
oteapi_optimade/models/strategies/parse.py
# pylint: disable=no-self-use from typing import Any, Dict, Literal, Optional from optimade.models import Response from oteapi.models import ResourceConfig, SessionUpdate from pydantic import Field from oteapi_optimade.models.config import OPTIMADEConfig from oteapi_optimade.models.custom_types import OPTIMADEUrl c...
0.77768
0.059894
from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('contact', '0004_auto_20201102_1951'), ('product', '0022_auto_20210424_0940'), ('invoice', '0001_initial'), ...
purchase/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('contact', '0004_auto_20201102_1951'), ('product', '0022_auto_20210424_0940'), ('invoice', '0001_initial'), ...
0.548432
0.145722
import numpy as np def numpy_solution(Xdata, ydata): # half examples for training Xtrain, ytrain = Xdata[::2], ydata[::2] # half examples for validation Xvalid, yvalid = Xdata[1::2], ydata[1::2] # closed-form solution to minimize cost (loss) function # min(cost) = inverse(XT*X) * (XT*y) ...
LinearRegression.py
import numpy as np def numpy_solution(Xdata, ydata): # half examples for training Xtrain, ytrain = Xdata[::2], ydata[::2] # half examples for validation Xvalid, yvalid = Xdata[1::2], ydata[1::2] # closed-form solution to minimize cost (loss) function # min(cost) = inverse(XT*X) * (XT*y) ...
0.67662
0.718125
from __future__ import annotations import argparse import json import os import sys import awkward as ak import numpy as np import uproot import shml def initial(writeout_dir: str, filepath: str, cut_type: str) -> ak.Array: print(f"running preprocessing with {cut_type} preselection") filenames = list(filte...
examples/run_preprocessing.py
from __future__ import annotations import argparse import json import os import sys import awkward as ak import numpy as np import uproot import shml def initial(writeout_dir: str, filepath: str, cut_type: str) -> ak.Array: print(f"running preprocessing with {cut_type} preselection") filenames = list(filte...
0.38549
0.173884
import pickle import numpy as np def load_pickle(pickle_file): try: with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f) except UnicodeDecodeError as e: with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f, encoding='latin1') except Exception as...
utils.py
import pickle import numpy as np def load_pickle(pickle_file): try: with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f) except UnicodeDecodeError as e: with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f, encoding='latin1') except Exception as...
0.342791
0.226741
import psycopg2, psycopg2.extras import os import configparser import random def ceiling_fox_post(): data = [] with open((os.path.join(os.path.dirname(__file__), 'blobfox')), 'r', encoding='utf-8') as emojilist: data = emojilist.read().splitlines() random.seed() zahl = random.randint(0, len(da...
ceilingfox.py
import psycopg2, psycopg2.extras import os import configparser import random def ceiling_fox_post(): data = [] with open((os.path.join(os.path.dirname(__file__), 'blobfox')), 'r', encoding='utf-8') as emojilist: data = emojilist.read().splitlines() random.seed() zahl = random.randint(0, len(da...
0.21917
0.119126
from .Handlers import handlemsg, handlemsg_all, clientid_to_myself import ba, _ba Commands = ['kill', 'heal', 'curse', 'sleep', 'superpunch', 'gloves', 'shield', 'freeze', 'unfreeze', 'godmode'] CommandAliases = ['die', 'heath', 'cur', 'sp', 'punch', 'protect', 'ice', 'thaw', 'gm'] def ExcelCommand(command, arg...
dist/ba_root/mods/chatHandle/ChatCommands/commands/Cheats.py
from .Handlers import handlemsg, handlemsg_all, clientid_to_myself import ba, _ba Commands = ['kill', 'heal', 'curse', 'sleep', 'superpunch', 'gloves', 'shield', 'freeze', 'unfreeze', 'godmode'] CommandAliases = ['die', 'heath', 'cur', 'sp', 'punch', 'protect', 'ice', 'thaw', 'gm'] def ExcelCommand(command, arg...
0.107379
0.181046
import matplotlib.pyplot as plt def single_loc_plot(): """Plot results for single location model.""" mfdgps = [0.600, 0.537, 0.371, 0.322] ml_benchs = [0.118, 0.117, -0.051, -0.118] env_benchs = [0.586, 0.439, -0.076] x_mfdgp = [0., 0.2, 0.4, 0.6] x_ml = [1., 1.2, 1.4, 1.6] x_env = [2., 2...
analysis/barplot.py
import matplotlib.pyplot as plt def single_loc_plot(): """Plot results for single location model.""" mfdgps = [0.600, 0.537, 0.371, 0.322] ml_benchs = [0.118, 0.117, -0.051, -0.118] env_benchs = [0.586, 0.439, -0.076] x_mfdgp = [0., 0.2, 0.4, 0.6] x_ml = [1., 1.2, 1.4, 1.6] x_env = [2., 2...
0.704262
0.693038
import numpy as np from optparse import OptionParser # get the command line arguments parser = OptionParser(description="python script to create pvalue and log2(foldchange) filtered ") parser.add_option('-i', '--input_file', type=str, default="results/plotSelection.txt...
scripts/filterForPlots.py
import numpy as np from optparse import OptionParser # get the command line arguments parser = OptionParser(description="python script to create pvalue and log2(foldchange) filtered ") parser.add_option('-i', '--input_file', type=str, default="results/plotSelection.txt...
0.244093
0.211112
import numbers import os import warnings import numpy as np import cv2 import random import math from train_config import config as cfg ######May wrong, when use it check it def Rotate_aug(src,angle,label=None,center=None,scale=1.0): ''' :param src: src image :param label: label should be nu...
lib/dataset/augmentor/augmentation.py
import numbers import os import warnings import numpy as np import cv2 import random import math from train_config import config as cfg ######May wrong, when use it check it def Rotate_aug(src,angle,label=None,center=None,scale=1.0): ''' :param src: src image :param label: label should be nu...
0.337422
0.314379
import datetime import math import matplotlib.pyplot as plt class Reporter(object): def __init__(self, name): self.name = name self.plots = [] def flushes_per_txg(self, x_txgs, y): fig, ax = plt.subplots() ax.set_ylabel('# of flushes', color='r') ax.set_ylim(0, max(y) +...
Reporter.py
import datetime import math import matplotlib.pyplot as plt class Reporter(object): def __init__(self, name): self.name = name self.plots = [] def flushes_per_txg(self, x_txgs, y): fig, ax = plt.subplots() ax.set_ylabel('# of flushes', color='r') ax.set_ylim(0, max(y) +...
0.39222
0.306138
from sys_simulator.channels import BANChannel from sys_simulator import general as gen from sys_simulator.q_learning.environments.completeEnvironment5 \ import CompleteEnvironment5 from sys_simulator.dqn.agents.dqnAgent import ExternalDQNAgent from sys_simulator.dqn.externalDQNFramework import ExternalDQNFramework ...
scripts_dql/script31.py
from sys_simulator.channels import BANChannel from sys_simulator import general as gen from sys_simulator.q_learning.environments.completeEnvironment5 \ import CompleteEnvironment5 from sys_simulator.dqn.agents.dqnAgent import ExternalDQNAgent from sys_simulator.dqn.externalDQNFramework import ExternalDQNFramework ...
0.374791
0.406037
import mock from novaclient.v2 import client as nova_client from oslotest import mockpatch from cloudferry.lib.os.compute import nova_compute from cloudferry.lib.utils import utils from tests import test FAKE_CONFIG = { 'src': {'user': 'fake_user', 'password': '<PASSWORD>', 'tenant': '...
tests/lib/os/compute/test_nova.py
import mock from novaclient.v2 import client as nova_client from oslotest import mockpatch from cloudferry.lib.os.compute import nova_compute from cloudferry.lib.utils import utils from tests import test FAKE_CONFIG = { 'src': {'user': 'fake_user', 'password': '<PASSWORD>', 'tenant': '...
0.548915
0.087759
class YouTubeRequest: """ YouTubeRequest is a data class for making YouTube API calls. """ def __init__(self): """ Initializes all members (except safe_search) as None. safe_search is initialized to strict because otherwise you get some 'interesting' results by default... ""...
videolocale/youtube_request.py
class YouTubeRequest: """ YouTubeRequest is a data class for making YouTube API calls. """ def __init__(self): """ Initializes all members (except safe_search) as None. safe_search is initialized to strict because otherwise you get some 'interesting' results by default... ""...
0.666605
0.376852
import vibrance PALETTE = ( "000000", # black "FFFFFF", # white "FF0000", # red "00FF00", # green "0000FF", # blue "FFFF00", # yellow "00FFFF", # cyan "FF00FF", # magenta "FF8000", # orange "8000FF", # purple "0080FF", # light blue "FF0080", # pink ) color =...
examples/everything/scripts/keypad_simple.py
import vibrance PALETTE = ( "000000", # black "FFFFFF", # white "FF0000", # red "00FF00", # green "0000FF", # blue "FFFF00", # yellow "00FFFF", # cyan "FF00FF", # magenta "FF8000", # orange "8000FF", # purple "0080FF", # light blue "FF0080", # pink ) color =...
0.310276
0.314024
from typing import List, Optional, Set from numpy import ndarray from livia.process.analyzer.object_detection.DetectedObject import DetectedObject class FrameObjectDetection: def __init__(self, frame: ndarray, objects: List[DetectedObject], class_names: Optional[Set[str]] = None): self.__frame: ndarray ...
livia/process/analyzer/object_detection/FrameObjectDetection.py
from typing import List, Optional, Set from numpy import ndarray from livia.process.analyzer.object_detection.DetectedObject import DetectedObject class FrameObjectDetection: def __init__(self, frame: ndarray, objects: List[DetectedObject], class_names: Optional[Set[str]] = None): self.__frame: ndarray ...
0.901415
0.400222
import datetime import logging from typing import List, Tuple from climsoft_api.api.form_agro1 import schema as form_agro1_schema from climsoft_api.utils.query import get_count from fastapi.exceptions import HTTPException from opencdms.models.climsoft import v4_1_1_core as models from sqlalchemy.orm.session import Sess...
src/climsoft_api/services/form_agro1_service.py
import datetime import logging from typing import List, Tuple from climsoft_api.api.form_agro1 import schema as form_agro1_schema from climsoft_api.utils.query import get_count from fastapi.exceptions import HTTPException from opencdms.models.climsoft import v4_1_1_core as models from sqlalchemy.orm.session import Sess...
0.588416
0.082143
import unittest from whoosh import analysis, fields from whoosh.filedb.filestore import RamStorage from whoosh.filedb.filewriting import NO_MERGE class TestReading(unittest.TestCase): def _create_index(self): s = fields.Schema(f1 = fields.KEYWORD(stored = True), f2 = fields.KEYWO...
tests/test_reading.py
import unittest from whoosh import analysis, fields from whoosh.filedb.filestore import RamStorage from whoosh.filedb.filewriting import NO_MERGE class TestReading(unittest.TestCase): def _create_index(self): s = fields.Schema(f1 = fields.KEYWORD(stored = True), f2 = fields.KEYWO...
0.439266
0.299912
from abc import ABC, abstractmethod from typing import Callable, Dict, Generic, List, Iterable, TypeVar from .connection import Connection from ..errors import NotFound from ..models.user import User from ..models.guild import Guild from ..typings import Snowflake from ..typings.payloads import PartialUserPayload, ...
wumpus/core/manager.py
from abc import ABC, abstractmethod from typing import Callable, Dict, Generic, List, Iterable, TypeVar from .connection import Connection from ..errors import NotFound from ..models.user import User from ..models.guild import Guild from ..typings import Snowflake from ..typings.payloads import PartialUserPayload, ...
0.914927
0.247407
import tensorflow.keras.backend as K import tensorflow as tf import numpy as np # alpha = 1, beta = 0.03, margin = {0.5, 1, 2, 4, 8} class modals(tf.keras.Model): def make_feature_extractor(self, layers, input_dim, hidden_size): inputs = tf.keras.Input(shape=(None, input_dim)) x = inputs f...
source/modals.py
import tensorflow.keras.backend as K import tensorflow as tf import numpy as np # alpha = 1, beta = 0.03, margin = {0.5, 1, 2, 4, 8} class modals(tf.keras.Model): def make_feature_extractor(self, layers, input_dim, hidden_size): inputs = tf.keras.Input(shape=(None, input_dim)) x = inputs f...
0.542621
0.504028
from datetime import date from functools import partial from os import remove from os.path import exists import matplotlib.pyplot as plt from kivy.app import App from kivy.core.window import Window from kivy.uix.behaviors import ToggleButtonBehavior from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import ...
main.py
from datetime import date from functools import partial from os import remove from os.path import exists import matplotlib.pyplot as plt from kivy.app import App from kivy.core.window import Window from kivy.uix.behaviors import ToggleButtonBehavior from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import ...
0.50293
0.09709
import logging import numpy as np from mlagents.trainers import UnityException from mlagents.trainers.models import LearningModel logger = logging.getLogger("mlagents.trainers") class UnityPolicyException(UnityException): """ Related to errors with the Trainer. """ pass class Policy(object): "...
ml-agents/mlagents/trainers/policy.py
import logging import numpy as np from mlagents.trainers import UnityException from mlagents.trainers.models import LearningModel logger = logging.getLogger("mlagents.trainers") class UnityPolicyException(UnityException): """ Related to errors with the Trainer. """ pass class Policy(object): "...
0.8709
0.408778
import smbus import time MCP23017_IODIRA = 0x00 MCP23017_IPOLA = 0x02 MCP23017_GPINTENA = 0x04 MCP23017_DEFVALA = 0x06 MCP23017_INTCONA = 0x08 MCP23017_IOCONA = 0x0A MCP23017_GPPUA = 0x0C MCP23017_INTFA = 0x0E MCP23017_INTCAPA = 0x10 MCP23017_GPIOA = 0x12 MCP23017_OLATA = 0x14 MCP23017_IODIRB = 0x01 MCP23017_IPOLB =...
PiPyRelayProp/waveshare-expander/MCP23017-Raspberry-PI-Python-Library/mcp23017 input ouput demo.py
import smbus import time MCP23017_IODIRA = 0x00 MCP23017_IPOLA = 0x02 MCP23017_GPINTENA = 0x04 MCP23017_DEFVALA = 0x06 MCP23017_INTCONA = 0x08 MCP23017_IOCONA = 0x0A MCP23017_GPPUA = 0x0C MCP23017_INTFA = 0x0E MCP23017_INTCAPA = 0x10 MCP23017_GPIOA = 0x12 MCP23017_OLATA = 0x14 MCP23017_IODIRB = 0x01 MCP23017_IPOLB =...
0.088936
0.234977
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='FrontPage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize...
frontpage/migrations/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='FrontPage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize...
0.433382
0.187542
import pytest from subnet import ip_network, IPv4Network, IPv4Address from wireguard import ( INTERFACE, PORT, Config, ServerConfig, Peer, Server, ) from wireguard.utils import generate_key, public_key def test_basic_server(): subnet = '192.168.0.0/24' address = '192.168.0.1' se...
tests/test_server.py
import pytest from subnet import ip_network, IPv4Network, IPv4Address from wireguard import ( INTERFACE, PORT, Config, ServerConfig, Peer, Server, ) from wireguard.utils import generate_key, public_key def test_basic_server(): subnet = '192.168.0.0/24' address = '192.168.0.1' se...
0.696165
0.387864
import boto3 import os from botocore.exceptions import ClientError def get_stack_outputs(): """ Gets asetuapi stack outputs if it exists """ cfn = boto3.client("cloudformation") try: asetuapi_stack = cfn.describe_stacks(StackName="asetuapi") except ClientError: print( ...
generate_exports_and_bundle.py
import boto3 import os from botocore.exceptions import ClientError def get_stack_outputs(): """ Gets asetuapi stack outputs if it exists """ cfn = boto3.client("cloudformation") try: asetuapi_stack = cfn.describe_stacks(StackName="asetuapi") except ClientError: print( ...
0.34798
0.16398
import maya.cmds as mc # globel attributes srcObjSel=[] trgObjSel=[] srcCmpList=[] trgCmpList=[] srcTrList=[] trgTrList=[] srcGrp=[] trgGrp=[] actLayerList = [] currentLayer = [] sourceObj = [] targetObjs = [] sourceShape = [] targetShapes = [] srcPreText=[""] srcSufText=[""] trgPreText=[""] trgSufText=[""] allLaye...
matchRenderLayers.py
import maya.cmds as mc # globel attributes srcObjSel=[] trgObjSel=[] srcCmpList=[] trgCmpList=[] srcTrList=[] trgTrList=[] srcGrp=[] trgGrp=[] actLayerList = [] currentLayer = [] sourceObj = [] targetObjs = [] sourceShape = [] targetShapes = [] srcPreText=[""] srcSufText=[""] trgPreText=[""] trgSufText=[""] allLaye...
0.177063
0.133981
from itertools import chain import numpy as np from openmdao.core.implicitcomponent import ImplicitComponent from openmdao.core.constants import INT_DTYPE import openmdao.func_api as omf from openmdao.components.func_comp_common import _check_var_name, _copy_with_ignore, _add_options, \ jac_forward, jac_reverse, _...
openmdao/components/implicit_func_comp.py
from itertools import chain import numpy as np from openmdao.core.implicitcomponent import ImplicitComponent from openmdao.core.constants import INT_DTYPE import openmdao.func_api as omf from openmdao.components.func_comp_common import _check_var_name, _copy_with_ignore, _add_options, \ jac_forward, jac_reverse, _...
0.80213
0.454714
import os, shutil from classes.asar import Asar class BaseUtils: def prompt_for(self, message, valid_responses=None, default_response='', response_case_sensitive=False): if valid_responses is None: valid_responses = [] message = self.process_input_message(message, valid_respons...
classes/utils.py
import os, shutil from classes.asar import Asar class BaseUtils: def prompt_for(self, message, valid_responses=None, default_response='', response_case_sensitive=False): if valid_responses is None: valid_responses = [] message = self.process_input_message(message, valid_respons...
0.240329
0.078819
import logging import math import os from abc import abstractmethod, ABC from typing import Sequence, Tuple, List, Union import numpy as np import pandas as pd from .util import cache from .util.cache import DelayedUpdateHook from .util.string import objectRepr from .util.typing import PandasNamedTuple log = loggin...
src/sensai/distance_metric.py
import logging import math import os from abc import abstractmethod, ABC from typing import Sequence, Tuple, List, Union import numpy as np import pandas as pd from .util import cache from .util.cache import DelayedUpdateHook from .util.string import objectRepr from .util.typing import PandasNamedTuple log = loggin...
0.887302
0.367327
import logging import voluptuous as vol import traceback from homeassistant import config_entries from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_create_clientsession from .api import BWTPerlaApi from .const import ( CONF_CODE, CONF_HOST, CONF_SYNC_INTERVAL,...
custom_components/bwt_perla/config_flow.py
import logging import voluptuous as vol import traceback from homeassistant import config_entries from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_create_clientsession from .api import BWTPerlaApi from .const import ( CONF_CODE, CONF_HOST, CONF_SYNC_INTERVAL,...
0.395484
0.079639
import os import cv2 import numpy as np import pandas as pd import skimage.io import torch from torch.utils.data import Dataset class SpacenetLocDataset(Dataset): def __init__(self, data_path, mode, fold=0, folds_csv='folds.csv', transforms=None, normalize=None, multiplier=1, fix_orientation=Tru...
5-selim_sef/spacenet_dataset.py
import os import cv2 import numpy as np import pandas as pd import skimage.io import torch from torch.utils.data import Dataset class SpacenetLocDataset(Dataset): def __init__(self, data_path, mode, fold=0, folds_csv='folds.csv', transforms=None, normalize=None, multiplier=1, fix_orientation=Tru...
0.627951
0.200577
import numpy as np from magenpy.simulation import GWASSimulator class AnnotatedGWASSimulator(GWASSimulator): def __init__(self, bed_files, **kwargs): super().__init__(bed_files, **kwargs) # For now, we will restrict to 2 mixture components. assert self.n_mixtures == 2 self.w_h2 ...
magenpy/simulation/AnnotatedGWASSimulator.py
import numpy as np from magenpy.simulation import GWASSimulator class AnnotatedGWASSimulator(GWASSimulator): def __init__(self, bed_files, **kwargs): super().__init__(bed_files, **kwargs) # For now, we will restrict to 2 mixture components. assert self.n_mixtures == 2 self.w_h2 ...
0.586404
0.572783
import os import datetime # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY W...
rss_temple/rss_temple/settings.py
import os import datetime # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY W...
0.307462
0.098339
from symbol import parameters __author__ = "<NAME>" import re import logging logging.basicConfig(level=logging.INFO) LOG = logging.getLogger(__name__) class ParameterCollector: def __init__(self, config): self.config = config def _translate_parameters_to_oversim(self, parameters): transl...
configurator/configurator/ParamCollector.py
from symbol import parameters __author__ = "<NAME>" import re import logging logging.basicConfig(level=logging.INFO) LOG = logging.getLogger(__name__) class ParameterCollector: def __init__(self, config): self.config = config def _translate_parameters_to_oversim(self, parameters): transl...
0.298185
0.269308
from django.test import TestCase from ..models import ( Project, ProjectGroup, ) class ProjectTest(TestCase): def setUp(self): self.project_group = ProjectGroup.objects.create( name='Pronto World', slug='pronto-world', description='Pronto World Group' )...
rocket/projects/tests/test_models.py
from django.test import TestCase from ..models import ( Project, ProjectGroup, ) class ProjectTest(TestCase): def setUp(self): self.project_group = ProjectGroup.objects.create( name='Pronto World', slug='pronto-world', description='Pronto World Group' )...
0.521715
0.405331