code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import os import numpy as np class Graph: def __init__(self, filename, mem_mode='lst', weighted=False, directed=False): # Verificando se o nome do arquivo passado eh uma string if (type(filename) != type('')): raise TypeError('Graph expects a string with the path to the text file that ...
guara/graph.py
import os import numpy as np class Graph: def __init__(self, filename, mem_mode='lst', weighted=False, directed=False): # Verificando se o nome do arquivo passado eh uma string if (type(filename) != type('')): raise TypeError('Graph expects a string with the path to the text file that ...
0.422505
0.409811
from byteplay import Code from byteplay import LOAD_FAST from byteplay import LOAD_ATTR from byteplay import LOAD_CONST from byteplay import BINARY_SUBSCR from byteplay import STORE_FAST import inspect _ANY_VALUE = object() class _MatchingTuple(tuple): def __eq__(self, other): for s, o in zip(self, ot...
pydenji/userproperties/codescraper.py
from byteplay import Code from byteplay import LOAD_FAST from byteplay import LOAD_ATTR from byteplay import LOAD_CONST from byteplay import BINARY_SUBSCR from byteplay import STORE_FAST import inspect _ANY_VALUE = object() class _MatchingTuple(tuple): def __eq__(self, other): for s, o in zip(self, ot...
0.374219
0.111386
from pygears import alternative, TypeMatchError, gear from pygears.typing import Union from pygears.lib import fmap as common_fmap from pygears.lib.mux import mux from pygears.lib.demux import demux_ctrl from pygears.lib.ccat import ccat from pygears.lib.shred import shred def unionmap_check(dtype, f, mapping): i...
pygears/lib/fmaps/union.py
from pygears import alternative, TypeMatchError, gear from pygears.typing import Union from pygears.lib import fmap as common_fmap from pygears.lib.mux import mux from pygears.lib.demux import demux_ctrl from pygears.lib.ccat import ccat from pygears.lib.shred import shred def unionmap_check(dtype, f, mapping): i...
0.493409
0.459925
import datetime from toolium.utils.dataset import replace_param def test_replace_param_no_string(): param = replace_param(1234) assert param == 1234 def test_replace_param_no_pattern(): param = replace_param('my param') assert param == 'my param' def test_replace_param_incomplete_pattern(): p...
toolium/test/utils/test_dataset_replace_param.py
import datetime from toolium.utils.dataset import replace_param def test_replace_param_no_string(): param = replace_param(1234) assert param == 1234 def test_replace_param_no_pattern(): param = replace_param('my param') assert param == 'my param' def test_replace_param_incomplete_pattern(): p...
0.445771
0.480113
from maclookup import * from maclookup.models import * from maclookup.exceptions import EmptyResponseException from .mock_requester import MockRequester import unittest from dateutil.parser import parse class ApiClientTest(unittest.TestCase): def setUp(self): pass def test_parsing(self): pay...
tests/api_client_test.py
from maclookup import * from maclookup.models import * from maclookup.exceptions import EmptyResponseException from .mock_requester import MockRequester import unittest from dateutil.parser import parse class ApiClientTest(unittest.TestCase): def setUp(self): pass def test_parsing(self): pay...
0.59843
0.191649
import pandas as pd import csv from sklearn import neighbors from sklearn import datasets import numpy as np import yellowbrick as yb from yellowbrick.neighbors import KnnDecisionBoundariesVisualizer import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def load_adm_sat_school_data(return_X_y=F...
examples/balavenkatesan/testing.py
import pandas as pd import csv from sklearn import neighbors from sklearn import datasets import numpy as np import yellowbrick as yb from yellowbrick.neighbors import KnnDecisionBoundariesVisualizer import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap def load_adm_sat_school_data(return_X_y=F...
0.693473
0.506652
from __future__ import absolute_import, division, print_function, unicode_literals import logging import unittest import tensorflow as tf import numpy as np from art.attacks import UniversalPerturbation from art.classifiers import KerasClassifier from art.utils import load_dataset, master_seed from art.utils_test im...
tests/attacks/test_universal_perturbation.py
from __future__ import absolute_import, division, print_function, unicode_literals import logging import unittest import tensorflow as tf import numpy as np from art.attacks import UniversalPerturbation from art.classifiers import KerasClassifier from art.utils import load_dataset, master_seed from art.utils_test im...
0.856077
0.640889
import sys import types import collections import io from opcode import * from opcode import __all__ as _opcodes_all __all__ = ["code_info", "dis", "disassemble", "distb", "disco", "findlinestarts", "findlabels", "show_code", "get_instructions", "Instruction", "Bytecode"] + _opcodes_all del _op...
contrib/tools/python3/src/Lib/dis.py
import sys import types import collections import io from opcode import * from opcode import __all__ as _opcodes_all __all__ = ["code_info", "dis", "disassemble", "distb", "disco", "findlinestarts", "findlabels", "show_code", "get_instructions", "Instruction", "Bytecode"] + _opcodes_all del _op...
0.364099
0.186095
import numpy as np from ... import opcodes from ...config import options from ...core import OutputType, ENTITY_TYPE from ...serialization.serializables import BoolField from .core import DataFrameReductionOperand, DataFrameReductionMixin class DataFrameSkew(DataFrameReductionOperand, DataFrameReductionMixin): ...
mars/dataframe/reduction/skew.py
import numpy as np from ... import opcodes from ...config import options from ...core import OutputType, ENTITY_TYPE from ...serialization.serializables import BoolField from .core import DataFrameReductionOperand, DataFrameReductionMixin class DataFrameSkew(DataFrameReductionOperand, DataFrameReductionMixin): ...
0.760384
0.379637
import pytest from investpy import get_stock_historical_data import trendet def test_errors(): """ This function raises trendet errors to improve coverage """ params = [ { 'stock': ['error'], 'country': 'Spain', 'from_date': '01/01/2018', 'to...
tests/test_trendet_errors.py
import pytest from investpy import get_stock_historical_data import trendet def test_errors(): """ This function raises trendet errors to improve coverage """ params = [ { 'stock': ['error'], 'country': 'Spain', 'from_date': '01/01/2018', 'to...
0.361503
0.278665
import copy import chainer from chainer import reporter from chainercv.evaluations import eval_semantic_segmentation from chainercv.utils import apply_to_iterator import pandas import six import tqdm from instance_occlsegm_lib.contrib.synthetic2d.evaluations import \ eval_instseg_voc from ..evaluations import ev...
demos/instance_occlsegm/instance_occlsegm_lib/contrib/instance_occlsegm/extensions/panoptic_segmentation_voc_evaluator.py
import copy import chainer from chainer import reporter from chainercv.evaluations import eval_semantic_segmentation from chainercv.utils import apply_to_iterator import pandas import six import tqdm from instance_occlsegm_lib.contrib.synthetic2d.evaluations import \ eval_instseg_voc from ..evaluations import ev...
0.506591
0.215908
import unittest import collections import dimod from dwave.system.composites import VirtualGraphComposite from dwave.system.testing import MockDWaveSampler class TestVirtualGraphWithMockDWaveSampler(unittest.TestCase): def setUp(self): self.sampler = MockDWaveSampler() def test_smoke(self): ...
tests/test_virtual_graph_composite.py
import unittest import collections import dimod from dwave.system.composites import VirtualGraphComposite from dwave.system.testing import MockDWaveSampler class TestVirtualGraphWithMockDWaveSampler(unittest.TestCase): def setUp(self): self.sampler = MockDWaveSampler() def test_smoke(self): ...
0.75101
0.521349
import torch from torch.utils.data.sampler import Sampler def uxxxx_to_utf8(in_str): idx = 0 result = "" if in_str.strip() == "": return "" for uxxxx in in_str.split(): if uxxxx == "": continue if uxxxx == "<unk>" or uxxxx == "<s>" or uxxxx == "</s>": ...
fairseq/data/datautils.py
import torch from torch.utils.data.sampler import Sampler def uxxxx_to_utf8(in_str): idx = 0 result = "" if in_str.strip() == "": return "" for uxxxx in in_str.split(): if uxxxx == "": continue if uxxxx == "<unk>" or uxxxx == "<s>" or uxxxx == "</s>": ...
0.359926
0.32344
import collections import testtools from neutron.db import api as db from neutron.plugins.ml2.drivers.cisco import exceptions from neutron.plugins.ml2.drivers.cisco import nexus_db_v2 from neutron.tests import base class CiscoNexusDbTest(base.BaseTestCase): """Unit tests for Cisco mechanism driver's Nexus port...
neutron/tests/unit/ml2/drivers/test_cisco_nexus_db.py
import collections import testtools from neutron.db import api as db from neutron.plugins.ml2.drivers.cisco import exceptions from neutron.plugins.ml2.drivers.cisco import nexus_db_v2 from neutron.tests import base class CiscoNexusDbTest(base.BaseTestCase): """Unit tests for Cisco mechanism driver's Nexus port...
0.802865
0.351367
import argparse import chainer from chainer import iterators from chainercv.datasets import coco_bbox_label_names from chainercv.datasets import COCOBboxDataset from chainercv.evaluations import eval_detection_coco from chainercv.utils import apply_to_iterator from chainercv.utils import ProgressHook from light_head_...
examples/eval_coco.py
import argparse import chainer from chainer import iterators from chainercv.datasets import coco_bbox_label_names from chainercv.datasets import COCOBboxDataset from chainercv.evaluations import eval_detection_coco from chainercv.utils import apply_to_iterator from chainercv.utils import ProgressHook from light_head_...
0.499512
0.225768
import argparse import math import torch.nn as nn import torch import torch.nn.functional as F from torchvision import datasets, transforms from models import BayesNet def train(args, model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): ...
bayes-by-backprop/train.py
import argparse import math import torch.nn as nn import torch import torch.nn.functional as F from torchvision import datasets, transforms from models import BayesNet def train(args, model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): ...
0.848345
0.497376
import binascii import json import os import os.path from typing import Callable, Dict, Optional import requests from oauthlib.oauth2 import TokenExpiredError from requests_oauthlib import OAuth2Session from .exceptions import NeatoException, NeatoLoginException, NeatoRobotException from .neato import Neato, Vendor f...
pybotvac/session.py
import binascii import json import os import os.path from typing import Callable, Dict, Optional import requests from oauthlib.oauth2 import TokenExpiredError from requests_oauthlib import OAuth2Session from .exceptions import NeatoException, NeatoLoginException, NeatoRobotException from .neato import Neato, Vendor f...
0.785226
0.093844
import os from neptune.utils import validate_notebook_path class Notebook(object): """It contains all the information about a Neptune Notebook Args: backend (:class:`~neptune.ApiClient`): A ApiClient object project (:class:`~neptune.projects.Project`): Project object ...
neptune/notebook.py
import os from neptune.utils import validate_notebook_path class Notebook(object): """It contains all the information about a Neptune Notebook Args: backend (:class:`~neptune.ApiClient`): A ApiClient object project (:class:`~neptune.projects.Project`): Project object ...
0.761006
0.251396
import io import os from functools import lru_cache from lark.exceptions import UnexpectedInput, UnexpectedToken from .compiler import Compiler from .compiler.lowering import Lowering from .exceptions import CompilerError, StoryError, StorySyntaxError from .parser import Parser @lru_cache(maxsize=1) def _parser():...
storyscript/Story.py
import io import os from functools import lru_cache from lark.exceptions import UnexpectedInput, UnexpectedToken from .compiler import Compiler from .compiler.lowering import Lowering from .exceptions import CompilerError, StoryError, StorySyntaxError from .parser import Parser @lru_cache(maxsize=1) def _parser():...
0.589007
0.227748
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import re from six import string_types from spdx import annotation from spdx import checksum from spdx import creationinfo from spdx import document from spdx import file from spdx import package fro...
spdx/parsers/tagvaluebuilders.py
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import re from six import string_types from spdx import annotation from spdx import checksum from spdx import creationinfo from spdx import document from spdx import file from spdx import package fro...
0.464173
0.111895
from bottle import route, run from phue import Bridge import os, configparser, logging, logging.config, threading, time def writeDefaultConfig(): logger.debug('No config found. Writing default config to server.cfg. Please adapt accordingly and restart the server.') config = configparser.ConfigParser() config...
server.py
from bottle import route, run from phue import Bridge import os, configparser, logging, logging.config, threading, time def writeDefaultConfig(): logger.debug('No config found. Writing default config to server.cfg. Please adapt accordingly and restart the server.') config = configparser.ConfigParser() config...
0.193414
0.04056
import click from escpostools.aliases import resolve_alias from escpostools.cli import pass_context LONG_RULER = '....:....|' * 8 SHORT_RULER = '....:....|' * 4 @click.command('test', short_help='Runs tests against implementations.') @click.argument('aliases', type=click.STRING) @click.option('--all', is_flag=Tru...
escpostools/commands/cmd_test.py
import click from escpostools.aliases import resolve_alias from escpostools.cli import pass_context LONG_RULER = '....:....|' * 8 SHORT_RULER = '....:....|' * 4 @click.command('test', short_help='Runs tests against implementations.') @click.argument('aliases', type=click.STRING) @click.option('--all', is_flag=Tru...
0.749454
0.181173
from numpy import power,min,max,floor import tensorflow as tf from tensorflow.keras import Model, Sequential, optimizers, losses from tensorflow.keras.layers import Dense, GRU, Input, Masking, LSTM from tensorflow.keras.callbacks import LearningRateScheduler tf.keras.backend.set_floatx('float64') ''' Learning rate ad...
earshot/model.py
from numpy import power,min,max,floor import tensorflow as tf from tensorflow.keras import Model, Sequential, optimizers, losses from tensorflow.keras.layers import Dense, GRU, Input, Masking, LSTM from tensorflow.keras.callbacks import LearningRateScheduler tf.keras.backend.set_floatx('float64') ''' Learning rate ad...
0.833392
0.560614
WIDTH = sx = 854 HEIGHT = sy = 480 TITLE = "Clooky Clunker" score, totalscore, clunkers = 0, 0, 0 nextgoal = 0 tgoal = -100 clunks = [] tbuy, buytext = -100, "" t = 0 buttonrects = [Rect((50, 120 + 85 * j, 180, 70)) for j in range(4)] buttonnames = ["auto-clunker", "clunkutron", "turbo enclunkulator", "clunx capacit...
basic/clooky_clunker.py
WIDTH = sx = 854 HEIGHT = sy = 480 TITLE = "Clooky Clunker" score, totalscore, clunkers = 0, 0, 0 nextgoal = 0 tgoal = -100 clunks = [] tbuy, buytext = -100, "" t = 0 buttonrects = [Rect((50, 120 + 85 * j, 180, 70)) for j in range(4)] buttonnames = ["auto-clunker", "clunkutron", "turbo enclunkulator", "clunx capacit...
0.41739
0.197077
from wtforms.fields import IntegerField, SelectField from wtforms.validators import DataRequired, Length, NumberRange, Optional, ValidationError from indico.util.i18n import _, ngettext from indico.web.fields.base import BaseField from indico.web.forms.fields import IndicoRadioField, IndicoSelectMultipleCheckboxField...
indico/web/fields/choices.py
from wtforms.fields import IntegerField, SelectField from wtforms.validators import DataRequired, Length, NumberRange, Optional, ValidationError from indico.util.i18n import _, ngettext from indico.web.fields.base import BaseField from indico.web.forms.fields import IndicoRadioField, IndicoSelectMultipleCheckboxField...
0.826817
0.178562
import numpy as np from skmultiflow.trees.nodes import ActiveLearningNodePerceptronMultiTarget from skmultiflow.trees.attribute_observer import NumericAttributeRegressionObserverMultiTarget from skmultiflow.trees.attribute_observer import NominalAttributeRegressionObserver from skmultiflow.utils import get_dimensions ...
src/skmultiflow/trees/nodes/sst_active_learning_node.py
import numpy as np from skmultiflow.trees.nodes import ActiveLearningNodePerceptronMultiTarget from skmultiflow.trees.attribute_observer import NumericAttributeRegressionObserverMultiTarget from skmultiflow.trees.attribute_observer import NominalAttributeRegressionObserver from skmultiflow.utils import get_dimensions ...
0.896499
0.645511
import uuid import testtools from tempest.api.compute import base from tempest.common import tempest_fixtures as fixtures from tempest.common.utils import data_utils from tempest.common import waiters from tempest import config from tempest.lib import exceptions as lib_exc from tempest import test CONF = config.CON...
tempest/api/compute/admin/test_servers_negative.py
import uuid import testtools from tempest.api.compute import base from tempest.common import tempest_fixtures as fixtures from tempest.common.utils import data_utils from tempest.common import waiters from tempest import config from tempest.lib import exceptions as lib_exc from tempest import test CONF = config.CON...
0.359364
0.177543
from __future__ import unicode_literals import numbers import six from flex._compat import Sequence, Mapping SCHEMES = ( 'http', 'https', 'ws', 'wss', ) MIMETYPES = ( 'application/json', ) NULL = 'null' BOOLEAN = 'boolean' INTEGER = 'integer' NUMBER = 'number' STRING = 'string' ARRAY = 'array' OBJECT = ...
flex/constants.py
from __future__ import unicode_literals import numbers import six from flex._compat import Sequence, Mapping SCHEMES = ( 'http', 'https', 'ws', 'wss', ) MIMETYPES = ( 'application/json', ) NULL = 'null' BOOLEAN = 'boolean' INTEGER = 'integer' NUMBER = 'number' STRING = 'string' ARRAY = 'array' OBJECT = ...
0.572962
0.081593
import json import sys if sys.version_info[0] != 3: range = xrange # @ReservedAssignment @UndefinedVariable class VkTools(object): """ Содержит некоторые воспомогательные функции, которые могут понадобиться при использовании API """ __slots__ = ('vk',) def __init__(self, vk): "...
vk_api/vk_tools.py
import json import sys if sys.version_info[0] != 3: range = xrange # @ReservedAssignment @UndefinedVariable class VkTools(object): """ Содержит некоторые воспомогательные функции, которые могут понадобиться при использовании API """ __slots__ = ('vk',) def __init__(self, vk): "...
0.191252
0.467696
import datetime from typing import Dict, List, Optional, Union from azure.core.exceptions import HttpResponseError import msrest.serialization from ._monitor_query_client_enums import * class BatchQueryRequest(msrest.serialization.Model): """An single request in a batch. Variables are only populated by th...
sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/models/_models_py3.py
import datetime from typing import Dict, List, Optional, Union from azure.core.exceptions import HttpResponseError import msrest.serialization from ._monitor_query_client_enums import * class BatchQueryRequest(msrest.serialization.Model): """An single request in a batch. Variables are only populated by th...
0.92964
0.29328
import enum from typing import Dict import socket import ipgetter2 import psutil import orchard.extensions class IPVersion(enum.Enum): """ Versions of the Internet Protocol. """ v4 = 4 v6 = 6 @orchard.extensions.cache.memoize() def hostname() -> str: """ Get the host name of th...
orchard/system_status/system/network.py
import enum from typing import Dict import socket import ipgetter2 import psutil import orchard.extensions class IPVersion(enum.Enum): """ Versions of the Internet Protocol. """ v4 = 4 v6 = 6 @orchard.extensions.cache.memoize() def hostname() -> str: """ Get the host name of th...
0.841109
0.298044
import cx_Oracle from utils.logger.log import log class oracle: def __init__(self, configs): self.logger = log.get_logger(category="oracle") _user = configs["user"] _password = configs["password"] _host = configs["host"] _port = configs["port"] _sid = c...
utils/database/oracle_tool.py
import cx_Oracle from utils.logger.log import log class oracle: def __init__(self, configs): self.logger = log.get_logger(category="oracle") _user = configs["user"] _password = configs["password"] _host = configs["host"] _port = configs["port"] _sid = c...
0.177775
0.062617
import warnings import argparse from torch import optim from torch.optim import lr_scheduler from torch.utils.data import DataLoader from dogsvscats.data import get_datasets from dogsvscats.model import train_model, load_model, MODELS from dogsvscats.callbacks import EarlyStopping from dogsvscats import config warning...
dogsvscats/train.py
import warnings import argparse from torch import optim from torch.optim import lr_scheduler from torch.utils.data import DataLoader from dogsvscats.data import get_datasets from dogsvscats.model import train_model, load_model, MODELS from dogsvscats.callbacks import EarlyStopping from dogsvscats import config warning...
0.665628
0.220143
import fcntl import os import os.path import socket import tempfile import time import warnings from datetime import datetime from datetime import timedelta from tornado.escape import json_encode from tornado.escape import to_unicode from tornado.escape import utf8 from tornado.ioloop import IOLoop from webtiles impo...
crawl-ref/source/webserver/webtiles/connection.py
import fcntl import os import os.path import socket import tempfile import time import warnings from datetime import datetime from datetime import timedelta from tornado.escape import json_encode from tornado.escape import to_unicode from tornado.escape import utf8 from tornado.ioloop import IOLoop from webtiles impo...
0.224735
0.056444
import numpy as np import cv2 from typing import Any, Dict, List, Optional, Type, Union import gym import habitat from habitat.config import Config from habitat.core.dataset import Dataset, Episode from habitat.core.simulator import Observations class ModifiedEnvForVis(habitat.Env): def reset_to_episode(self, ta...
pointnav_vo/vis/modified_env.py
import numpy as np import cv2 from typing import Any, Dict, List, Optional, Type, Union import gym import habitat from habitat.config import Config from habitat.core.dataset import Dataset, Episode from habitat.core.simulator import Observations class ModifiedEnvForVis(habitat.Env): def reset_to_episode(self, ta...
0.932592
0.48182
import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import numpy as np from matplotlib.colors import LinearSegmentedColormap def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.c...
classifier/utils.py
import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import numpy as np from matplotlib.colors import LinearSegmentedColormap def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.c...
0.935964
0.694691
"""THOR""" import numpy as np from mindspore.ops import functional as F, composite as C, operations as P from mindspore.common.initializer import initializer from mindspore.common.parameter import Parameter, ParameterTuple from mindspore.common.tensor import Tensor import mindspore.nn as nn import mindspore.common.dtyp...
mindspore/nn/optim/thor.py
"""THOR""" import numpy as np from mindspore.ops import functional as F, composite as C, operations as P from mindspore.common.initializer import initializer from mindspore.common.parameter import Parameter, ParameterTuple from mindspore.common.tensor import Tensor import mindspore.nn as nn import mindspore.common.dtyp...
0.862236
0.520557
from typing import Type from .abc_listing import ListingBaseClass from bs4 import BeautifulSoup from dataclasses import dataclass @dataclass class CarListingAdvertiser(ListingBaseClass): __postendpoint__ = "/advertisers" __webpageurl__ = "https://www.marktplaats.nl/v/" name: str = "_" activity: str =...
scraper/app/models/listings/car_listing_advertiser.py
from typing import Type from .abc_listing import ListingBaseClass from bs4 import BeautifulSoup from dataclasses import dataclass @dataclass class CarListingAdvertiser(ListingBaseClass): __postendpoint__ = "/advertisers" __webpageurl__ = "https://www.marktplaats.nl/v/" name: str = "_" activity: str =...
0.664976
0.091544
from __future__ import absolute_import import socket import unittest from threading import Thread from hl7apy.mllp import MLLPServer, AbstractHandler from hl7apy.mllp import InvalidHL7Message, UnsupportedMessageType HOST = 'localhost' PORT = 2576 INVALID_MESSAGE = 'INVALID MESSAGE' UNSUPPORTED_MESSAGE = 'INVALID ME...
tests/test_mllp.py
from __future__ import absolute_import import socket import unittest from threading import Thread from hl7apy.mllp import MLLPServer, AbstractHandler from hl7apy.mllp import InvalidHL7Message, UnsupportedMessageType HOST = 'localhost' PORT = 2576 INVALID_MESSAGE = 'INVALID MESSAGE' UNSUPPORTED_MESSAGE = 'INVALID ME...
0.625552
0.161485
import asyncio import json import fakeredis import pytest import tempfile import os import rasa.utils.io from rasa.core import training, restore from rasa.core import utils from rasa.core.actions.action import ACTION_LISTEN_NAME from rasa.core.domain import Domain from rasa.core.events import ( UserUttered, A...
tests/core/test_trackers.py
import asyncio import json import fakeredis import pytest import tempfile import os import rasa.utils.io from rasa.core import training, restore from rasa.core import utils from rasa.core.actions.action import ACTION_LISTEN_NAME from rasa.core.domain import Domain from rasa.core.events import ( UserUttered, A...
0.4917
0.25724
import copy from typing import Dict import torch import torch.nn as nn import texar.torch as tx __all__ = [ "MetaModule", "TexarBertMetaModule" ] class MetaModule(nn.ModuleList): # pylint: disable=line-too-long r"""A class extending :class:`torch.nn.Module` that registers the parameters of a :cl...
forte/models/da_rl/magic_model.py
import copy from typing import Dict import torch import torch.nn as nn import texar.torch as tx __all__ = [ "MetaModule", "TexarBertMetaModule" ] class MetaModule(nn.ModuleList): # pylint: disable=line-too-long r"""A class extending :class:`torch.nn.Module` that registers the parameters of a :cl...
0.893114
0.444324
import logging import re from contextlib import contextmanager from functools import wraps import requests from zeep import Client from .services import BaseService log = logging.getLogger() def to_snake(name): s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1...
pydsec/pydsec.py
import logging import re from contextlib import contextmanager from functools import wraps import requests from zeep import Client from .services import BaseService log = logging.getLogger() def to_snake(name): s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1...
0.469763
0.054727
import argparse import gym import ptan import random import numpy as np import torch import torch.optim as optim import torch.nn.functional as F from ignite.engine import Engine from lib import dqn_extra, dqn_model, epsilon_tracker, hyper_params, utils def calc_loss(batch, _net, _target_net, gamma, _device="cpu"):...
2 - Code/210929 - DQN Extensions #2/03 - DQN Categorical.py
import argparse import gym import ptan import random import numpy as np import torch import torch.optim as optim import torch.nn.functional as F from ignite.engine import Engine from lib import dqn_extra, dqn_model, epsilon_tracker, hyper_params, utils def calc_loss(batch, _net, _target_net, gamma, _device="cpu"):...
0.746601
0.339636
import geopandas as gpd import json from affine import Affine from rasterio.windows import Window from rasterio.vrt import WarpedVRT from rasterio.enums import Resampling from rio_tiler.utils import get_vrt_transform, has_alpha_band from rio_tiler.utils import _requested_tile_aligned_with_internal_tile def save_empty...
solaris/utils/tile.py
import geopandas as gpd import json from affine import Affine from rasterio.windows import Window from rasterio.vrt import WarpedVRT from rasterio.enums import Resampling from rio_tiler.utils import get_vrt_transform, has_alpha_band from rio_tiler.utils import _requested_tile_aligned_with_internal_tile def save_empty...
0.823364
0.267414
import collections import json from six import string_types from ..type import (GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLScalarType) _empty_list = [] def is_valid_value(value, type): """Given a type and any value, return True if that value is valid.""" ...
graphql/core/utils/is_valid_value.py
import collections import json from six import string_types from ..type import (GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLScalarType) _empty_list = [] def is_valid_value(value, type): """Given a type and any value, return True if that value is valid.""" ...
0.629205
0.202266
"""Interfaces to all of the Movie objects offered by the Trakt.tv API""" from collections import namedtuple from trakt.core import Alias, Comment, Genre, get, delete from trakt.sync import (Scrobbler, comment, rate, add_to_history, remove_from_history, add_to_watchlist, r...
trakt/movies.py
"""Interfaces to all of the Movie objects offered by the Trakt.tv API""" from collections import namedtuple from trakt.core import Alias, Comment, Genre, get, delete from trakt.sync import (Scrobbler, comment, rate, add_to_history, remove_from_history, add_to_watchlist, r...
0.822225
0.346348
"""Tests for the X File System (XFS) file-like object.""" import os import unittest from dfvfs.file_io import xfs_file_io from dfvfs.lib import definitions from dfvfs.lib import errors from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context from tests import test_lib as shared_test_lib...
tests/file_io/xfs_file_io.py
"""Tests for the X File System (XFS) file-like object.""" import os import unittest from dfvfs.file_io import xfs_file_io from dfvfs.lib import definitions from dfvfs.lib import errors from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context from tests import test_lib as shared_test_lib...
0.563138
0.42913
import tkinter as tk import sqlite3 from files import get_current_file, global_db_path from widgets import Frame, LabelH3, Label, FrameHilited, LabelH2, Button from custom_combobox_widget import Combobox from autofill import EntryAuto, EntryAutoHilited from styles import make_formats_dict from messages import...
app/python/dates.py
import tkinter as tk import sqlite3 from files import get_current_file, global_db_path from widgets import Frame, LabelH3, Label, FrameHilited, LabelH2, Button from custom_combobox_widget import Combobox from autofill import EntryAuto, EntryAutoHilited from styles import make_formats_dict from messages import...
0.514644
0.348978
import os from subprocess import PIPE, STDOUT from mock import Mock import pytest from tests.utils import CorrectedCommand, Rule from theplease import const from theplease.exceptions import EmptyCommand from theplease.system import Path from theplease.types import Command class TestCorrectedCommand(object): def...
tests/test_types.py
import os from subprocess import PIPE, STDOUT from mock import Mock import pytest from tests.utils import CorrectedCommand, Rule from theplease import const from theplease.exceptions import EmptyCommand from theplease.system import Path from theplease.types import Command class TestCorrectedCommand(object): def...
0.377311
0.289033
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Page', fields=[...
ostinato/pages/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Page', fields=[...
0.613352
0.145844
import itertools import time import flask from dash import Dash from dash.dependencies import Input, Output import dash_html_components as html import dash_core_components as dcc from .IntegrationTests import IntegrationTests from .utils import wait_for class Tests(IntegrationTests): def setUp(self): pa...
tests/test_race_conditions.py
import itertools import time import flask from dash import Dash from dash.dependencies import Input, Output import dash_html_components as html import dash_core_components as dcc from .IntegrationTests import IntegrationTests from .utils import wait_for class Tests(IntegrationTests): def setUp(self): pa...
0.257205
0.113727
from .tool.func import * def func_upload_2(conn): curs = conn.cursor() if acl_check(None, 'upload') == 1: return re_error('/ban') if flask.request.method == 'POST': if captcha_post(flask.request.form.get('g-recaptcha-response', flask.request.form.get('g-recaptcha', ''))) == 1: ...
route/func_upload.py
from .tool.func import * def func_upload_2(conn): curs = conn.cursor() if acl_check(None, 'upload') == 1: return re_error('/ban') if flask.request.method == 'POST': if captcha_post(flask.request.form.get('g-recaptcha-response', flask.request.form.get('g-recaptcha', ''))) == 1: ...
0.21036
0.083778
import vField import numpy as np def transformField( field, scale, translate ): '''Performs a transformation on the domain of a vector field. @param field An instance of vField.VectorField. This will be changed IN PLACE. @param scale A 2-tuple of floats....
out/xformVectorField.py
import vField import numpy as np def transformField( field, scale, translate ): '''Performs a transformation on the domain of a vector field. @param field An instance of vField.VectorField. This will be changed IN PLACE. @param scale A 2-tuple of floats....
0.548432
0.605099
import math import tkinter as tk from dusted import geom, utils class LevelView(tk.Canvas): def __init__(self, parent, level, cursor): super().__init__(parent, height=0) self.level = level self.level.subscribe(self.on_level_change) self.cursor = cursor self.cursor.subscr...
dusted/level_view.py
import math import tkinter as tk from dusted import geom, utils class LevelView(tk.Canvas): def __init__(self, parent, level, cursor): super().__init__(parent, height=0) self.level = level self.level.subscribe(self.on_level_change) self.cursor = cursor self.cursor.subscr...
0.50952
0.185762
from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Tuple import numpy as np import pandapower as pp import pandas as pd from pandapower.control import ConstControl from pandapower.timeseries import DFData, OutputWriter, run_timeseries from tqdm import tqdm from...
src/simulation/simulation.py
from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Tuple import numpy as np import pandapower as pp import pandas as pd from pandapower.control import ConstControl from pandapower.timeseries import DFData, OutputWriter, run_timeseries from tqdm import tqdm from...
0.903741
0.447158
import copy import itertools from typing import List, Iterable relation_mandatory_args = { "Accident": {"location", "trigger"}, "CanceledRoute": {"location", "trigger"}, "CanceledStop": {"location", "trigger"}, "Delay": {"location", "trigger"}, "Disaster": {"type", "location"}, "Obstruction": {...
spart/util/util.py
import copy import itertools from typing import List, Iterable relation_mandatory_args = { "Accident": {"location", "trigger"}, "CanceledRoute": {"location", "trigger"}, "CanceledStop": {"location", "trigger"}, "Delay": {"location", "trigger"}, "Disaster": {"type", "location"}, "Obstruction": {...
0.540924
0.265499
import pytest from app.emails import send_email @pytest.mark.parametrize('sender, config_set_arg, config_set, tags', [ (None, None, '', []), ('<EMAIL>', 'foo', 'foo', [{'Name': 'foo', 'Value': 'foo'}]) ]) def test_send_email(test_app, mocker, sender, config_set_arg, config_set, tags): "...
tests/unit/test_emails.py
import pytest from app.emails import send_email @pytest.mark.parametrize('sender, config_set_arg, config_set, tags', [ (None, None, '', []), ('<EMAIL>', 'foo', 'foo', [{'Name': 'foo', 'Value': 'foo'}]) ]) def test_send_email(test_app, mocker, sender, config_set_arg, config_set, tags): "...
0.480235
0.186595
import unittest from follower_maze import clients from tests import factories from tests import mocks from tests.helpers import async_test PAYLOAD1 = b"1" PAYLOAD2 = b"2" CLIENT1 = 1 CLIENT2 = 13 CLIENT3 = 87 class TestClientRegistry(unittest.TestCase): """ Test ClientRegistry: correct mapping, notifie...
tests/test_client_registry.py
import unittest from follower_maze import clients from tests import factories from tests import mocks from tests.helpers import async_test PAYLOAD1 = b"1" PAYLOAD2 = b"2" CLIENT1 = 1 CLIENT2 = 13 CLIENT3 = 87 class TestClientRegistry(unittest.TestCase): """ Test ClientRegistry: correct mapping, notifie...
0.429908
0.225385
import smtplib import sys def load_emails(filename): """ Load the target email addresses from a file. """ emails = [] print('[*] Loading email addresses.') with open(filename) as f: for line in f: line = line.rstrip() if line.startswith('#'): co...
smtp_enum.py
import smtplib import sys def load_emails(filename): """ Load the target email addresses from a file. """ emails = [] print('[*] Loading email addresses.') with open(filename) as f: for line in f: line = line.rstrip() if line.startswith('#'): co...
0.307774
0.205097
import json from otcextensions.tests.functional.osclient.nat.v2 import common class TestSnat(common.NatTestCase): """Functional Tests for NAT Gateway""" def setUp(self): super(TestSnat, self).setUp() def test_snat_rule_list(self): json_output = json.loads(self.openstack( 'n...
otcextensions/tests/functional/osclient/nat/v2/test_snat.py
import json from otcextensions.tests.functional.osclient.nat.v2 import common class TestSnat(common.NatTestCase): """Functional Tests for NAT Gateway""" def setUp(self): super(TestSnat, self).setUp() def test_snat_rule_list(self): json_output = json.loads(self.openstack( 'n...
0.474875
0.225768
calls.""" from typing import List, Union from mythril.disassembler.disassembly import Disassembly from mythril.laser.ethereum.cfg import Node, Edge, JumpType from mythril.laser.ethereum.state.calldata import ConcreteCalldata from mythril.laser.ethereum.state.global_state import GlobalState from mythril.laser.ethereum....
mythril/laser/ethereum/transaction/concolic.py
calls.""" from typing import List, Union from mythril.disassembler.disassembly import Disassembly from mythril.laser.ethereum.cfg import Node, Edge, JumpType from mythril.laser.ethereum.state.calldata import ConcreteCalldata from mythril.laser.ethereum.state.global_state import GlobalState from mythril.laser.ethereum....
0.74872
0.295795
import sqlite3 from .validations import type_pos_int, type_non_neg_int, expect_in, expect_type, expect_len_range, cast_expect_type from .shared_exceptions import StatusMessageException def _process_values(values, processors, column_list, context): if not values or not processors: return values if is...
restomatic/json_sql_compositor.py
import sqlite3 from .validations import type_pos_int, type_non_neg_int, expect_in, expect_type, expect_len_range, cast_expect_type from .shared_exceptions import StatusMessageException def _process_values(values, processors, column_list, context): if not values or not processors: return values if is...
0.485844
0.32603
from __future__ import print_function import time import sys from GeneticAlgorithm.fitness import assess_chromosome_fitness from GeneticAlgorithm.genetic_engine import * import subprocess import unittest import logging from logging import config image_size = 28 num_labels = 10 img_rows = 28 img_cols = 28 def unp...
examples/MNIST.py
from __future__ import print_function import time import sys from GeneticAlgorithm.fitness import assess_chromosome_fitness from GeneticAlgorithm.genetic_engine import * import subprocess import unittest import logging from logging import config image_size = 28 num_labels = 10 img_rows = 28 img_cols = 28 def unp...
0.474631
0.403449
from telethon.sync import TelegramClient from telethon.tl.types import InputPeerChannel from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError, PhoneNumberBannedError, ChatAdminRequiredError from telethon.errors.rpcerrorlist import ChatWriteForbiddenError, UserBannedInChannelError, UserA...
start.py
from telethon.sync import TelegramClient from telethon.tl.types import InputPeerChannel from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError, PhoneNumberBannedError, ChatAdminRequiredError from telethon.errors.rpcerrorlist import ChatWriteForbiddenError, UserBannedInChannelError, UserA...
0.123683
0.046141
import json import platform import warnings import requests from . import __version__, exceptions, models, API_CONFIG, DEFAULT_API_VERSION, DEFAULT_API_ENDPOINT class SearchFilters: """Simple class to hold search filter constants.""" SYMPTOMS = "symptom" RISK_FACTORS = "risk_factor" LAB_TESTS = "lab...
infermedica_api/webservice.py
import json import platform import warnings import requests from . import __version__, exceptions, models, API_CONFIG, DEFAULT_API_VERSION, DEFAULT_API_ENDPOINT class SearchFilters: """Simple class to hold search filter constants.""" SYMPTOMS = "symptom" RISK_FACTORS = "risk_factor" LAB_TESTS = "lab...
0.768646
0.111822
import asyncio import pathlib from pathlib import Path from typing import Dict, List, Optional, Union, cast from playwright._impl._api_structures import ( Geolocation, HttpCredentials, ProxySettings, ViewportSize, ) from playwright._impl._api_types import Error from playwright._impl._browser import Br...
playwright/_impl/_browser_type.py
import asyncio import pathlib from pathlib import Path from typing import Dict, List, Optional, Union, cast from playwright._impl._api_structures import ( Geolocation, HttpCredentials, ProxySettings, ViewportSize, ) from playwright._impl._api_types import Error from playwright._impl._browser import Br...
0.794026
0.124559
import argparse import os import numpy as np import tensorflow as tf from PIL import Image from matplotlib import pyplot as plt from tensorflow import keras from data import dateset_fashion_mnist from model import VAE parser = argparse.ArgumentParser() parser.add_argument('--auther', help='inner batch size', default...
VaritionalAutoEncoders.py
import argparse import os import numpy as np import tensorflow as tf from PIL import Image from matplotlib import pyplot as plt from tensorflow import keras from data import dateset_fashion_mnist from model import VAE parser = argparse.ArgumentParser() parser.add_argument('--auther', help='inner batch size', default...
0.748536
0.370795
import re import os from fabkit import api, run, sudo, filer, env, user from fablib import git from fablib.base import SimpleBase class Python(SimpleBase): def __init__(self, prefix='/usr'): self.prefix = prefix self.packages = { 'CentOS Linux 7.*': [ 'python-devel', ...
__init__.py
import re import os from fabkit import api, run, sudo, filer, env, user from fablib import git from fablib.base import SimpleBase class Python(SimpleBase): def __init__(self, prefix='/usr'): self.prefix = prefix self.packages = { 'CentOS Linux 7.*': [ 'python-devel', ...
0.246624
0.067209
from soa import token EOF_CHAR = chr(0) class Lexer(): "Lexer is the main class for lexing" def __init__(self, input_text): self.input_text = input_text + EOF_CHAR self.pos = 0 self.buffer = [] self.tokens = [] def next_char(self): "next moves the position over and...
py/soa/lexer.py
from soa import token EOF_CHAR = chr(0) class Lexer(): "Lexer is the main class for lexing" def __init__(self, input_text): self.input_text = input_text + EOF_CHAR self.pos = 0 self.buffer = [] self.tokens = [] def next_char(self): "next moves the position over and...
0.709221
0.448245
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from analysis.util import stimulus_names from sklearn.decomposition import PCA def stretch_axes(points): """ Run PCA. Stretch axes so as to make the variance along each axis the same. Do so by dividing the values of the coordinat...
analysis/perceptual_space_visualizations.py
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from analysis.util import stimulus_names from sklearn.decomposition import PCA def stretch_axes(points): """ Run PCA. Stretch axes so as to make the variance along each axis the same. Do so by dividing the values of the coordinat...
0.724968
0.625324
import torch from tqdm import tqdm import torch.nn as nn import torch.nn.functional as F def evaluate_pose(x, att): # x: B3N, att: B1KN1 # ts: B3k1 pai = att.sum(dim=3, keepdim=True) # B1K11 att = att / torch.clamp(pai, min=1e-3) ts = torch.sum( att * x[:, :, None, :, None], ...
loss_util.py
import torch from tqdm import tqdm import torch.nn as nn import torch.nn.functional as F def evaluate_pose(x, att): # x: B3N, att: B1KN1 # ts: B3k1 pai = att.sum(dim=3, keepdim=True) # B1K11 att = att / torch.clamp(pai, min=1e-3) ts = torch.sum( att * x[:, :, None, :, None], ...
0.539469
0.569254
from types import TracebackType from typing import Any, Optional, Type from scrapli.channel import Channel from scrapli.driver.base_driver import ASYNCIO_TRANSPORTS, ScrapeBase from scrapli.exceptions import TransportPluginError class Scrape(ScrapeBase): def __init__(self, **kwargs: Any) -> None: """ ...
venv/Lib/site-packages/scrapli/driver/driver.py
from types import TracebackType from typing import Any, Optional, Type from scrapli.channel import Channel from scrapli.driver.base_driver import ASYNCIO_TRANSPORTS, ScrapeBase from scrapli.exceptions import TransportPluginError class Scrape(ScrapeBase): def __init__(self, **kwargs: Any) -> None: """ ...
0.902889
0.193814
from dlflow.mgr import model, config from dlflow.models import ModelBase import tensorflow as tf class _Embedding(tf.keras.layers.Layer): def __init__(self, input_dim, output_dim): super(_Embedding, self).__init__() self.input_dim = input_dim self.output_dim = output_dim def build(se...
dlflow/models/internal/DNNBinaryClassifier.py
from dlflow.mgr import model, config from dlflow.models import ModelBase import tensorflow as tf class _Embedding(tf.keras.layers.Layer): def __init__(self, input_dim, output_dim): super(_Embedding, self).__init__() self.input_dim = input_dim self.output_dim = output_dim def build(se...
0.922024
0.371707
from armstrong.dev.tests.utils.backports import override_settings from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.template.response import TemplateResponse from django.test.client import Client from functools import wraps import fudg...
armstrong/apps/donations/tests/views.py
from armstrong.dev.tests.utils.backports import override_settings from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.template.response import TemplateResponse from django.test.client import Client from functools import wraps import fudg...
0.340924
0.185228
from contact import Contact def create_contact(fname,lname,phone,email): ''' Function to create a new contact ''' new_contact = Contact(fname,lname,phone,email) return new_contact def save_contacts(contact): ''' Function to save contact ''' contact.save_contact() def del_contact(co...
run.py
from contact import Contact def create_contact(fname,lname,phone,email): ''' Function to create a new contact ''' new_contact = Contact(fname,lname,phone,email) return new_contact def save_contacts(contact): ''' Function to save contact ''' contact.save_contact() def del_contact(co...
0.300335
0.118615
from __future__ import print_function import argparse import os import random import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import torchvision.utils as vut...
train_segmentation.py
from __future__ import print_function import argparse import os import random import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import torchvision.utils as vut...
0.53777
0.249493
import os import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter import numpy as np import pandas as pd from scipy import exp from scipy.linalg import eigh from scipy.spatial.distance import ( pdist, squareform, ) from sklearn.cross_validation import train_test_split from sklearn.data...
chapter_5.py
import os import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter import numpy as np import pandas as pd from scipy import exp from scipy.linalg import eigh from scipy.spatial.distance import ( pdist, squareform, ) from sklearn.cross_validation import train_test_split from sklearn.data...
0.586641
0.528412
# Standard libraries import os import sys import logging import inspect import hashlib from pathlib import Path from multiprocessing import cpu_count, Pool # Third party libraries import joblib import numpy as np import pandas as pd # User defined libraries from .file import mkdir class ProgressBar: def __ini...
tabular_buddy/utils/helper.py
# Standard libraries import os import sys import logging import inspect import hashlib from pathlib import Path from multiprocessing import cpu_count, Pool # Third party libraries import joblib import numpy as np import pandas as pd # User defined libraries from .file import mkdir class ProgressBar: def __ini...
0.366817
0.120051
from tkinter import Toplevel, Frame, BOTH from tkinter.scrolledtext import ScrolledText from io import StringIO import re import sys import traceback class DebugConsole: def __init__(self, root, title='', locals={}, destroy=None): self.root = Toplevel(root) self.root.wm_title("Debug console") ...
fitter/gui/debugConsole.py
from tkinter import Toplevel, Frame, BOTH from tkinter.scrolledtext import ScrolledText from io import StringIO import re import sys import traceback class DebugConsole: def __init__(self, root, title='', locals={}, destroy=None): self.root = Toplevel(root) self.root.wm_title("Debug console") ...
0.218169
0.081849
import os import sys from pathlib import Path import json # Linking params # Global vars for linking and their default values LINKABLE_FILES_EXTENSION = ".js" OUTPUT_FILE = "../main.js" LINKING_MAP_FILE = "default_linked_dirs.json" LINKING_FOR_FINAL_FILES = False def linker(): printHeader() toLinkAccording...
linker.py
import os import sys from pathlib import Path import json # Linking params # Global vars for linking and their default values LINKABLE_FILES_EXTENSION = ".js" OUTPUT_FILE = "../main.js" LINKING_MAP_FILE = "default_linked_dirs.json" LINKING_FOR_FINAL_FILES = False def linker(): printHeader() toLinkAccording...
0.04691
0.050611
from server import utils from server import cache import requests import config class General: @classmethod @cache.memoize(timeout=config.cache) def _calc_supply(cls, height): snapshot = 443863973624633 supply = 0 for height in range(0, height + 1): supply += utils.rewa...
server/methods/general.py
from server import utils from server import cache import requests import config class General: @classmethod @cache.memoize(timeout=config.cache) def _calc_supply(cls, height): snapshot = 443863973624633 supply = 0 for height in range(0, height + 1): supply += utils.rewa...
0.496094
0.139309
import os import argparse def get_cmd(task, sub_task, model_tag, gpu, data_num, bs, lr, source_length, target_length, patience, epoch, warmup, gpu_type, res_fn): cmd_str = 'bash exp_with_args.sh %s %s %s %d %d %d %d %d %d %d %d %d %s %s' % \ (task, sub_task, model_tag, gpu, data_num, bs...
sh/run_exp.py
import os import argparse def get_cmd(task, sub_task, model_tag, gpu, data_num, bs, lr, source_length, target_length, patience, epoch, warmup, gpu_type, res_fn): cmd_str = 'bash exp_with_args.sh %s %s %s %d %d %d %d %d %d %d %d %d %s %s' % \ (task, sub_task, model_tag, gpu, data_num, bs...
0.404743
0.364156
from __future__ import annotations import re from typing import Callable, ClassVar, List, Optional, Pattern, Sequence, Tuple, Union, cast import discord from discord.ext import commands _ID_RE = re.compile(r"([0-9]{15,20})$") _USER_MENTION_RE = re.compile(r"<@!?([0-9]{15,20})>$") _CHAN_MENTION_RE = re.compile(r"<#([...
bot/utils/predicates.py
from __future__ import annotations import re from typing import Callable, ClassVar, List, Optional, Pattern, Sequence, Tuple, Union, cast import discord from discord.ext import commands _ID_RE = re.compile(r"([0-9]{15,20})$") _USER_MENTION_RE = re.compile(r"<@!?([0-9]{15,20})>$") _CHAN_MENTION_RE = re.compile(r"<#([...
0.934005
0.281963
from __future__ import absolute_import from sentry.models.projectoption import ProjectOption from sentry.testutils import TestCase from sentry.utils.safe import set_path from sentry.message_filters import ( _localhost_filter, _browser_extensions_filter, _web_crawlers_filter, _legacy_browsers_filter, ) class ...
tests/integration/test_message_filters.py
from __future__ import absolute_import from sentry.models.projectoption import ProjectOption from sentry.testutils import TestCase from sentry.utils.safe import set_path from sentry.message_filters import ( _localhost_filter, _browser_extensions_filter, _web_crawlers_filter, _legacy_browsers_filter, ) class ...
0.659295
0.139045
"""Compare environment variables snapshot with expected and detect changes """ import argparse import difflib import logging import pathlib import re import os import sys import typing import uuid def normalize_env_variables(variables: typing.Dict[str, str]) -> typing.Dict[str, str]: """Cleanup environment variab...
tests/resources/environment_vars/env_vars_changes_compare.py
"""Compare environment variables snapshot with expected and detect changes """ import argparse import difflib import logging import pathlib import re import os import sys import typing import uuid def normalize_env_variables(variables: typing.Dict[str, str]) -> typing.Dict[str, str]: """Cleanup environment variab...
0.500488
0.37935
import torchvision_sunner.transforms as sunnertransforms import torchvision_sunner.data as sunnerData import torchvision.transforms as transforms from tensorboardX import SummaryWriter from networks_stylegan import StyleGenerator, StyleDiscriminator from loss import gradient_penalty, R1Penalty, R2Penalty from opts i...
train_stylegan.py
import torchvision_sunner.transforms as sunnertransforms import torchvision_sunner.data as sunnerData import torchvision.transforms as transforms from tensorboardX import SummaryWriter from networks_stylegan import StyleGenerator, StyleDiscriminator from loss import gradient_penalty, R1Penalty, R2Penalty from opts i...
0.729327
0.346044
from collections import defaultdict from chroma_core.services.job_scheduler.job_scheduler_client import JobSchedulerClient from django.db.models import Q from chroma_core.models import ManagedFilesystem, ManagedTarget from chroma_core.models import ManagedOst, ManagedMdt, ManagedMgs from chroma_core.models import Vo...
chroma-manager/chroma_api/filesystem.py
from collections import defaultdict from chroma_core.services.job_scheduler.job_scheduler_client import JobSchedulerClient from django.db.models import Q from chroma_core.models import ManagedFilesystem, ManagedTarget from chroma_core.models import ManagedOst, ManagedMdt, ManagedMgs from chroma_core.models import Vo...
0.501221
0.124452
import requests from bs4 import BeautifulSoup as bs from itertools import chain, filterfalse langs = {'python': ['(py)', '(pypy)', '(py3)'], 'ruby': ['(rb)']} def get_pids(maxpage=17): """ gatter problem ids and return it one by one """ baseurl = 'https://algospot.com/judge/problem/list/%d' for...
hard-gists/ef9e5c352e54769c4d43/snippet.py
import requests from bs4 import BeautifulSoup as bs from itertools import chain, filterfalse langs = {'python': ['(py)', '(pypy)', '(py3)'], 'ruby': ['(rb)']} def get_pids(maxpage=17): """ gatter problem ids and return it one by one """ baseurl = 'https://algospot.com/judge/problem/list/%d' for...
0.435421
0.119254
import json import pathlib import re as regex from abc import ABC, abstractmethod from typing import List, Optional import requests import semver import cpo.utils.process from cpo.config import configuration_manager from cpo.lib.error import DataGateCLIException class AbstractDependencyManagerPlugIn(ABC): ""...
cpo/lib/dependency_manager/dependency_manager_plugin.py
import json import pathlib import re as regex from abc import ABC, abstractmethod from typing import List, Optional import requests import semver import cpo.utils.process from cpo.config import configuration_manager from cpo.lib.error import DataGateCLIException class AbstractDependencyManagerPlugIn(ABC): ""...
0.900115
0.340787
from pathlib import Path from typing import Mapping, Optional from hamcrest import ( assert_that, contains, equal_to, is_, ) from microcosm_sagemaker.testing.bytes_extractor import ExtractorMatcherPair def _identity(x): return x def _is_hidden(path: Path) -> bool: return path.name.startswi...
microcosm_sagemaker/testing/directory_comparison.py
from pathlib import Path from typing import Mapping, Optional from hamcrest import ( assert_that, contains, equal_to, is_, ) from microcosm_sagemaker.testing.bytes_extractor import ExtractorMatcherPair def _identity(x): return x def _is_hidden(path: Path) -> bool: return path.name.startswi...
0.92095
0.460956
import os import sys import pexpect def close_benchmark(benchmark): benchmark.expect(pexpect.EOF, timeout=None) benchmark.close() def check_exit_status(benchmark): if benchmark.exitstatus != 0 or benchmark.signalstatus is not None: print( "Benchmark failed with exit status " ...
scripts/test/hyriseBenchmarkCore.py
import os import sys import pexpect def close_benchmark(benchmark): benchmark.expect(pexpect.EOF, timeout=None) benchmark.close() def check_exit_status(benchmark): if benchmark.exitstatus != 0 or benchmark.signalstatus is not None: print( "Benchmark failed with exit status " ...
0.189896
0.128963
from telethon.tl import functions from telethon.tl.types import MessageEntityMentionName from . import * @bot.on(phoenix_cmd(pattern="create (b|g|c) (.*)")) # pylint:disable=E0602 @bot.on(sudo_cmd(pattern="create (b|g|c) (.*)", allow_sudo=True)) async def _(event): if event.fwd_from: return type_of_...
Phoenix/plugins/create.py
from telethon.tl import functions from telethon.tl.types import MessageEntityMentionName from . import * @bot.on(phoenix_cmd(pattern="create (b|g|c) (.*)")) # pylint:disable=E0602 @bot.on(sudo_cmd(pattern="create (b|g|c) (.*)", allow_sudo=True)) async def _(event): if event.fwd_from: return type_of_...
0.421195
0.136234
import logging import os import pyauto_media import pyauto # HTML test path; relative to src/chrome/test/data. _TEST_HTML_PATH = os.path.join('media', 'html', 'media_basic_playback.html') # Test videos to play. TODO(dalecurtis): Convert to text matrix parser when we # have more test videos in the matrix. Code alr...
chrome/test/functional/media/media_basic_playback.py
import logging import os import pyauto_media import pyauto # HTML test path; relative to src/chrome/test/data. _TEST_HTML_PATH = os.path.join('media', 'html', 'media_basic_playback.html') # Test videos to play. TODO(dalecurtis): Convert to text matrix parser when we # have more test videos in the matrix. Code alr...
0.375936
0.427815
import pprint import re # noqa: F401 import six from hubspot.crm.schemas.configuration import Configuration class ModelProperty(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: ...
hubspot/crm/schemas/models/model_property.py
import pprint import re # noqa: F401 import six from hubspot.crm.schemas.configuration import Configuration class ModelProperty(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: ...
0.690872
0.195613
import copy import os import unittest from collections import OrderedDict from conans import tools from conans.client.client_cache import ClientCache from conans.client.conf.detect import detect_defaults_settings from conans.paths import CONANFILE_TXT from conans.test.utils.test_files import temp_folder from conans.te...
conans/test/integration/conf_default_settings_test.py
import copy import os import unittest from collections import OrderedDict from conans import tools from conans.client.client_cache import ClientCache from conans.client.conf.detect import detect_defaults_settings from conans.paths import CONANFILE_TXT from conans.test.utils.test_files import temp_folder from conans.te...
0.457621
0.185062
from __future__ import unicode_literals from collections import OrderedDict from datetime import datetime, timedelta from dateutil import rrule from flask import flash, jsonify, request, session from werkzeug.exceptions import BadRequest from indico.modules.events.cloning import EventCloner from indico.modules.even...
indico/modules/events/management/controllers/cloning.py
from __future__ import unicode_literals from collections import OrderedDict from datetime import datetime, timedelta from dateutil import rrule from flask import flash, jsonify, request, session from werkzeug.exceptions import BadRequest from indico.modules.events.cloning import EventCloner from indico.modules.even...
0.696165
0.165357
import os try: __IPYTHON__ import sys del sys.argv[1:] except: pass import srwl_bl import srwlib import srwlpy import srwl_uti_smp def set_optics(v=None): el = [] pp = [] names = ['MOAT_1', 'MOAT_1_MOAT_2', 'MOAT_2', 'MOAT_2_HFM', 'HFM', 'HFM_VFM', 'VFM', 'VFM_VDM', 'VDM', 'VDM_SSA', 'SS...
tests/template/srw_generate_data/nsls-ii-smi-beamline.py
import os try: __IPYTHON__ import sys del sys.argv[1:] except: pass import srwl_bl import srwlib import srwlpy import srwl_uti_smp def set_optics(v=None): el = [] pp = [] names = ['MOAT_1', 'MOAT_1_MOAT_2', 'MOAT_2', 'MOAT_2_HFM', 'HFM', 'HFM_VFM', 'VFM', 'VFM_VDM', 'VDM', 'VDM_SSA', 'SS...
0.158142
0.222025
from __future__ import unicode_literals import posixpath from uuid import uuid4 from sqlalchemy.dialects.postgresql import JSONB, UUID from indico.core.config import config from indico.core.db import db from indico.core.storage import StoredFileMixin from indico.util.fs import secure_filename from indico.util.strin...
indico/modules/files/models/files.py
from __future__ import unicode_literals import posixpath from uuid import uuid4 from sqlalchemy.dialects.postgresql import JSONB, UUID from indico.core.config import config from indico.core.db import db from indico.core.storage import StoredFileMixin from indico.util.fs import secure_filename from indico.util.strin...
0.552057
0.095013
import unittest from openprocurement.archivarius.tenders.tests.base import BaseTenderArchivariusWebTest class TenderArchivariusResourceTest(BaseTenderArchivariusWebTest): def test_dump_tender_invalid(self): response = self.app.get('/tenders/some_id/dump', status=404) self.assertEqual(response.sta...
openprocurement/archivarius/tenders/tests/dump.py
import unittest from openprocurement.archivarius.tenders.tests.base import BaseTenderArchivariusWebTest class TenderArchivariusResourceTest(BaseTenderArchivariusWebTest): def test_dump_tender_invalid(self): response = self.app.get('/tenders/some_id/dump', status=404) self.assertEqual(response.sta...
0.413004
0.280173
from __future__ import absolute_import from oci._vendor import requests # noqa: F401 from oci._vendor import six from oci import retry # noqa: F401 from oci.base_client import BaseClient from oci.config import get_config_value_or_default, validate_config from oci.signer import Signer from oci.util import Sentinel ...
darling_ansible/python_venv/lib/python3.7/site-packages/oci/data_flow/data_flow_client.py
from __future__ import absolute_import from oci._vendor import requests # noqa: F401 from oci._vendor import six from oci import retry # noqa: F401 from oci.base_client import BaseClient from oci.config import get_config_value_or_default, validate_config from oci.signer import Signer from oci.util import Sentinel ...
0.86977
0.272999