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 __future__ import absolute_import
from __future__ import print_function
import mock
import charms_openstack.test_utils as test_utils
import charm.openstack.keystone_kerberos as keystone_kerberos
def FakeConfig(init_dict):
def _config(key=None):
return init_dict[key] if key else init_dict
re... | unit_tests/test_lib_charm_openstack_keystone_kerberos.py |
from __future__ import absolute_import
from __future__ import print_function
import mock
import charms_openstack.test_utils as test_utils
import charm.openstack.keystone_kerberos as keystone_kerberos
def FakeConfig(init_dict):
def _config(key=None):
return init_dict[key] if key else init_dict
re... | 0.657868 | 0.144662 |
from datetime import datetime
from typing import List
from grapl_common.metrics.metric_reporter import MetricReporter, TagPair
from grapl_common.time_utils import MillisDuration
class TestMetricReporter:
def test__smoke_test(self) -> None:
f = Fixture()
tags = (TagPair("k1", "v1"), TagPair("k2", ... | src/python/grapl-common/tests/metrics/test_metric_reporter.py | from datetime import datetime
from typing import List
from grapl_common.metrics.metric_reporter import MetricReporter, TagPair
from grapl_common.time_utils import MillisDuration
class TestMetricReporter:
def test__smoke_test(self) -> None:
f = Fixture()
tags = (TagPair("k1", "v1"), TagPair("k2", ... | 0.846847 | 0.40204 |
import pprint
import re # noqa: F401
import six
class Greeks(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value... | swagger_client/mercury/client/model/greeks.py | import pprint
import re # noqa: F401
import six
class Greeks(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value... | 0.721154 | 0.307287 |
import unittest
import numpy
import dicomifier
import odil
class TestOdilGetter(unittest.TestCase):
def test_getter_binary(self):
data_set = odil.DataSet()
pixel_data = [bin(42)]
data_set.add("PixelData", pixel_data, odil.VR.OB)
val = dicomifier.dicom_to_nifti.odil_getter._getter... | tests/python/dicomifier/dicom_to_nifti/test_odil_getter.py | import unittest
import numpy
import dicomifier
import odil
class TestOdilGetter(unittest.TestCase):
def test_getter_binary(self):
data_set = odil.DataSet()
pixel_data = [bin(42)]
data_set.add("PixelData", pixel_data, odil.VR.OB)
val = dicomifier.dicom_to_nifti.odil_getter._getter... | 0.433742 | 0.485783 |
# STDLIB
import os
import sys
import warnings
# THIRD-PARTY
import numpy as np
import pytest
# ASTROPY
from astropy.utils.data import get_pkg_data_filename
from astropy.utils.exceptions import AstropyUserWarning
# SYNPHOT
from synphot import exceptions as synexceptions
# LOCAL
from .. import stio
from ..config impo... | stsynphot/tests/test_stio.py | # STDLIB
import os
import sys
import warnings
# THIRD-PARTY
import numpy as np
import pytest
# ASTROPY
from astropy.utils.data import get_pkg_data_filename
from astropy.utils.exceptions import AstropyUserWarning
# SYNPHOT
from synphot import exceptions as synexceptions
# LOCAL
from .. import stio
from ..config impo... | 0.377885 | 0.287733 |
import itertools
from collections import defaultdict
from copy import deepcopy
from typing import List, Dict, Any, Tuple, Sequence, Optional, Iterator
from pyfileconf.basemodels.config import ConfigBase
from pyfileconf.logger.logger import logger
from pyfileconf.plugin import manager
from pyfileconf.runner.models.inte... | pyfileconf/iterate.py | import itertools
from collections import defaultdict
from copy import deepcopy
from typing import List, Dict, Any, Tuple, Sequence, Optional, Iterator
from pyfileconf.basemodels.config import ConfigBase
from pyfileconf.logger.logger import logger
from pyfileconf.plugin import manager
from pyfileconf.runner.models.inte... | 0.835114 | 0.307976 |
import hid
from time import sleep
class XpgSummonerControl:
def __init__(self, vid=0x125f, did=0x9418):
self.hidraw = hid.device(vid,did)
while True:
try:
self.hidraw.open(vid,did)
break
except Exception:
pass
def selectPr... | XpgSummonerControl.py | import hid
from time import sleep
class XpgSummonerControl:
def __init__(self, vid=0x125f, did=0x9418):
self.hidraw = hid.device(vid,did)
while True:
try:
self.hidraw.open(vid,did)
break
except Exception:
pass
def selectPr... | 0.219588 | 0.08389 |
import os
from app.main.utils.run_code_util import is_error, make_python_codefile, generate_output_error, compare_output, read_error
import json
from app.main.models.SubmissionsModel import SubmissionsModel
from app.main import db
def make_submit_folder(submission_id):
"""
Make submission folder
"""
... | src/server/app/main/utils/submitcode_util.py | import os
from app.main.utils.run_code_util import is_error, make_python_codefile, generate_output_error, compare_output, read_error
import json
from app.main.models.SubmissionsModel import SubmissionsModel
from app.main import db
def make_submit_folder(submission_id):
"""
Make submission folder
"""
... | 0.195287 | 0.149656 |
import json
import sys
import os
if __name__ == '__main__':
print(sys.argv)
POSTGRES_PASSWORD = sys.argv[1]
SUPERADMIN_PASSWORD = sys.argv[2]
APP_SECRET = sys.argv[3]
KUBERNETES_NETWORK = sys.argv[4]
KUBERNETES_ADVERTISE_ADDR = sys.argv[5]
SINGA_AUTO_VERSION = sys.argv[6]
SINGA_AUTO_AD... | scripts/kubernetes/create_config.py |
import json
import sys
import os
if __name__ == '__main__':
print(sys.argv)
POSTGRES_PASSWORD = sys.argv[1]
SUPERADMIN_PASSWORD = sys.argv[2]
APP_SECRET = sys.argv[3]
KUBERNETES_NETWORK = sys.argv[4]
KUBERNETES_ADVERTISE_ADDR = sys.argv[5]
SINGA_AUTO_VERSION = sys.argv[6]
SINGA_AUTO_AD... | 0.200871 | 0.055234 |
"""Tests for ops to trim segments."""
from absl.testing import parameterized
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import test_util
from tensorflow.python.ops.ragged import ragged_factory_ops
from tensorflow.python.platform import test
from tensorflow_text.python.ops imp... | tensorflow_text/python/ops/trimmer_ops_test.py |
"""Tests for ops to trim segments."""
from absl.testing import parameterized
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import test_util
from tensorflow.python.ops.ragged import ragged_factory_ops
from tensorflow.python.platform import test
from tensorflow_text.python.ops imp... | 0.842313 | 0.64777 |
import logging
import os
import usernamerules
import utils.argparsers as argparsers
DEFAULT_RULE_NAMES = ['simple', 'surname', 'name', 'partial_name_and_surname', 'name_and_partial_surname']
def __apply(rule_names, with_user_data, with_separator):
usernames = set()
for rule_name in rule_names:
rul... | entusergenerator.py |
import logging
import os
import usernamerules
import utils.argparsers as argparsers
DEFAULT_RULE_NAMES = ['simple', 'surname', 'name', 'partial_name_and_surname', 'name_and_partial_surname']
def __apply(rule_names, with_user_data, with_separator):
usernames = set()
for rule_name in rule_names:
rul... | 0.310276 | 0.143128 |
import argparse
import importlib
import sys
from signal import SIG_DFL, SIGPIPE, signal
from typing import Any, Dict, Generator, List, Optional
from flupy import __version__, flu, walk_dirs, walk_files
def read_file(path: str) -> Generator[str, None, None]:
"""Yield lines from a file given its path"""
with o... | src/flupy/cli/cli.py | import argparse
import importlib
import sys
from signal import SIG_DFL, SIGPIPE, signal
from typing import Any, Dict, Generator, List, Optional
from flupy import __version__, flu, walk_dirs, walk_files
def read_file(path: str) -> Generator[str, None, None]:
"""Yield lines from a file given its path"""
with o... | 0.485844 | 0.162646 |
import warnings
from typing import Any, Dict, Optional, Union
import numpy as np
import pandas as pd
from scipy import sparse as sps
from sklearn.linear_model import LogisticRegression
from .util import benchmark_convergence_tolerance, runtime
def _build_and_fit(model_args, train_args):
return LogisticRegressio... | src/glum_benchmarks/bench_liblinear.py | import warnings
from typing import Any, Dict, Optional, Union
import numpy as np
import pandas as pd
from scipy import sparse as sps
from sklearn.linear_model import LogisticRegression
from .util import benchmark_convergence_tolerance, runtime
def _build_and_fit(model_args, train_args):
return LogisticRegressio... | 0.935487 | 0.452717 |
from datetime import datetime, timedelta
from academics.flashcard.manage import FlashcardManager
from django.db import models
from django.utils import timezone
from config.settings import AUTH_USER_MODEL
# TODO: revisit the _str implementation for various models
class Subject(models.Model):
"""
Simple Sche... | studenthub/academics/flashcard/models.py | from datetime import datetime, timedelta
from academics.flashcard.manage import FlashcardManager
from django.db import models
from django.utils import timezone
from config.settings import AUTH_USER_MODEL
# TODO: revisit the _str implementation for various models
class Subject(models.Model):
"""
Simple Sche... | 0.464416 | 0.16807 |
from django.forms import ModelForm as DjangoModelForm
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields import NOT_PROVIDED
class ModelForm(DjangoModelForm):
"""
Allows a model form to validate properly with default attributes missing.
Django model forms expect all attrib... | djrest/forms.py | from django.forms import ModelForm as DjangoModelForm
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields import NOT_PROVIDED
class ModelForm(DjangoModelForm):
"""
Allows a model form to validate properly with default attributes missing.
Django model forms expect all attrib... | 0.591959 | 0.446314 |
import os
PACKAGE_DIR=os.path.abspath(os.path.dirname(__file__))
DOWNLOAD_DIR=os.path.join(PACKAGE_DIR,"models")
from transformers.file_utils import hf_bucket_url
MODEL_URL=hf_bucket_url("KoichiYasuoka/SuPar-Kanbun","suparkanbun/models/")
import numpy
from spacy.language import Language
from spacy.symbols import LAN... | suparkanbun/suparkanbun.py |
import os
PACKAGE_DIR=os.path.abspath(os.path.dirname(__file__))
DOWNLOAD_DIR=os.path.join(PACKAGE_DIR,"models")
from transformers.file_utils import hf_bucket_url
MODEL_URL=hf_bucket_url("KoichiYasuoka/SuPar-Kanbun","suparkanbun/models/")
import numpy
from spacy.language import Language
from spacy.symbols import LAN... | 0.189896 | 0.09187 |
from twisted.trial.unittest import SkipTest, SynchronousTestCase
from ..cinder import (
get_keystone_session, get_cinder_v1_client, wait_for_volume_state
)
from ..test.blockdevicefactory import (
InvalidConfig,
ProviderType,
get_openstack_region_for_test,
get_blockdevice_config,
)
from ....testtool... | flocker/node/agents/functional/test_cinder_behaviour.py | from twisted.trial.unittest import SkipTest, SynchronousTestCase
from ..cinder import (
get_keystone_session, get_cinder_v1_client, wait_for_volume_state
)
from ..test.blockdevicefactory import (
InvalidConfig,
ProviderType,
get_openstack_region_for_test,
get_blockdevice_config,
)
from ....testtool... | 0.819929 | 0.289064 |
import os
import argparse
import yaml
import csv
import logging
import pandas as pd
import numpy as np
import pbio.ribo.ribo_utils as ribo_utils
import pbio.ribo.ribo_filenames as filenames
import pbio.misc.logging_utils as logging_utils
import pbio.misc.parallel as parallel
import pbio.misc.pandas_utils as pandas_ut... | pproc/pgrms/get_all_read_counts_per_frame.py | import os
import argparse
import yaml
import csv
import logging
import pandas as pd
import numpy as np
import pbio.ribo.ribo_utils as ribo_utils
import pbio.ribo.ribo_filenames as filenames
import pbio.misc.logging_utils as logging_utils
import pbio.misc.parallel as parallel
import pbio.misc.pandas_utils as pandas_ut... | 0.553264 | 0.163412 |
import logging
from django.db import models
from django.utils.text import slugify
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.contenttypes.models import ContentType
from jsonfield import JSONField
from localflavor.... | foia_hub/models.py | import logging
from django.db import models
from django.utils.text import slugify
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.contenttypes.models import ContentType
from jsonfield import JSONField
from localflavor.... | 0.432303 | 0.179315 |
import os, subprocess
# cookiecutter jinja2 obj is extracted as an OrderedDict
from collections import OrderedDict
from cookiecutter.main import cookiecutter
from github import Github
from git import Repo
def setup_git(context):
project_slug = context['project_slug']
use_github = context['use_github']
co... | common/post_gen_hook.py | import os, subprocess
# cookiecutter jinja2 obj is extracted as an OrderedDict
from collections import OrderedDict
from cookiecutter.main import cookiecutter
from github import Github
from git import Repo
def setup_git(context):
project_slug = context['project_slug']
use_github = context['use_github']
co... | 0.270769 | 0.139104 |
from typing import Iterable, Iterator, List, Optional, Tuple
from pypict import capi
class Task:
def __init__(self, seed: Optional[int] = None):
self.handle = capi.createTask()
self._model = _Model(seed)
capi.setRootModel(self.handle, self._model.handle)
def __del__(self) -> None:
... | pypict/api.py | from typing import Iterable, Iterator, List, Optional, Tuple
from pypict import capi
class Task:
def __init__(self, seed: Optional[int] = None):
self.handle = capi.createTask()
self._model = _Model(seed)
capi.setRootModel(self.handle, self._model.handle)
def __del__(self) -> None:
... | 0.865963 | 0.203985 |
from flask_sqlalchemy import SQLAlchemy
from .EnvironmentModel import EnvironmentModel
from .ZoneModel import ZoneModel
from .FirewallModel import FirewallModel
from .AllowedPortModel import AllowedPortModel
from .ZoneConnectionModel import ZoneConnectionModel
def flask_sqlalchemy_mappings(db: SQLAlchemy):
metada... | fwl-automation-decisions/infrastructure/src/infrastructure/flsql/model/Mappings.py | from flask_sqlalchemy import SQLAlchemy
from .EnvironmentModel import EnvironmentModel
from .ZoneModel import ZoneModel
from .FirewallModel import FirewallModel
from .AllowedPortModel import AllowedPortModel
from .ZoneConnectionModel import ZoneConnectionModel
def flask_sqlalchemy_mappings(db: SQLAlchemy):
metada... | 0.641198 | 0.063686 |
import pytest
import torch
from stacked_hourglass import hg1, hg2
from stacked_hourglass.datasets.mpii import Mpii
from stacked_hourglass.train import do_training_step, do_validation_step, do_validation_epoch, \
do_training_epoch
from torch.optim import Adam
from torch.utils.data import DataLoader
def test_do_tra... | Source_Codes/Human Pose Estimation/tests/test_train.py | import pytest
import torch
from stacked_hourglass import hg1, hg2
from stacked_hourglass.datasets.mpii import Mpii
from stacked_hourglass.train import do_training_step, do_validation_step, do_validation_epoch, \
do_training_epoch
from torch.optim import Adam
from torch.utils.data import DataLoader
def test_do_tra... | 0.744935 | 0.565959 |
"""Tests for tensorflow_transform.internal.schema_inference."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow_transform import schema_inference
from tensorflow_transform.tf_metadata import dataset_schema
import un... | tensorflow_transform/schema_inference_test.py | """Tests for tensorflow_transform.internal.schema_inference."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow_transform import schema_inference
from tensorflow_transform.tf_metadata import dataset_schema
import un... | 0.894167 | 0.529568 |
import os
import sys
import pymysql
import logging
from chatterbot import ChatBot
from chatterbot import languages
from chatterbot.response_selection import get_random_response, get_first_response, get_most_frequent_response
from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer
from chatterbot import com... | api/__init__.py | import os
import sys
import pymysql
import logging
from chatterbot import ChatBot
from chatterbot import languages
from chatterbot.response_selection import get_random_response, get_first_response, get_most_frequent_response
from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer
from chatterbot import com... | 0.181481 | 0.067485 |
import threading
import time
import datetime
import pytz
class WorkerThreadExceptionClass(Exception):
pass
#First impleimentaion was using pref_counter
# reimplemented to use date time due to limitations
def getNextWorkerTime(lastRunTime, curTime, frequency):
retVal = lastRunTime
while retVal < curTime:
ret... | EllucianEthosPythonClient/WorkerThread.py | import threading
import time
import datetime
import pytz
class WorkerThreadExceptionClass(Exception):
pass
#First impleimentaion was using pref_counter
# reimplemented to use date time due to limitations
def getNextWorkerTime(lastRunTime, curTime, frequency):
retVal = lastRunTime
while retVal < curTime:
ret... | 0.334807 | 0.155527 |
from Torapi import Torapi
from Torapi.Filters import *
import time
# !! IMPORTANT: Notice the time.sleep(1) before each Get() request
t = Torapi()
# Everything is returned in JSON
# Returning a simple list
time.sleep(1)
t.Get()
time.sleep(1)
t.List().Get()
# Searches
# Simple Torrent search
time.sleep(1)
t.Search... | torapi_test.py | from Torapi import Torapi
from Torapi.Filters import *
import time
# !! IMPORTANT: Notice the time.sleep(1) before each Get() request
t = Torapi()
# Everything is returned in JSON
# Returning a simple list
time.sleep(1)
t.Get()
time.sleep(1)
t.List().Get()
# Searches
# Simple Torrent search
time.sleep(1)
t.Search... | 0.613237 | 0.257882 |
from functools import reduce
N = int(input())
S = input()
MOD = 998244353
class ModInt:
def __init__(self, x):
self.x = x % MOD
def __str__(self):
return str(self.x)
__repr__ = __str__
def __add__(self, other):
return (
ModInt(self.x + other.x) if isinstance(ot... | agc/037/b.py | from functools import reduce
N = int(input())
S = input()
MOD = 998244353
class ModInt:
def __init__(self, x):
self.x = x % MOD
def __str__(self):
return str(self.x)
__repr__ = __str__
def __add__(self, other):
return (
ModInt(self.x + other.x) if isinstance(ot... | 0.61451 | 0.223081 |
import requests
from logging import getLogger
from dateutil.parser import parse
log = getLogger(__name__)
class ApiException(Exception):
""" Error, raised by API wrapper """
class MissingProperty(ApiException):
""" API object is missing property"""
def __str__(self):
return 'API object {0} is m... | copydog/api/base.py | import requests
from logging import getLogger
from dateutil.parser import parse
log = getLogger(__name__)
class ApiException(Exception):
""" Error, raised by API wrapper """
class MissingProperty(ApiException):
""" API object is missing property"""
def __str__(self):
return 'API object {0} is m... | 0.580233 | 0.127517 |
import numpy as np
from src import utils
class Robot:
MAX_LIN_ACC = 1.0
MAX_ANG_ACC = 1.0
MAX_V = 0.5
MIN_V = 0.0
MAX_OMEGA = 0.5
MIN_OMEGA = -0.5
@classmethod
def T(cls, theta, omega, delta):
"""
Parameters:
----------
theta: float
curre... | src/robot.py | import numpy as np
from src import utils
class Robot:
MAX_LIN_ACC = 1.0
MAX_ANG_ACC = 1.0
MAX_V = 0.5
MIN_V = 0.0
MAX_OMEGA = 0.5
MIN_OMEGA = -0.5
@classmethod
def T(cls, theta, omega, delta):
"""
Parameters:
----------
theta: float
curre... | 0.924073 | 0.724212 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | platipy/imaging/tests/test_cardiac.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | 0.837155 | 0.472562 |
from pathlib import Path
import pandas as pd
import mysql.connector as connector
targets = [Path("data/external/mobile-phone-usage.csv"),
Path("data/external/world-happiness-report.csv"),
Path("data/external/freedom-of-speech.csv")]
datasets = [pd.read_csv(target, encoding="utf-8") f... | src/data-cleaning/clean-externals.py | from pathlib import Path
import pandas as pd
import mysql.connector as connector
targets = [Path("data/external/mobile-phone-usage.csv"),
Path("data/external/world-happiness-report.csv"),
Path("data/external/freedom-of-speech.csv")]
datasets = [pd.read_csv(target, encoding="utf-8") f... | 0.545044 | 0.300611 |
import pandas as pd
import tensorflow as tf
import cv2
def load_data(train_path, valid_path, test_path):
"""Returns the ILSVRC dataset as (train_x, train_y), (test_x, test_y)."""
train = pd.read_csv(train_path, header=None)
valid = pd.read_csv(valid_path, header=None)
test = pd.read_csv( test_path, he... | ILSVRC.py | import pandas as pd
import tensorflow as tf
import cv2
def load_data(train_path, valid_path, test_path):
"""Returns the ILSVRC dataset as (train_x, train_y), (test_x, test_y)."""
train = pd.read_csv(train_path, header=None)
valid = pd.read_csv(valid_path, header=None)
test = pd.read_csv( test_path, he... | 0.82478 | 0.500977 |
__author__ = '<NAME>, <NAME>, <NAME>'
__copyright__ = 'Copyright (C) 2018, Nokia'
__email__ = '<EMAIL>, <EMAIL>'
import re
from abc import abstractmethod
from moler.command import Command
class AtCommandModeNotSupported(Exception):
pass
class AtCommandFailure(Exception):
pass
class AtCmd(Command):
d... | moler/cmd/at/at.py | __author__ = '<NAME>, <NAME>, <NAME>'
__copyright__ = 'Copyright (C) 2018, Nokia'
__email__ = '<EMAIL>, <EMAIL>'
import re
from abc import abstractmethod
from moler.command import Command
class AtCommandModeNotSupported(Exception):
pass
class AtCommandFailure(Exception):
pass
class AtCmd(Command):
d... | 0.449876 | 0.090253 |
from typing import Optional, Sequence, Union, TYPE_CHECKING
from command.args.base import ArgSpace, Argument
from command.args.error import ArgumentError
from command.args.namespace import Namespace
from command.args.result import DefaultResult, Result
if TYPE_CHECKING:
from data.character import Character
def ... | src/command/args/helpers.py | from typing import Optional, Sequence, Union, TYPE_CHECKING
from command.args.base import ArgSpace, Argument
from command.args.error import ArgumentError
from command.args.namespace import Namespace
from command.args.result import DefaultResult, Result
if TYPE_CHECKING:
from data.character import Character
def ... | 0.944906 | 0.581689 |
#Imports
import argparse
import numpy
from itertools import islice
#Functions
def read_in_derived_reactivities(afile):
'''Reads in a reactivity file'''
information = {}
with open(afile,'r') as f:
while True:
next_n_lines = list(islice(f, 2))
if not next_n_lines:
... | react_bins.py | #Imports
import argparse
import numpy
from itertools import islice
#Functions
def read_in_derived_reactivities(afile):
'''Reads in a reactivity file'''
information = {}
with open(afile,'r') as f:
while True:
next_n_lines = list(islice(f, 2))
if not next_n_lines:
... | 0.228501 | 0.232517 |
# Import libraries
import argparse
from sys import exit
from os.path import exists, isfile
from os import mkdir
from json import load
import pandas as pd
# Prem matrices
# https://doi.org/10.1371/journal.pcbi.1005697.s002
ifn1 = "MUestimates_all_locations_1.json"
ifn2 = "MUestimates_all_locations_2.json"
# UN ISO 3... | Pipeline/1_Prem_Matrices_to_df/Executable/prem_matrices_to_df.py | # Import libraries
import argparse
from sys import exit
from os.path import exists, isfile
from os import mkdir
from json import load
import pandas as pd
# Prem matrices
# https://doi.org/10.1371/journal.pcbi.1005697.s002
ifn1 = "MUestimates_all_locations_1.json"
ifn2 = "MUestimates_all_locations_2.json"
# UN ISO 3... | 0.400984 | 0.350338 |
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.fn as fn
import nvidia.dali.math as math
import nvidia.dali.types as types
import nvidia.dali as dali
from nvidia.dali.backend_impl import TensorListGPU
import numpy as np
from nose_utils import assert_raises
from test_utils im... | dali/test/python/test_operator_pad.py |
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.fn as fn
import nvidia.dali.math as math
import nvidia.dali.types as types
import nvidia.dali as dali
from nvidia.dali.backend_impl import TensorListGPU
import numpy as np
from nose_utils import assert_raises
from test_utils im... | 0.575469 | 0.44354 |
import humanize
from collections import defaultdict
from apps.characters.models import CharacterJournal
#creates a highcharts dict for balance at downtime for last month
def monthly_balance(characterapi):
dataset = nested_dict()
#set basics
dataset = default_chart(dataset)
dataset = timeline(dataset)
... | apps/charts/charts.py | import humanize
from collections import defaultdict
from apps.characters.models import CharacterJournal
#creates a highcharts dict for balance at downtime for last month
def monthly_balance(characterapi):
dataset = nested_dict()
#set basics
dataset = default_chart(dataset)
dataset = timeline(dataset)
... | 0.502197 | 0.318843 |
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from api.helper import json_response, json_error_response, json_400_incorrect_use
from api.sms import send_sms
from api.utils import parse_iso, random_letters, random_digits
from customer.sql import get_ranking_results
from employee.... | web/transiq/customer/booking_helper.py | from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from api.helper import json_response, json_error_response, json_400_incorrect_use
from api.sms import send_sms
from api.utils import parse_iso, random_letters, random_digits
from customer.sql import get_ranking_results
from employee.... | 0.29381 | 0.077762 |
import pytest
from zum.requests.errors import (
InvalidBodyParameterTypeError,
MissingEndpointParamsError,
)
from zum.requests.helpers import cast_parameter, cast_value, reduce_arguments
class TestReduceArguments:
def setup_method(self):
self.keys = ["first", "second", "third"]
self.short... | tests/requests/test_helpers.py | import pytest
from zum.requests.errors import (
InvalidBodyParameterTypeError,
MissingEndpointParamsError,
)
from zum.requests.helpers import cast_parameter, cast_value, reduce_arguments
class TestReduceArguments:
def setup_method(self):
self.keys = ["first", "second", "third"]
self.short... | 0.605682 | 0.588771 |
from appscale.search.protocols import search_pb2
# Max amount of time to wait for response from Solr (in seconds).
SOLR_TIMEOUT = 60
# Max amount of time to wait before commit updates (in milliseconds).
SOLR_COMMIT_WITHIN = 0
# Name of Solr configs set for appscale collections.
APPSCALE_CONFIG_SET_NAME = 'appscale_s... | SearchService2/appscale/search/constants.py | from appscale.search.protocols import search_pb2
# Max amount of time to wait for response from Solr (in seconds).
SOLR_TIMEOUT = 60
# Max amount of time to wait before commit updates (in milliseconds).
SOLR_COMMIT_WITHIN = 0
# Name of Solr configs set for appscale collections.
APPSCALE_CONFIG_SET_NAME = 'appscale_s... | 0.613121 | 0.11004 |
"""Base class for TFX nodes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
from six import with_metaclass
from typing import Any, Optional, Text
from tensorflow.python.util import deprecation # pylint: disable=g-direct-tensorflow-import
... | tfx/components/base/base_node.py | """Base class for TFX nodes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
from six import with_metaclass
from typing import Any, Optional, Text
from tensorflow.python.util import deprecation # pylint: disable=g-direct-tensorflow-import
... | 0.925584 | 0.145388 |
import pytest
import re
from ..morphophonology.fr import (
LE_LEQUEL_RE, LES_LESQUELS_RE, insert_au_du,
add_apostrophe, deduplicate_left_right_realisation,
start_with_vowel)
from ..lexicon.feature.category import CONJUNCTION
@pytest.mark.parametrize('s', [
'le',
'lequel',
pytest.mark.xfail('l... | pynlg/test/test_morphophonology_fr.py | import pytest
import re
from ..morphophonology.fr import (
LE_LEQUEL_RE, LES_LESQUELS_RE, insert_au_du,
add_apostrophe, deduplicate_left_right_realisation,
start_with_vowel)
from ..lexicon.feature.category import CONJUNCTION
@pytest.mark.parametrize('s', [
'le',
'lequel',
pytest.mark.xfail('l... | 0.645567 | 0.531453 |
import sys
import os
import pandas as pd
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QTableWidget, QDockWidget, QTextEdit, QTableWidgetItem, QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QFont
class ApvSe... | Re-write/New (QT)/qt-apv.py | import sys
import os
import pandas as pd
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QTableWidget, QDockWidget, QTextEdit, QTableWidgetItem, QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QFont
class ApvSe... | 0.139836 | 0.069101 |
from rdkit import Chem
import pandas as pd
from rdkit.Chem.rdMolDescriptors import GetMorganFingerprintAsBitVect
from rdkit.Chem.rdMolDescriptors import GetMorganFingerprint
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit.Chem.Draw import _getMorganEnv
__all__ = ['GetFoldedCircularFragment',
'GetUnfolde... | smash/fragments/circular.py | from rdkit import Chem
import pandas as pd
from rdkit.Chem.rdMolDescriptors import GetMorganFingerprintAsBitVect
from rdkit.Chem.rdMolDescriptors import GetMorganFingerprint
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit.Chem.Draw import _getMorganEnv
__all__ = ['GetFoldedCircularFragment',
'GetUnfolde... | 0.792745 | 0.461988 |
from __future__ import annotations
from typing import Union
import numpy as np
class PowerFlow:
"""Power flow."""
def __init__(
self,
components: list(int),
fully_connected: bool = False,
auto_update_values: bool = False,
single_direction: bool = True,
) -> None:... | solara/envs/wiring.py |
from __future__ import annotations
from typing import Union
import numpy as np
class PowerFlow:
"""Power flow."""
def __init__(
self,
components: list(int),
fully_connected: bool = False,
auto_update_values: bool = False,
single_direction: bool = True,
) -> None:... | 0.948322 | 0.595904 |
"""A simple mod of SkiFree"""
# Source code inspired by <NAME> at
# http://www.manning-source.com/books/sande/All_Files_By_Chapter/hw_ch10_code/skiing_game.py
# Released under the MIT license http://www.opensource.org/licenses/mit-license.php
import random
import pygame
# TODO 1) ensure always fixed number of trees... | skifree.py | """A simple mod of SkiFree"""
# Source code inspired by <NAME> at
# http://www.manning-source.com/books/sande/All_Files_By_Chapter/hw_ch10_code/skiing_game.py
# Released under the MIT license http://www.opensource.org/licenses/mit-license.php
import random
import pygame
# TODO 1) ensure always fixed number of trees... | 0.365343 | 0.281791 |
import sys
import signal
import gi
gi.require_version('Gst', '1.0')
#gi.require_version('Gtk', '4.0')
from gi.repository import GObject, Gst, GLib #, Gtk
# print('Press Ctrl+C')
# signal.pause()
# gst-launch-1.0 pulsesrc ! audioconvert ! vorbisenc ! oggmux ! filesink location=dump.ogg
# gst-launch-1.0 playbin uri=fil... | record-mic.py | import sys
import signal
import gi
gi.require_version('Gst', '1.0')
#gi.require_version('Gtk', '4.0')
from gi.repository import GObject, Gst, GLib #, Gtk
# print('Press Ctrl+C')
# signal.pause()
# gst-launch-1.0 pulsesrc ! audioconvert ! vorbisenc ! oggmux ! filesink location=dump.ogg
# gst-launch-1.0 playbin uri=fil... | 0.08429 | 0.107297 |
from utils import *
from batchscores import *
from sklearn.metrics import roc_auc_score
def get_epoch_performances_baseline_CAE(valid_loader, test_loader, device, net, normal_cls):
scores_valid, scores_labels_valid = DeepNormalityHyperspheres_BatchScores_baseline_CAE(valid_loader, device, net)
y_valid_ad = con... | epochscores.py | from utils import *
from batchscores import *
from sklearn.metrics import roc_auc_score
def get_epoch_performances_baseline_CAE(valid_loader, test_loader, device, net, normal_cls):
scores_valid, scores_labels_valid = DeepNormalityHyperspheres_BatchScores_baseline_CAE(valid_loader, device, net)
y_valid_ad = con... | 0.847306 | 0.29995 |
import numpy as np
from scipy.io import savemat, loadmat
# TODO: it does not work with regular conv2d layer
def convert_to_1bit_conv(model, folder2store):
ZeroOneWeightsDict = {}
AllParamsDict = {}
NumBinaryWeights = 0.0
Num32bitWeights = 0.0
for layer in model.layers:
# print(layer.name)
... | src/complexity_considerations_package/convert_to_1bit.py | import numpy as np
from scipy.io import savemat, loadmat
# TODO: it does not work with regular conv2d layer
def convert_to_1bit_conv(model, folder2store):
ZeroOneWeightsDict = {}
AllParamsDict = {}
NumBinaryWeights = 0.0
Num32bitWeights = 0.0
for layer in model.layers:
# print(layer.name)
... | 0.238018 | 0.458955 |
from __future__ import (absolute_import, division, generators, unicode_literals, print_function, nested_scopes,
with_statement)
import logging as log
import re
import time
import requests
from .common import MIME_JSON
from .connection_tpp_common import TPPCommonConnection, URLS
from .errors ... | vcert/connection_tpp.py |
from __future__ import (absolute_import, division, generators, unicode_literals, print_function, nested_scopes,
with_statement)
import logging as log
import re
import time
import requests
from .common import MIME_JSON
from .connection_tpp_common import TPPCommonConnection, URLS
from .errors ... | 0.573201 | 0.074939 |
from __future__ import absolute_import
from . import GithubEvent
"""
Triggered when a pull request is assigned, unassigned, labeled, unlabeled, opened,
edited, closed, reopened, or synchronized.
Also triggered when a pull request review is requested, or when a review request is removed.
"""
class PullRequestEvent(Gi... | captain_hook/services/github/events/pull_request.py | from __future__ import absolute_import
from . import GithubEvent
"""
Triggered when a pull request is assigned, unassigned, labeled, unlabeled, opened,
edited, closed, reopened, or synchronized.
Also triggered when a pull request review is requested, or when a review request is removed.
"""
class PullRequestEvent(Gi... | 0.335351 | 0.193262 |
import typing
import flask
import cauldron
from cauldron import environ
from cauldron.cli import commander
from cauldron.environ.response import Response
from cauldron.runner import redirection
from cauldron.ui import arguments
from cauldron.ui import configs as ui_configs
ParsedCommand = typing.NamedTuple('COMMAND_... | cauldron/ui/routes/apis/executions/runner.py | import typing
import flask
import cauldron
from cauldron import environ
from cauldron.cli import commander
from cauldron.environ.response import Response
from cauldron.runner import redirection
from cauldron.ui import arguments
from cauldron.ui import configs as ui_configs
ParsedCommand = typing.NamedTuple('COMMAND_... | 0.547222 | 0.183484 |
import os, errno
import re
import docker
import yaml
from contextlib import contextmanager
from build_db import returnModels
from PyInquirer import Validator, ValidationError
CONFIG = yaml.load(open('configurations/config.yaml', 'r'))
sagemaker_role = CONFIG['roles'][0]['role']
sagemaker_bucket = CONFIG['descriptio... | utils.py | import os, errno
import re
import docker
import yaml
from contextlib import contextmanager
from build_db import returnModels
from PyInquirer import Validator, ValidationError
CONFIG = yaml.load(open('configurations/config.yaml', 'r'))
sagemaker_role = CONFIG['roles'][0]['role']
sagemaker_bucket = CONFIG['descriptio... | 0.188959 | 0.124266 |
import os
import sys
import six
from collections.abc import Mapping
from collections import deque
from ppdet.core.workspace import register, serializable
from ppdet.utils.logger import setup_logger
from ppdet.data.reader import BaseDataLoader, Compose
from paddle.fluid.dataloader.collate import default_collate_fn
impo... | modules/video/multiple_object_tracking/jde_darknet53/dataset.py | import os
import sys
import six
from collections.abc import Mapping
from collections import deque
from ppdet.core.workspace import register, serializable
from ppdet.utils.logger import setup_logger
from ppdet.data.reader import BaseDataLoader, Compose
from paddle.fluid.dataloader.collate import default_collate_fn
impo... | 0.444083 | 0.120568 |
import os
import numpy as np
import sys
import lstm
def combinador1(clases):
cw, cc = clases.shape
acum = np.empty_like (clases[0])
out = ""
LSTM = lstm.LSTM_Pred('')
for i in range(0,cw):
maxj = 0
for j in range(0,cc):
if clases[i][maxj]<clases[i][j]:
... | tp4/entrega/combinacion.py | import os
import numpy as np
import sys
import lstm
def combinador1(clases):
cw, cc = clases.shape
acum = np.empty_like (clases[0])
out = ""
LSTM = lstm.LSTM_Pred('')
for i in range(0,cw):
maxj = 0
for j in range(0,cc):
if clases[i][maxj]<clases[i][j]:
... | 0.073746 | 0.102439 |
from simtk import openmm, unit
from simtk.openmm import app
from openmmtools import integrators
from openmmtools.testsystems import WaterBox
import sys
sys.path.append("/Users/rossg/Work/saltswap/saltswap")
size = 25.0*unit.angstrom # The length of the edges of the water box.
temperature = 300*unit.kelvin
pressur... | saltswap/tests/Development/vV_minimal.py | from simtk import openmm, unit
from simtk.openmm import app
from openmmtools import integrators
from openmmtools.testsystems import WaterBox
import sys
sys.path.append("/Users/rossg/Work/saltswap/saltswap")
size = 25.0*unit.angstrom # The length of the edges of the water box.
temperature = 300*unit.kelvin
pressur... | 0.482429 | 0.376537 |
from django.contrib.auth.models import User
from django.test import TestCase
from users.models import photo_upload, UserAddressModel, UserProfileModel
class TestUsers(TestCase):
"""UnitTest for users models"""
def test_photo_name_unique(self):
"""test for image upload unique id generator"""
... | users/tests/test_models.py | from django.contrib.auth.models import User
from django.test import TestCase
from users.models import photo_upload, UserAddressModel, UserProfileModel
class TestUsers(TestCase):
"""UnitTest for users models"""
def test_photo_name_unique(self):
"""test for image upload unique id generator"""
... | 0.646683 | 0.341555 |
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.forms import widgets
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
... | accounts/forms.py |
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.forms import widgets
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
... | 0.458349 | 0.129238 |
import numpy as np
from allennlp.data import Token, Vocabulary
from allennlp.data.fields import TextField, ListField, ArrayField, SpanField
from allennlp.data.token_indexers import SingleIdTokenIndexer
from allennlp.data.tokenizers import WordTokenizer
from allennlp.data.tokenizers.word_splitter import JustSpace... | tests/test_dict_field.py | import numpy as np
from allennlp.data import Token, Vocabulary
from allennlp.data.fields import TextField, ListField, ArrayField, SpanField
from allennlp.data.token_indexers import SingleIdTokenIndexer
from allennlp.data.tokenizers import WordTokenizer
from allennlp.data.tokenizers.word_splitter import JustSpace... | 0.520496 | 0.417212 |
import sys
import flask
import json # it MUST be included after flask!
import heartex
import requests
import pandas as pd
from flask import request
from utils import exception_treatment, answer, log_config, log
# init
config_path = sys.argv[1] if len(sys.argv) == 2 else 'config.json'
c = json.load(open(config_path))... | src/service.py | import sys
import flask
import json # it MUST be included after flask!
import heartex
import requests
import pandas as pd
from flask import request
from utils import exception_treatment, answer, log_config, log
# init
config_path = sys.argv[1] if len(sys.argv) == 2 else 'config.json'
c = json.load(open(config_path))... | 0.476336 | 0.197251 |
from PyQt5 import Qt
import pkg_resources
from . import device_widget
from . import status_widget
from ..simple_rpc import rpc_client
from .. import util
class MicroscopeWidget(device_widget.DeviceWidget):
PROPERTY_ROOT = 'scope.'
PROPERTIES = [
# tuple contains: property, type, and zero or more args... | scope/gui/microscope_widget.py |
from PyQt5 import Qt
import pkg_resources
from . import device_widget
from . import status_widget
from ..simple_rpc import rpc_client
from .. import util
class MicroscopeWidget(device_widget.DeviceWidget):
PROPERTY_ROOT = 'scope.'
PROPERTIES = [
# tuple contains: property, type, and zero or more args... | 0.349755 | 0.104798 |
import asyncio
import mimetypes
import os
import sys
from functools import partial
from pathlib import Path
from typing import Optional
import aiohttp
import discogs_client
import json5
import music_tag
from music_tag import AudioFile
from peewee import IntegrityError, OperationalError
from jukebox import APP_ROOT, C... | jukebox/scan_files.py | import asyncio
import mimetypes
import os
import sys
from functools import partial
from pathlib import Path
from typing import Optional
import aiohttp
import discogs_client
import json5
import music_tag
from music_tag import AudioFile
from peewee import IntegrityError, OperationalError
from jukebox import APP_ROOT, C... | 0.334698 | 0.117826 |
import unittest
from logrec.dataprep.preprocessors import loggable
from logrec.dataprep.model.chars import NewLine
from logrec.dataprep.model.containers import MultilineComment, StringLiteral, SplitContainer
from logrec.dataprep.model.logging import LoggableBlock
class MarkLogTest(unittest.TestCase):
def test_ne... | tests/dataprep/preprocessors/loggable.py | import unittest
from logrec.dataprep.preprocessors import loggable
from logrec.dataprep.model.chars import NewLine
from logrec.dataprep.model.containers import MultilineComment, StringLiteral, SplitContainer
from logrec.dataprep.model.logging import LoggableBlock
class MarkLogTest(unittest.TestCase):
def test_ne... | 0.414899 | 0.195383 |
import json
import inspect
from functools import wraps
from warnings import warn
from client_encryption.field_level_encryption_config import FieldLevelEncryptionConfig
from client_encryption.session_key_params import SessionKeyParams
from client_encryption.field_level_encryption import encrypt_payload, decrypt_payload
... | client_encryption/api_encryption.py | import json
import inspect
from functools import wraps
from warnings import warn
from client_encryption.field_level_encryption_config import FieldLevelEncryptionConfig
from client_encryption.session_key_params import SessionKeyParams
from client_encryption.field_level_encryption import encrypt_payload, decrypt_payload
... | 0.620047 | 0.064153 |
import pytest
import json
from scripts import update_snippets
from capdb.models import Snippet
@pytest.mark.django_db(databases=['capdb'])
def test_map_numbers(case_factory, jurisdiction):
[case_factory(jurisdiction=jurisdiction) for i in range(3)]
update_snippets.update_map_numbers()
snippet = Snippet.obj... | capstone/scripts/tests/test_snippet_updaters.py | import pytest
import json
from scripts import update_snippets
from capdb.models import Snippet
@pytest.mark.django_db(databases=['capdb'])
def test_map_numbers(case_factory, jurisdiction):
[case_factory(jurisdiction=jurisdiction) for i in range(3)]
update_snippets.update_map_numbers()
snippet = Snippet.obj... | 0.319121 | 0.451387 |
import contextlib
import os
import docker.errors
import pytest
import tempfile
from ebonite.build.builder.base import use_local_installation
from ebonite.build.builder.docker_builder import _DockerfileGenerator, DockerBuilder, create_docker_client
from tests.build.conftest import has_docker
from tests.build.builder.t... | tests/build/builder/test_docker.py | import contextlib
import os
import docker.errors
import pytest
import tempfile
from ebonite.build.builder.base import use_local_installation
from ebonite.build.builder.docker_builder import _DockerfileGenerator, DockerBuilder, create_docker_client
from tests.build.conftest import has_docker
from tests.build.builder.t... | 0.204025 | 0.061312 |
from __future__ import absolute_import
from __future__ import print_function
import sys, numpy, time
from pyFAI.utils import mathutil
from . import utilstest
import fabio, pyopencl
from pylab import *
print("#"*50)
pyFAI = sys.modules["pyFAI"]
from pyFAI import splitBBox
#splitBBox = sys.modules["pyFAI.splitBBox"]
ai... | sandbox/profile_ocl_lut.py |
from __future__ import absolute_import
from __future__ import print_function
import sys, numpy, time
from pyFAI.utils import mathutil
from . import utilstest
import fabio, pyopencl
from pylab import *
print("#"*50)
pyFAI = sys.modules["pyFAI"]
from pyFAI import splitBBox
#splitBBox = sys.modules["pyFAI.splitBBox"]
ai... | 0.357792 | 0.24947 |
import requests
from django.conf import settings
def _get_genres_from_ids(url, ids, fields, headers):
r = requests.get(f'{url}/genres/{ids}/?fields={fields}', headers=headers)
return r.json()
class BaseAdapter(object):
def __init__(self):
self.url = f"{settings.IGDB_API_URL}"
self.headers... | game_requests/adapter.py | import requests
from django.conf import settings
def _get_genres_from_ids(url, ids, fields, headers):
r = requests.get(f'{url}/genres/{ids}/?fields={fields}', headers=headers)
return r.json()
class BaseAdapter(object):
def __init__(self):
self.url = f"{settings.IGDB_API_URL}"
self.headers... | 0.288168 | 0.050471 |
from __future__ import absolute_import, division, print_function, unicode_literals
from braintree.test.nonces import Nonces
import mock
from gratipay.testing.billing import BillingHarness
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
class TestRoutes(Bi... | tests/py/test_routes.py | from __future__ import absolute_import, division, print_function, unicode_literals
from braintree.test.nonces import Nonces
import mock
from gratipay.testing.billing import BillingHarness
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
class TestRoutes(Bi... | 0.594316 | 0.255802 |
import importlib
import inspect
import unittest
from dataclasses import field, dataclass
from outlier_benchmark.data_collection import DatasetCollection
from outlier_benchmark.datasets import __all__ as all_datasets
from outlier_benchmark.datasets.base import BaseDataset
class TestDatasetCollection(unittest.TestCase... | tests/test_dataset_collection.py | import importlib
import inspect
import unittest
from dataclasses import field, dataclass
from outlier_benchmark.data_collection import DatasetCollection
from outlier_benchmark.datasets import __all__ as all_datasets
from outlier_benchmark.datasets.base import BaseDataset
class TestDatasetCollection(unittest.TestCase... | 0.790894 | 0.657442 |
# Import Python base libraries
import os
import json
import yaml
import pandas as pd
# Read list (of dict) from JSON file
def get_list_from_json(json_path:str, encoding:str="utf-8") -> list:
result = []
try:
with open(json_path, mode="r", encoding=encoding) as file:
result = json.load(... | code/DataProcessor/src/util/files.py | # Import Python base libraries
import os
import json
import yaml
import pandas as pd
# Read list (of dict) from JSON file
def get_list_from_json(json_path:str, encoding:str="utf-8") -> list:
result = []
try:
with open(json_path, mode="r", encoding=encoding) as file:
result = json.load(... | 0.265119 | 0.146148 |
import numpy as np
import torch
import imageio
from a2c_ppo_acktr import utils
from a2c_ppo_acktr.envs import make_vec_envs
def get_obs_rms(env):
return getattr(utils.get_vec_normalize(env), 'obs_rms', None)
def make_movie(movie_path, frames):
height, width, layers = frames[0].shape
video = cv2.VideoWri... | pytorch-ppo/evaluation.py | import numpy as np
import torch
import imageio
from a2c_ppo_acktr import utils
from a2c_ppo_acktr.envs import make_vec_envs
def get_obs_rms(env):
return getattr(utils.get_vec_normalize(env), 'obs_rms', None)
def make_movie(movie_path, frames):
height, width, layers = frames[0].shape
video = cv2.VideoWri... | 0.538741 | 0.331336 |
from .color2float import *
def color2gray(C, weight=(1/3, 1/3, 1/3), dim=-1):
"""
Converts the given color in grayscale using the specified weights
Parameters
----------
C : Tensor
the (3,W,H,) or (N,3,) RGB color tensor
weight : list or tuple (optional)
the weighting factors ... | ACME/color/color2gray.py | from .color2float import *
def color2gray(C, weight=(1/3, 1/3, 1/3), dim=-1):
"""
Converts the given color in grayscale using the specified weights
Parameters
----------
C : Tensor
the (3,W,H,) or (N,3,) RGB color tensor
weight : list or tuple (optional)
the weighting factors ... | 0.958991 | 0.688301 |
from mythic_payloadtype_container.MythicCommandBase import *
import json
class RunArguments(TaskArguments):
def __init__(self, command_line, **kwargs):
super().__init__(command_line, **kwargs)
self.args = [
CommandParameter(
name="executable",
cli_name=... | Payload_Type/apollo/mythic/agent_functions/run.py | from mythic_payloadtype_container.MythicCommandBase import *
import json
class RunArguments(TaskArguments):
def __init__(self, command_line, **kwargs):
super().__init__(command_line, **kwargs)
self.args = [
CommandParameter(
name="executable",
cli_name=... | 0.512205 | 0.13109 |
from netCDF4 import Dataset
import numpy as np
#-------------------------------------------------------------------------------
def average_variational_strains():
gridSizes = [2562, 10242, 40962, 163842]
operatorMethods = ["wachspress","pwl","weakwachs"]
for operatorMethod in operatorMethods:
... | components/mpas-seaice/testing_and_setup/testcases/spherical_operators/strain/average_variational_strains.py | from netCDF4 import Dataset
import numpy as np
#-------------------------------------------------------------------------------
def average_variational_strains():
gridSizes = [2562, 10242, 40962, 163842]
operatorMethods = ["wachspress","pwl","weakwachs"]
for operatorMethod in operatorMethods:
... | 0.321034 | 0.350894 |
import pexpect
import time
from datetime import datetime
uuid_pre = "F000"
uuid_pos = "-0451-4000-B000-000000000000"
#format: handle = [data, config]
temp_uuid = ["AA01", "AA02"]
move_uuid = ["AA81", "AA82"]
humd_uuid = ["AA21", "AA22"]
baro_uuid = ["AA41", "AA42"]
opti_uuid = ["AA71", "AA72"]
leds_uuid = ["AA65", "A... | sensor.py |
import pexpect
import time
from datetime import datetime
uuid_pre = "F000"
uuid_pos = "-0451-4000-B000-000000000000"
#format: handle = [data, config]
temp_uuid = ["AA01", "AA02"]
move_uuid = ["AA81", "AA82"]
humd_uuid = ["AA21", "AA22"]
baro_uuid = ["AA41", "AA42"]
opti_uuid = ["AA71", "AA72"]
leds_uuid = ["AA65", "A... | 0.227298 | 0.235262 |
import cv2
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
from tensorflow.keras.models import load_model
from data_processing import get_test_data, imgappend, getYimg, psnr
from model import RDN, L1_loss
''' Set parameters '''
scale = 2
size = 32 # Input size
aug_num = 4 # Number of... | test.py | import cv2
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
from tensorflow.keras.models import load_model
from data_processing import get_test_data, imgappend, getYimg, psnr
from model import RDN, L1_loss
''' Set parameters '''
scale = 2
size = 32 # Input size
aug_num = 4 # Number of... | 0.548432 | 0.624837 |
import pickle as pickle
import gzip
import filecmp
import json
import os
import shutil
import sys
import time
from svviz import app
from svviz import utilities
class MockArgs(object):
def __getattr__(self, attr):
return None
def run():
timings = {}
for testName in ["mei", "inv", "ins_moleculo",... | resources/usr/local/lib/python2.7/dist-packages/svviz/rendertest.py | import pickle as pickle
import gzip
import filecmp
import json
import os
import shutil
import sys
import time
from svviz import app
from svviz import utilities
class MockArgs(object):
def __getattr__(self, attr):
return None
def run():
timings = {}
for testName in ["mei", "inv", "ins_moleculo",... | 0.114084 | 0.138928 |
import torch
import torch.nn.functional as F
from layers.activation import DisentangledSelfAttention
from torchfm.layer import FeaturesEmbedding, FeaturesLinear, MultiLayerPerceptron
class DESTINE(torch.nn.Module):
def __init__(
self, field_dims, embed_dim, atten_embed_dim, num_heads,
... | models/DESTINE.py | import torch
import torch.nn.functional as F
from layers.activation import DisentangledSelfAttention
from torchfm.layer import FeaturesEmbedding, FeaturesLinear, MultiLayerPerceptron
class DESTINE(torch.nn.Module):
def __init__(
self, field_dims, embed_dim, atten_embed_dim, num_heads,
... | 0.916232 | 0.384825 |
from sonic_py_common.interface import get_interface_table_name, get_intf_longname, VLAN_SUB_INTERFACE_SEPARATOR
from sonic_py_common.multi_asic import DEFAULT_NAMESPACE
from dump.match_infra import MatchRequest
from dump.helper import create_template_dict, handle_error
from dump.match_helper import fetch_port_oid, fetc... | dump/plugins/interface.py | from sonic_py_common.interface import get_interface_table_name, get_intf_longname, VLAN_SUB_INTERFACE_SEPARATOR
from sonic_py_common.multi_asic import DEFAULT_NAMESPACE
from dump.match_infra import MatchRequest
from dump.helper import create_template_dict, handle_error
from dump.match_helper import fetch_port_oid, fetc... | 0.380299 | 0.088072 |
import asyncio
import atexit
import concurrent
import logging
import queue
import threading
import time
import typing as t
from funcx.sdk.asynchronous.funcx_future import FuncXFuture
from funcx.sdk.asynchronous.ws_polling_task import WebSocketPollingTask
from funcx.sdk.client import FuncXClient
log = logging.getLogge... | funcx_sdk/funcx/sdk/executor.py | import asyncio
import atexit
import concurrent
import logging
import queue
import threading
import time
import typing as t
from funcx.sdk.asynchronous.funcx_future import FuncXFuture
from funcx.sdk.asynchronous.ws_polling_task import WebSocketPollingTask
from funcx.sdk.client import FuncXClient
log = logging.getLogge... | 0.687105 | 0.126003 |
import warnings
warnings.simplefilter(action="ignore")
import pandas as pd
import numpy as np
from scipy import sparse
import seaborn as sns
import matplotlib.pyplot as plt
import pickle
import textwrap
import re
import sys, os
import utils
sys.path.append(os.path.abspath(os.path.join("libs/cidre")))
from cidre impo... | workflow/plot-citation-net-cartels.py |
import warnings
warnings.simplefilter(action="ignore")
import pandas as pd
import numpy as np
from scipy import sparse
import seaborn as sns
import matplotlib.pyplot as plt
import pickle
import textwrap
import re
import sys, os
import utils
sys.path.append(os.path.abspath(os.path.join("libs/cidre")))
from cidre impo... | 0.55447 | 0.268207 |
import os
import time
import speech_recognition as sr
from fuzzywuzzy import fuzz
import pyttsx3
import datetime
import pyjokes
import os
import keyboard
import wikipedia
import random
# настройки
opts = {
"alias": ('кеша', 'кеш', 'инокентий', 'иннокентий', 'кишун', 'киш',
'кишаня', 'к... | jarvis.py | import os
import time
import speech_recognition as sr
from fuzzywuzzy import fuzz
import pyttsx3
import datetime
import pyjokes
import os
import keyboard
import wikipedia
import random
# настройки
opts = {
"alias": ('кеша', 'кеш', 'инокентий', 'иннокентий', 'кишун', 'киш',
'кишаня', 'к... | 0.07179 | 0.216105 |
import unittest
import os
import tempfile
import shutil
from py_fpff import FPFF, SectionType
class FPFFTest(unittest.TestCase):
"""FPFF test cases.
"""
def setUp(self):
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.test_dir)
def test_empty(self):
... | tests/test_fpff.py | import unittest
import os
import tempfile
import shutil
from py_fpff import FPFF, SectionType
class FPFFTest(unittest.TestCase):
"""FPFF test cases.
"""
def setUp(self):
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.test_dir)
def test_empty(self):
... | 0.303009 | 0.615203 |
import heapq
import logging
from . import feeders
from .exc import RequiredToolNotFound
from .diff import diff, reverse_unified_diff, diff_split_lines
from .excludes import command_excluded
logger = logging.getLogger(__name__)
class Difference(object):
def __init__(
self,
unified_diff,
... | venv/lib/python3.7/site-packages/diffoscope/difference.py |
import heapq
import logging
from . import feeders
from .exc import RequiredToolNotFound
from .diff import diff, reverse_unified_diff, diff_split_lines
from .excludes import command_excluded
logger = logging.getLogger(__name__)
class Difference(object):
def __init__(
self,
unified_diff,
... | 0.645902 | 0.131703 |
import asyncio
import json
import logging
import time
from urllib.parse import urlencode
import aiohttp
import async_timeout
DEFAULT_TIMEOUT = 10
API_ENDPOINT = 'https://api.ambiclimate.com/api/v1/'
_LOGGER = logging.getLogger(__name__)
class AmbiclimateConnection:
"""Class to comunicate with the Ambiclimate a... | ambiclimate/__init__.py | import asyncio
import json
import logging
import time
from urllib.parse import urlencode
import aiohttp
import async_timeout
DEFAULT_TIMEOUT = 10
API_ENDPOINT = 'https://api.ambiclimate.com/api/v1/'
_LOGGER = logging.getLogger(__name__)
class AmbiclimateConnection:
"""Class to comunicate with the Ambiclimate a... | 0.734976 | 0.087525 |
r"""Simple tool for computing $L$-scores from Wikipron data.
Wikipron contains multilingual pronunciation data mined from Wiktionary.
The project can be found here: https://github.com/kylebgorman/wikipron.
Produces tab-separated file with the following format:
- Language code
- Language name.
- Type of the lex... | homophonous_logography/lexical/wikipron_lscores_main.py |
r"""Simple tool for computing $L$-scores from Wikipron data.
Wikipron contains multilingual pronunciation data mined from Wiktionary.
The project can be found here: https://github.com/kylebgorman/wikipron.
Produces tab-separated file with the following format:
- Language code
- Language name.
- Type of the lex... | 0.83056 | 0.393968 |
import logging
import logging.handlers
import os
from pathlib import Path
import pandas as pd
from loader import engine
from npl_planner.utilities.utils import timestamp
class LogDBHandler(logging.Handler):
"""Customized logging handler that puts logs to the database
"""
def emit(self, record):
... | utilities/logger.py | import logging
import logging.handlers
import os
from pathlib import Path
import pandas as pd
from loader import engine
from npl_planner.utilities.utils import timestamp
class LogDBHandler(logging.Handler):
"""Customized logging handler that puts logs to the database
"""
def emit(self, record):
... | 0.521959 | 0.085633 |
import copy
import numpy as np
from torchvision.transforms import Compose
from eisen.transforms import FilterFields, StackImagesChannelwise, CreateConstantFlags
class ModCreateConstantFlags:
"""Transform to create new fields or modify existing keys in the data dictionary containing.
"""
def __init__(se... | covid_challenge/transforms/imaging.py | import copy
import numpy as np
from torchvision.transforms import Compose
from eisen.transforms import FilterFields, StackImagesChannelwise, CreateConstantFlags
class ModCreateConstantFlags:
"""Transform to create new fields or modify existing keys in the data dictionary containing.
"""
def __init__(se... | 0.725065 | 0.677474 |
from ares.Lib.AresImports import requires
import traceback
class AresNeo4j(object):
"""
:category: Connector
:rubric: PY
:type: Class
:dsc:
:link Documentation: https://neo4j.com/developer/python/
https://community.neo4j.com/?_ga=2.69585106.394662973.1539480121-615400289.1539480121
"... | Lib/connectors/dbs/AresDbNeo4j.py |
from ares.Lib.AresImports import requires
import traceback
class AresNeo4j(object):
"""
:category: Connector
:rubric: PY
:type: Class
:dsc:
:link Documentation: https://neo4j.com/developer/python/
https://community.neo4j.com/?_ga=2.69585106.394662973.1539480121-615400289.1539480121
"... | 0.421195 | 0.141875 |
import array
class Heap:
def __init__(self):
self.pq = array.array('i', [-1])
self.qp = array.array('i', [-1])
self.keys = array.array('f', [-1])
self.elements = [None]
self.N = 0
self.I = 0
def insert(self, key, element):
self.N += 1
se... | heap.py |
import array
class Heap:
def __init__(self):
self.pq = array.array('i', [-1])
self.qp = array.array('i', [-1])
self.keys = array.array('f', [-1])
self.elements = [None]
self.N = 0
self.I = 0
def insert(self, key, element):
self.N += 1
se... | 0.326057 | 0.376795 |
# Copyright 2017 Johns Hopkins University (<NAME>)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""End-to-end speech recognition model decoding script."""
import configargparse
import logging
import os
import random
import sys
import numpy as np
from espnet.utils.cli_utils import strtobool
# NOTE: ... | espnet/bin/asr_recog.py |
# Copyright 2017 Johns Hopkins University (<NAME>)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""End-to-end speech recognition model decoding script."""
import configargparse
import logging
import os
import random
import sys
import numpy as np
from espnet.utils.cli_utils import strtobool
# NOTE: ... | 0.572842 | 0.093099 |
import base64
import json
import mimetypes
import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from itertools import chain
from typing import TYPE_CHECKING, Any, AsyncIterable, Dict, List, Optional, Union
from xml.etree import ElementTree
from httpx import URL, AsyncClient
from pydanti... | aioaws/s3.py | import base64
import json
import mimetypes
import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from itertools import chain
from typing import TYPE_CHECKING, Any, AsyncIterable, Dict, List, Optional, Union
from xml.etree import ElementTree
from httpx import URL, AsyncClient
from pydanti... | 0.775775 | 0.123471 |
import pytest
from yagup import GitURL, InvalidURL
TESTDATA_GITURL_VALID = [
(
"https://github.com/kinkerl/glowing-octo-succotash.git",
GitURL(
scheme="https",
host="github.com",
path="kinkerl/glowing-octo-succotash.git",
),
),
(
"https:... | yagup/test/test_parse.py | import pytest
from yagup import GitURL, InvalidURL
TESTDATA_GITURL_VALID = [
(
"https://github.com/kinkerl/glowing-octo-succotash.git",
GitURL(
scheme="https",
host="github.com",
path="kinkerl/glowing-octo-succotash.git",
),
),
(
"https:... | 0.319227 | 0.435962 |
import threading
import queue
import logging
import os.path
from typing import Optional
# pylint: disable=E0401
import hexchat
from auto_xdcc.packlist_item import PacklistItem
from auto_xdcc.util import is_modified_filename
DOWNLOAD_ABORT = -1
DOWNLOAD_AWAITING = 0
DOWNLOAD_REQUEST = 1
DOWNLOAD_CONNECT = 2
DOWNLOAD_... | src/auto_xdcc/download_manager.py | import threading
import queue
import logging
import os.path
from typing import Optional
# pylint: disable=E0401
import hexchat
from auto_xdcc.packlist_item import PacklistItem
from auto_xdcc.util import is_modified_filename
DOWNLOAD_ABORT = -1
DOWNLOAD_AWAITING = 0
DOWNLOAD_REQUEST = 1
DOWNLOAD_CONNECT = 2
DOWNLOAD_... | 0.597725 | 0.071009 |
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.signals import pre_save
from django.dispatch import receiver
from favorite_things.apps.favorite.models import AuditLog, Favorite, Category
@receiver(pre_save, sender=Favorite) # noqa: C901
def audit_log(sender, instance, **kwargs):
"""
... | server/favorite_things/apps/favorite/signals.py | from django.core.exceptions import ObjectDoesNotExist
from django.db.models.signals import pre_save
from django.dispatch import receiver
from favorite_things.apps.favorite.models import AuditLog, Favorite, Category
@receiver(pre_save, sender=Favorite) # noqa: C901
def audit_log(sender, instance, **kwargs):
"""
... | 0.456168 | 0.111096 |
__author__ = 'api.jscudder (<NAME>)'
import re
import httplib
import urllib
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree i... | libs/external_libs/gdata.py-1.0.13/src/gdata/service.py | __author__ = 'api.jscudder (<NAME>)'
import re
import httplib
import urllib
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree i... | 0.68056 | 0.14774 |
import random
import requests
import urllib.parse
import datetime
import hashlib
from random import Random
from bs4 import BeautifulSoup
from . import conf
def get_sign(data_dict, key):
"""
签名函数
:param data_dict: 需要签名的参数,格式为字典
:param key: 密钥 ,即上面的API_KEY
:return: 字符串
"""
params_list = sort... | WeChatPayment.py | import random
import requests
import urllib.parse
import datetime
import hashlib
from random import Random
from bs4 import BeautifulSoup
from . import conf
def get_sign(data_dict, key):
"""
签名函数
:param data_dict: 需要签名的参数,格式为字典
:param key: 密钥 ,即上面的API_KEY
:return: 字符串
"""
params_list = sort... | 0.123128 | 0.117953 |