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 base64
import os
import sqlite3
from html import escape
from scripts.ilapfuncs import is_platform_windows, open_sqlite_db_readonly
from scripts.plugin_base import ArtefactPlugin
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc
from scripts import artifact_report
is_wi... | scripts/artifacts/appicons.py | import base64
import os
import sqlite3
from html import escape
from scripts.ilapfuncs import is_platform_windows, open_sqlite_db_readonly
from scripts.plugin_base import ArtefactPlugin
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc
from scripts import artifact_report
is_wi... | 0.377885 | 0.046249 |
from collections import defaultdict, OrderedDict
from typing import Any, Dict, List, Tuple
import tqdm
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import cv_lib.distributed.utils as dist_utils
import cv_lib.metrics as metrics
from vit_mutual.loss import Loss
from vit_mutual.utils impor... | vit_mutual/eval/evaluation.py | from collections import defaultdict, OrderedDict
from typing import Any, Dict, List, Tuple
import tqdm
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import cv_lib.distributed.utils as dist_utils
import cv_lib.metrics as metrics
from vit_mutual.loss import Loss
from vit_mutual.utils impor... | 0.953891 | 0.304701 |
from event_testing.resolver import SingleSimResolver
from event_testing.results import TestResult
from interactions.base.immediate_interaction import ImmediateSuperInteraction
from interactions.base.super_interaction import SuperInteraction
from ui.ui_dialog import UiDialogOkCancel
import interactions
class GenericCho... | Scripts/simulation/interactions/generic_affordance_chooser.py | from event_testing.resolver import SingleSimResolver
from event_testing.results import TestResult
from interactions.base.immediate_interaction import ImmediateSuperInteraction
from interactions.base.super_interaction import SuperInteraction
from ui.ui_dialog import UiDialogOkCancel
import interactions
class GenericCho... | 0.603114 | 0.279159 |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import threading
try:
# Python 3
import queue
except ImportError:
# Python 2
import Queue as queue
import tweepy.auth
from tweepy.streaming import StreamListener, Stream
from tweepy.auth import OAuthHandler
import j... | jubakit/loader/twitter.py |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import threading
try:
# Python 3
import queue
except ImportError:
# Python 2
import Queue as queue
import tweepy.auth
from tweepy.streaming import StreamListener, Stream
from tweepy.auth import OAuthHandler
import j... | 0.718989 | 0.088229 |
import itertools
import portion
import pendulum as pdl
from CacheIntervals.utils import flatten
from CacheIntervals.Intervals import po2pd, pd2po
class RecordIntervals:
'''
The memoisation of time series involve:
1. a persistence of all intervals calculated
2. a calculation of the overlap of any new in... | CacheIntervals/RecordInterval.py | import itertools
import portion
import pendulum as pdl
from CacheIntervals.utils import flatten
from CacheIntervals.Intervals import po2pd, pd2po
class RecordIntervals:
'''
The memoisation of time series involve:
1. a persistence of all intervals calculated
2. a calculation of the overlap of any new in... | 0.670069 | 0.479382 |
import pygame, sys, time
from pygame.locals import *
# Set up pygame.
pygame.init()
# Set up the window.
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Animation')
# Set up direction variable
DOWNLEFT = 'downleft'
DOWNRIGHT... | Invent Your Own Computer Games with Python/ch18_animating_graphics/animation.py | import pygame, sys, time
from pygame.locals import *
# Set up pygame.
pygame.init()
# Set up the window.
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Animation')
# Set up direction variable
DOWNLEFT = 'downleft'
DOWNRIGHT... | 0.311008 | 0.185523 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",... | django_project/django_project/settings.py |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",... | 0.369429 | 0.124905 |
import csv
import json
import os
import re
from django import forms
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage as storage
from django.utils.text import slugify
from pyxform.... | keep_backend/repos/forms.py | import csv
import json
import os
import re
from django import forms
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage as storage
from django.utils.text import slugify
from pyxform.... | 0.47244 | 0.147248 |
from django.conf.urls import url, include
from . import views
from rest_framework import routers
from . import restViews
from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter, SimpleRouter, DynamicListRoute
class CustomRouter(SimpleRouter):
"""
A router for read-only APIs, which doesn't ... | WorkStatusForNetTrafficWithDjango/WorkStatusForNetTrafficWithDjango/dashboard/urls.py | from django.conf.urls import url, include
from . import views
from rest_framework import routers
from . import restViews
from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter, SimpleRouter, DynamicListRoute
class CustomRouter(SimpleRouter):
"""
A router for read-only APIs, which doesn't ... | 0.540681 | 0.10316 |
import os
import subprocess
import sys
import tempfile
from challenge_status import ChallengeState
def generate_local_script(challenge: ChallengeState):
local_script_fh, local_script_path = tempfile.mkstemp()
os.write(local_script_fh, f'2900\n'.encode("ascii"))
os.write(local_script_fh, f'$"rocketman\\r... | modem/src/run_generator.py |
import os
import subprocess
import sys
import tempfile
from challenge_status import ChallengeState
def generate_local_script(challenge: ChallengeState):
local_script_fh, local_script_path = tempfile.mkstemp()
os.write(local_script_fh, f'2900\n'.encode("ascii"))
os.write(local_script_fh, f'$"rocketman\\r... | 0.155015 | 0.058723 |
import re
import sys
from datetime import datetime
from .dateparsers import *
__all__ = [
'ValidationError',
'CompoundValidationError',
'Field',
'Compound',
'Text',
'HTML',
'Email',
'DateTime',
'Boolean',
'Range',
'Float',
'Integer',
'BoundingBox',
'LatLng',
... | valipede/fields.py | import re
import sys
from datetime import datetime
from .dateparsers import *
__all__ = [
'ValidationError',
'CompoundValidationError',
'Field',
'Compound',
'Text',
'HTML',
'Email',
'DateTime',
'Boolean',
'Range',
'Float',
'Integer',
'BoundingBox',
'LatLng',
... | 0.352425 | 0.14013 |
import time
import numpy as np
import torch as pt
import math
# choose cpu or gpu computing
dvc = pt.device("cuda")
# tune default type
pt.set_default_dtype(pt.double)
pt.cuda.synchronize()
t0 = time.time()
pi = math.pi
def kron(m1, m2):
"""
matrix kronecker product
"""
return pt.... | soliton_torch.py | import time
import numpy as np
import torch as pt
import math
# choose cpu or gpu computing
dvc = pt.device("cuda")
# tune default type
pt.set_default_dtype(pt.double)
pt.cuda.synchronize()
t0 = time.time()
pi = math.pi
def kron(m1, m2):
"""
matrix kronecker product
"""
return pt.... | 0.459319 | 0.377684 |
import glob
import re
import shutil
from os.path import exists, basename
import simplejson as simplejson
from globals import output_directories, fill_header, output_root
class ProjectGenerator:
def __init__(self, launch_args):
self.project_config_path = launch_args.project_config_path
self.ros_m... | epl_ros_generator/project_generator.py | import glob
import re
import shutil
from os.path import exists, basename
import simplejson as simplejson
from globals import output_directories, fill_header, output_root
class ProjectGenerator:
def __init__(self, launch_args):
self.project_config_path = launch_args.project_config_path
self.ros_m... | 0.187877 | 0.079389 |
from __future__ import absolute_import, unicode_literals
from datetime import date
import logging
import os
import shutil
import gnupg
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compat... | mayan/apps/django_gpg/models.py | from __future__ import absolute_import, unicode_literals
from datetime import date
import logging
import os
import shutil
import gnupg
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compat... | 0.442877 | 0.049405 |
import copy
import itertools
from tabulate import tabulate
from orion.client import create_experiment
class Benchmark:
"""
Benchmark definition
Parameters
----------
name: str
Name of the benchmark
algorithms: list, optional
Algorithms used for benchmark, and for each algori... | src/orion/benchmark/__init__.py | import copy
import itertools
from tabulate import tabulate
from orion.client import create_experiment
class Benchmark:
"""
Benchmark definition
Parameters
----------
name: str
Name of the benchmark
algorithms: list, optional
Algorithms used for benchmark, and for each algori... | 0.883588 | 0.522629 |
from datetime import datetime
import json
import mock
from common.waterfall import buildbucket_client
from common.waterfall import failure_type
from common.waterfall import try_job_error
from libs import analysis_status
from model.flake.flake_try_job import FlakeTryJob
from model.flake.flake_try_job_data import Flake... | appengine/findit/waterfall/test/monitor_try_job_pipeline_test.py |
from datetime import datetime
import json
import mock
from common.waterfall import buildbucket_client
from common.waterfall import failure_type
from common.waterfall import try_job_error
from libs import analysis_status
from model.flake.flake_try_job import FlakeTryJob
from model.flake.flake_try_job_data import Flake... | 0.447702 | 0.447641 |
import sys
from .world import world, setup_module, teardown_module, show_doc, show_method
from . import create_source_steps as source_create
from . import create_dataset_steps as dataset_create
from . import create_model_steps as model_create
from . import create_ensemble_steps as ensemble_create
from . import create_... | bigml/tests/test_33_compare_predictions.py | import sys
from .world import world, setup_module, teardown_module, show_doc, show_method
from . import create_source_steps as source_create
from . import create_dataset_steps as dataset_create
from . import create_model_steps as model_create
from . import create_ensemble_steps as ensemble_create
from . import create_... | 0.138753 | 0.498535 |
import torch
from torchvision.transforms import Normalize
import numpy as np
import cv2
import argparse
import json
from models import hmr, SMPL
from utils.imutils import crop
from utils.renderer import Renderer
import config
import constants
parser = argparse.ArgumentParser()
parser.add_argument('--checkpoint', requ... | demo.py | import torch
from torchvision.transforms import Normalize
import numpy as np
import cv2
import argparse
import json
from models import hmr, SMPL
from utils.imutils import crop
from utils.renderer import Renderer
import config
import constants
parser = argparse.ArgumentParser()
parser.add_argument('--checkpoint', requ... | 0.797281 | 0.327628 |
import pytest
from datadog_checks.elastic.metrics import health_stats_for_version, pshard_stats_for_version, stats_for_version
@pytest.mark.unit
def test_stats_for_version():
# v0.90
metrics = stats_for_version([0, 90, 0])
assert len(metrics) == 133
# v0.90.5
metrics = stats_for_version([0, 90, ... | elastic/tests/test_metrics.py | import pytest
from datadog_checks.elastic.metrics import health_stats_for_version, pshard_stats_for_version, stats_for_version
@pytest.mark.unit
def test_stats_for_version():
# v0.90
metrics = stats_for_version([0, 90, 0])
assert len(metrics) == 133
# v0.90.5
metrics = stats_for_version([0, 90, ... | 0.449151 | 0.872565 |
from __future__ import print_function
import sklearn.preprocessing
from numpy import *
from copy import *
import warnings
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter, MaxNLocator
from mpl_toolkits.mplot3d import Axes3... | Vanilla RNN/VisualizationOfRNN.py | from __future__ import print_function
import sklearn.preprocessing
from numpy import *
from copy import *
import warnings
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter, MaxNLocator
from mpl_toolkits.mplot3d import Axes3... | 0.46223 | 0.206474 |
# sections in returned structure
SUCCESS = 'success'
STATUS_CODE = 'status_code'
HEADERS = 'headers'
CONTENT = 'content'
RAINCONTENT = 'raincontent'
MESSAGE = 'msg'
DATA = 'data'
ATTRIBUTION_INFO = "Data provided by buienradar.nl"
# key names as user in returned result
ATTRIBUTION = "attribution"
BAROMETERFC = 'barom... | buienradar/constants.py | # sections in returned structure
SUCCESS = 'success'
STATUS_CODE = 'status_code'
HEADERS = 'headers'
CONTENT = 'content'
RAINCONTENT = 'raincontent'
MESSAGE = 'msg'
DATA = 'data'
ATTRIBUTION_INFO = "Data provided by buienradar.nl"
# key names as user in returned result
ATTRIBUTION = "attribution"
BAROMETERFC = 'barom... | 0.255715 | 0.105073 |
import pytest
import codecs
import json
import tarfile
import lyrebird
from pathlib import Path
from copy import deepcopy
from typing import NamedTuple
from urllib.parse import urlparse
from lyrebird.mock import dm
from lyrebird.mock.dm.file_data_adapter import data_adapter
from lyrebird import application
dataA = {
... | tests/test_dm.py | import pytest
import codecs
import json
import tarfile
import lyrebird
from pathlib import Path
from copy import deepcopy
from typing import NamedTuple
from urllib.parse import urlparse
from lyrebird.mock import dm
from lyrebird.mock.dm.file_data_adapter import data_adapter
from lyrebird import application
dataA = {
... | 0.395484 | 0.192843 |
from builtins import range
'''
1) проверка числа на простоту (простые числа - это те числа у которых делители единица и они сами);
'''
def simp_number(number):
'''
:param number: Целое число для проверки
:return:являеться ли число натуральным
'''
if type(number)== float:
print("Это дробь, ... | Lesson_5_pack/divisor_master.py | from builtins import range
'''
1) проверка числа на простоту (простые числа - это те числа у которых делители единица и они сами);
'''
def simp_number(number):
'''
:param number: Целое число для проверки
:return:являеться ли число натуральным
'''
if type(number)== float:
print("Это дробь, ... | 0.087597 | 0.52141 |
from django.contrib.auth.models import User, Group
from localflavor.us.forms import USPhoneNumberField
from localflavor.us.models import PhoneNumberField
from django.db import models
from what_apps.comm.models import CommunicationInvolvement
from what_apps.people.models import UserProfile
from what_apps.social.models i... | what_apps/contact/models.py | from django.contrib.auth.models import User, Group
from localflavor.us.forms import USPhoneNumberField
from localflavor.us.models import PhoneNumberField
from django.db import models
from what_apps.comm.models import CommunicationInvolvement
from what_apps.people.models import UserProfile
from what_apps.social.models i... | 0.455441 | 0.196672 |
import argparse
import matplotlib.pyplot as plt
import pyperf
import statistics
def plot_bench(args, bench):
if not args.split_runs:
runs = bench.get_runs()
if args.run:
run = runs[args.run - 1]
runs = [run]
values = []
for run in runs:
run_value... | doc/examples/plot.py | import argparse
import matplotlib.pyplot as plt
import pyperf
import statistics
def plot_bench(args, bench):
if not args.split_runs:
runs = bench.get_runs()
if args.run:
run = runs[args.run - 1]
runs = [run]
values = []
for run in runs:
run_value... | 0.359477 | 0.503479 |
import http.client as http
import ddt
import webob
from oslo_serialization import jsonutils
from glance.api.middleware import version_negotiation
from glance.api import versions
from glance.common.wsgi import Request as WsgiRequest
from glance.tests.unit import base
# make this public so it doesn't need to be rep... | glance/tests/unit/test_versions.py |
import http.client as http
import ddt
import webob
from oslo_serialization import jsonutils
from glance.api.middleware import version_negotiation
from glance.api import versions
from glance.common.wsgi import Request as WsgiRequest
from glance.tests.unit import base
# make this public so it doesn't need to be rep... | 0.448185 | 0.093885 |
from pyang.types import UnionTypeSpec
from ydkgen.api_model import Bits, Class, Package, DataType, Enum, snake_case, get_property_name
from ydkgen.builder import TypesExtractor
from ydkgen.common import get_module_name, has_list_ancestor, is_top_level_class, get_qualified_yang_name, get_unclashed_name
from ydkgen.prin... | ydkgen/printer/python/class_inits_printer.py | from pyang.types import UnionTypeSpec
from ydkgen.api_model import Bits, Class, Package, DataType, Enum, snake_case, get_property_name
from ydkgen.builder import TypesExtractor
from ydkgen.common import get_module_name, has_list_ancestor, is_top_level_class, get_qualified_yang_name, get_unclashed_name
from ydkgen.prin... | 0.426322 | 0.115636 |
# stdlib imports
import os.path
# third party libraries
from configobj import ConfigObj
from validate import Validator, VdtTypeError
def __getCustomValidator():
'''
Return a Validator object with the custom types we have defined here.
Returns:
Validator object with custom types embedded.
''... | gfail/conf.py |
# stdlib imports
import os.path
# third party libraries
from configobj import ConfigObj
from validate import Validator, VdtTypeError
def __getCustomValidator():
'''
Return a Validator object with the custom types we have defined here.
Returns:
Validator object with custom types embedded.
''... | 0.575349 | 0.257838 |
import logging
from typing import Any, List
from gidgethub import routing
from gidgethub.sansio import Event
from algorithms_keeper import utils
from algorithms_keeper.api import GitHubAPI
from algorithms_keeper.constants import Label
check_run_router = routing.Router()
logger = logging.getLogger(__package__)
@ch... | algorithms_keeper/event/check_run.py | import logging
from typing import Any, List
from gidgethub import routing
from gidgethub.sansio import Event
from algorithms_keeper import utils
from algorithms_keeper.api import GitHubAPI
from algorithms_keeper.constants import Label
check_run_router = routing.Router()
logger = logging.getLogger(__package__)
@ch... | 0.682997 | 0.217338 |
import nltk
nltk.download('stopwords')
from sklearn.base import BaseEstimator, TransformerMixin
from nltk.corpus import stopwords
from bs4 import BeautifulSoup
from tqdm import tqdm
import re
def classes_def(x):
if x == "Extremely Positive":
return "2"
elif x == "Extremely Negative":
return ... | mycode/utils.py | import nltk
nltk.download('stopwords')
from sklearn.base import BaseEstimator, TransformerMixin
from nltk.corpus import stopwords
from bs4 import BeautifulSoup
from tqdm import tqdm
import re
def classes_def(x):
if x == "Extremely Positive":
return "2"
elif x == "Extremely Negative":
return ... | 0.33546 | 0.157234 |
import meshed as ms
import pytest
@pytest.fixture
def example_graph():
return dict(a=['c'], b=['c', 'c'], c=['a', 'b', 'd', 'e'], d=['c'], e=['c', 'z'])
@pytest.fixture
def graph_children():
return {0: [1, 2], 1: [2, 3, 4], 2: [1, 4], 3: [4]}
@pytest.fixture
def digraph_children():
return {0: [1, 2], ... | meshed/tests/test_itools.py | import meshed as ms
import pytest
@pytest.fixture
def example_graph():
return dict(a=['c'], b=['c', 'c'], c=['a', 'b', 'd', 'e'], d=['c'], e=['c', 'z'])
@pytest.fixture
def graph_children():
return {0: [1, 2], 1: [2, 3, 4], 2: [1, 4], 3: [4]}
@pytest.fixture
def digraph_children():
return {0: [1, 2], ... | 0.631935 | 0.739963 |
import pandas as pd
import numpy as np
import pytest
from .. import class_label
from .. import mhealth_format as mh
from .. import extensions as ext
from .. import spades_lab as slab
from .. import extensions as ext
@pytest.fixture(scope='module')
def test_data(spades_lab_data):
annotation_file = spades_lab_data[... | arus/tests/test_class_set.py | import pandas as pd
import numpy as np
import pytest
from .. import class_label
from .. import mhealth_format as mh
from .. import extensions as ext
from .. import spades_lab as slab
from .. import extensions as ext
@pytest.fixture(scope='module')
def test_data(spades_lab_data):
annotation_file = spades_lab_data[... | 0.402392 | 0.463687 |
import proto # type: ignore
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(
package='google.cloud.assuredworkloads.v1',
manifest={
'CreateWorkloa... | google/cloud/assuredworkloads/v1/assuredworkloads-v1-py/google/cloud/assuredworkloads_v1/types/assuredworkloads.py | import proto # type: ignore
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(
package='google.cloud.assuredworkloads.v1',
manifest={
'CreateWorkloa... | 0.672332 | 0.123551 |
from cryptopy.keyedHash.pbkdf2 import pbkdf2, dot11PassPhraseToPSK
import unittest
from binascii_plus import a2b_p, b2a_p, b2a_hex,b2a_pter
class PBDKDF22_KnowAnswerTests(unittest.TestCase):
""" """
def pbkdf2KAT(self,testDescription, password, salt, iterations, keySize, ka):
""" Know Answer Tests fro... | script.module.streamlink.crypto/lib/cryptopy/keyedHash/pbkdf2_test.py | from cryptopy.keyedHash.pbkdf2 import pbkdf2, dot11PassPhraseToPSK
import unittest
from binascii_plus import a2b_p, b2a_p, b2a_hex,b2a_pter
class PBDKDF22_KnowAnswerTests(unittest.TestCase):
""" """
def pbkdf2KAT(self,testDescription, password, salt, iterations, keySize, ka):
""" Know Answer Tests fro... | 0.374676 | 0.344829 |
from codecs import open
from os import path
# Always prefer setuptools over distutils
from setuptools import find_packages, setup
import subprocess
version = subprocess.check_output(['head', 'debian/changelog', '-n1']).decode().split()[1].strip('()').split('~')[0].split('-')[0].split('+')[0]
here = path.abspath(path... | setup.py | from codecs import open
from os import path
# Always prefer setuptools over distutils
from setuptools import find_packages, setup
import subprocess
version = subprocess.check_output(['head', 'debian/changelog', '-n1']).decode().split()[1].strip('()').split('~')[0].split('-')[0].split('+')[0]
here = path.abspath(path... | 0.575349 | 0.18188 |
import optparse
import os
import shutil
import stat
import sys
import cx_Freeze
__all__ = ["main"]
USAGE = \
"""
%prog [options] [SCRIPT]
Freeze a Python script and all of its referenced modules to a base
executable which can then be distributed without requiring a Python
installation."""
VERSION = \
"""
%%prog %s... | core/native/vendor/cx_Freeze-5.0.1/cx_Freeze/main.py | import optparse
import os
import shutil
import stat
import sys
import cx_Freeze
__all__ = ["main"]
USAGE = \
"""
%prog [options] [SCRIPT]
Freeze a Python script and all of its referenced modules to a base
executable which can then be distributed without requiring a Python
installation."""
VERSION = \
"""
%%prog %s... | 0.359364 | 0.121634 |
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import annotations # isort:skip
import pytest ; pytest
#-------------------------------------------------------------------------... | tests/unit/bokeh/server/test_auth_provider.py |
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import annotations # isort:skip
import pytest ; pytest
#-------------------------------------------------------------------------... | 0.566738 | 0.31182 |
from openvino.opset1.ops import absolute
from openvino.opset1.ops import absolute as abs
from openvino.opset1.ops import acos
from openvino.opset4.ops import acosh
from openvino.opset1.ops import add
from openvino.opset1.ops import asin
from openvino.opset4.ops import asinh
from openvino.opset3.ops import assign
from ... | runtime/bindings/python/src/openvino/opset5/__init__.py |
from openvino.opset1.ops import absolute
from openvino.opset1.ops import absolute as abs
from openvino.opset1.ops import acos
from openvino.opset4.ops import acosh
from openvino.opset1.ops import add
from openvino.opset1.ops import asin
from openvino.opset4.ops import asinh
from openvino.opset3.ops import assign
from ... | 0.532182 | 0.139396 |
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from anynet import tls
import hashlib
import struct
import base64
import logging
logger = logging.getLogger(__name__)
def b64encode(data):
return base64.b64encode(data, b"-_").decode().rstrip("=")
def b64decode(text):
length = (len(tex... | nintendo/switch.py | from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from anynet import tls
import hashlib
import struct
import base64
import logging
logger = logging.getLogger(__name__)
def b64encode(data):
return base64.b64encode(data, b"-_").decode().rstrip("=")
def b64decode(text):
length = (len(tex... | 0.399109 | 0.105073 |
import typing
from typing import Any, Dict, List, Optional
import buildpg
from app import errors
from app.cogs.premium.premium_funcs import can_increase, limit_for
if typing.TYPE_CHECKING:
from app.database.database import Database
class PermRoles:
def __init__(self, db: "Database"):
self.db = db
... | app/database/database_functions/permroles.py | import typing
from typing import Any, Dict, List, Optional
import buildpg
from app import errors
from app.cogs.premium.premium_funcs import can_increase, limit_for
if typing.TYPE_CHECKING:
from app.database.database import Database
class PermRoles:
def __init__(self, db: "Database"):
self.db = db
... | 0.675658 | 0.143758 |
from __future__ import annotations
from os.path import abspath, join, dirname
from typing import Tuple
try:
import mapnik
import osgeo.ogr as geo
except ImportError as e:
print('[!]Module Unavailable : {}'.format(str(e)))
exit(1)
def __renderCountry__(myMap: mapnik.Map, bbox: mapnik._Box2d, target_fi... | map/build.py |
from __future__ import annotations
from os.path import abspath, join, dirname
from typing import Tuple
try:
import mapnik
import osgeo.ogr as geo
except ImportError as e:
print('[!]Module Unavailable : {}'.format(str(e)))
exit(1)
def __renderCountry__(myMap: mapnik.Map, bbox: mapnik._Box2d, target_fi... | 0.535098 | 0.270583 |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
engine = create_engine('sqlite:///restaurantMenu.db')
Base.metadata.bind=engine
DBSession = sessionmaker(bind = engine)
session = DBSession()
'''
CREATE
We created a new Restau... | 4-iterative-development/src/sqlalchemy_crud_ops.py | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
engine = create_engine('sqlite:///restaurantMenu.db')
Base.metadata.bind=engine
DBSession = sessionmaker(bind = engine)
session = DBSession()
'''
CREATE
We created a new Restau... | 0.237311 | 0.10859 |
from tempfile import TemporaryDirectory
from .. import errors
from fud.stages import Source, SourceType, Stage, Step
class VivadoTemplateStage(Stage):
"""
TODO(rachit): Document this.
"""
def __init__(self, name, target, config, descr):
super().__init__(name, target, config, descr)
s... | fud/fud/vivado/stage_template.py | from tempfile import TemporaryDirectory
from .. import errors
from fud.stages import Source, SourceType, Stage, Step
class VivadoTemplateStage(Stage):
"""
TODO(rachit): Document this.
"""
def __init__(self, name, target, config, descr):
super().__init__(name, target, config, descr)
s... | 0.206254 | 0.101145 |
import unittest
from client_cli.render.flatten.backup_rules import (
get_spec_matched,
get_spec_unmatched,
flatten_matched,
flatten_unmatched,
transform_rule_explanation
)
from tests.mocks import mock_data
class BackupRulesSpec(unittest.TestCase):
@classmethod
def setUpClass(cls):
... | client-cli/tests/render/flatten/test_backup_rules.py | import unittest
from client_cli.render.flatten.backup_rules import (
get_spec_matched,
get_spec_unmatched,
flatten_matched,
flatten_unmatched,
transform_rule_explanation
)
from tests.mocks import mock_data
class BackupRulesSpec(unittest.TestCase):
@classmethod
def setUpClass(cls):
... | 0.605682 | 0.636833 |
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, MATCH
import dash_bootstrap_components as dbc
from apps import text
from util import header
from app import app
from dataclasses import dataclass
@dataclass
class Card:
image: str = ""
title: ... | apps/app_gallery.py | import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, MATCH
import dash_bootstrap_components as dbc
from apps import text
from util import header
from app import app
from dataclasses import dataclass
@dataclass
class Card:
image: str = ""
title: ... | 0.667039 | 0.38145 |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... | pybind/slxos/v16r_1_00b/brocade_mpls_rpc/show_mpls_interface_one_interface/output/mpls_interface_detail/show_mpls_interface_detail/__init__.py | from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... | 0.616012 | 0.066782 |
import tarfile
import os
import pickle
from datetime import datetime
from featherstore.connection import Connection, current_db
METADATA_FILE_NAME = 'metadata.pkl'
def restore_table(store, source, errors='raise'):
"""Restores a table in to the currently selected db.
Parameters
----------
store : str... | featherstore/snapshot.py | import tarfile
import os
import pickle
from datetime import datetime
from featherstore.connection import Connection, current_db
METADATA_FILE_NAME = 'metadata.pkl'
def restore_table(store, source, errors='raise'):
"""Restores a table in to the currently selected db.
Parameters
----------
store : str... | 0.635675 | 0.110759 |
"""Factory for mean."""
import collections
from typing import Optional
import tensorflow as tf
from tensorflow_federated.python.aggregators import factory
from tensorflow_federated.python.aggregators import sum_factory
from tensorflow_federated.python.common_libs import py_typecheck
from tensorflow_federated.python.c... | tensorflow_federated/python/aggregators/mean_factory.py | """Factory for mean."""
import collections
from typing import Optional
import tensorflow as tf
from tensorflow_federated.python.aggregators import factory
from tensorflow_federated.python.aggregators import sum_factory
from tensorflow_federated.python.common_libs import py_typecheck
from tensorflow_federated.python.c... | 0.965916 | 0.509703 |
import os
from copy import deepcopy
from decimal import Decimal, ROUND_HALF_UP
from uuid import uuid4
from openregistry.lots.loki.utils import get_now
from openregistry.lots.core.constants import (
SANDBOX_MODE,
)
from openregistry.lots.loki.tests.fixtures import PARTIAL_MOCK_CONFIG
from openregistry.lots.core.tes... | openregistry/lots/loki/tests/base.py | import os
from copy import deepcopy
from decimal import Decimal, ROUND_HALF_UP
from uuid import uuid4
from openregistry.lots.loki.utils import get_now
from openregistry.lots.core.constants import (
SANDBOX_MODE,
)
from openregistry.lots.loki.tests.fixtures import PARTIAL_MOCK_CONFIG
from openregistry.lots.core.tes... | 0.423458 | 0.218263 |
import filecmp
import io
import json
import re
import os
import unittest
import functools
from pathlib import Path
from megatron.testing_utils import (
TestCasePlus,
execute_subprocess_async,
set_seed
)
from datasets import load_dataset
set_seed(42)
def write_jsonl(path, lines_num=1000, line_length=1... | tests/test_preprocessing.py |
import filecmp
import io
import json
import re
import os
import unittest
import functools
from pathlib import Path
from megatron.testing_utils import (
TestCasePlus,
execute_subprocess_async,
set_seed
)
from datasets import load_dataset
set_seed(42)
def write_jsonl(path, lines_num=1000, line_length=1... | 0.292494 | 0.253076 |
import os
from pathlib import Path
import numpy as np
import pandas as pd
import shutil
def S2(spectra, Bands):
"""Sentinel-2 convolution"""
cwd = Path.cwd()
Home_Dir = cwd
bands_Dir = str(cwd / "bands")
convolved_Dir = str(cwd / "convolved")
if (Path(bands_Dir)).exists() and (P... | FieldSpecUtils/Convolution.py |
import os
from pathlib import Path
import numpy as np
import pandas as pd
import shutil
def S2(spectra, Bands):
"""Sentinel-2 convolution"""
cwd = Path.cwd()
Home_Dir = cwd
bands_Dir = str(cwd / "bands")
convolved_Dir = str(cwd / "convolved")
if (Path(bands_Dir)).exists() and (P... | 0.294215 | 0.229535 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from os.path import dirname, abspath, join
import csv
BASE_DIR = dirname(abspath(__file__))
def add_defaults_from_csv(model, csv_file):
with open(join(BASE_DIR, csv_file)) as f:
for line in c... | src/niweb/apps/noclook/migrations/0012_authzaction_context_groupcontextauthzaction_nodehandlecontext.py | from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from os.path import dirname, abspath, join
import csv
BASE_DIR = dirname(abspath(__file__))
def add_defaults_from_csv(model, csv_file):
with open(join(BASE_DIR, csv_file)) as f:
for line in c... | 0.530966 | 0.093637 |
import urllib
import xml.etree.cElementTree as ET
import os
import sys
ROOT="/x1/mail-archives/mod_mbox"
# Get the list of podlings from a list the Incubator PMC maintains.
def _get_podlings():
rv = set()
u = urllib.urlopen("http://incubator.apache.org/podlings.xml")
string = u.read()
root = ET.fromstring(st... | scripts/site-index.py |
import urllib
import xml.etree.cElementTree as ET
import os
import sys
ROOT="/x1/mail-archives/mod_mbox"
# Get the list of podlings from a list the Incubator PMC maintains.
def _get_podlings():
rv = set()
u = urllib.urlopen("http://incubator.apache.org/podlings.xml")
string = u.read()
root = ET.fromstring(st... | 0.083446 | 0.097648 |
import numpy as np
import matplotlib.pyplot as plt
def _alphas(v, v_r):
"""
Calculates alpha parameters using current membrane potential
and resting potential in units of milli volts.
:param v: Membrane potential in milli volts. float.
:param v_r: Membrane potential in milli volts. float.
:ret... | neurosim.py | import numpy as np
import matplotlib.pyplot as plt
def _alphas(v, v_r):
"""
Calculates alpha parameters using current membrane potential
and resting potential in units of milli volts.
:param v: Membrane potential in milli volts. float.
:param v_r: Membrane potential in milli volts. float.
:ret... | 0.860604 | 0.610482 |
import os
import torch
from torch import nn
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
os.environ['config_file'] = 'configs/fedavg_lenet5.yml'
from plato.clients import simple
from plato.datasources import base
from plato.servers import fedavg
from plato.trainers import basic
... | examples/custom_model.py | import os
import torch
from torch import nn
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
os.environ['config_file'] = 'configs/fedavg_lenet5.yml'
from plato.clients import simple
from plato.datasources import base
from plato.servers import fedavg
from plato.trainers import basic
... | 0.856212 | 0.571348 |
import base64
import logging
import requests
import six
from cryptography import x509
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.x509 import NameOID
from hfc.util.crypto.crypto import ecies
DEFAULT_CA_ENDPOINT = 'http://localhost:7054'
DEFAULT_CA_BASE_URL = '/api/v1/'
_logge... | hfc/fabric_ca/caservice.py | import base64
import logging
import requests
import six
from cryptography import x509
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.x509 import NameOID
from hfc.util.crypto.crypto import ecies
DEFAULT_CA_ENDPOINT = 'http://localhost:7054'
DEFAULT_CA_BASE_URL = '/api/v1/'
_logge... | 0.838184 | 0.137532 |
import core.implant
import core.job
import string
class DynWrapXShellcodeJob(core.job.Job):
def create(self):
self.fork32Bit = True
def report(self, handler, data, sanitize = False):
task = handler.get_header(self.options.get("UUIDHEADER"), False)
if task == self.options.get("DLLUUID"... | modules/implant/inject/shellcode_dynwrapx.py | import core.implant
import core.job
import string
class DynWrapXShellcodeJob(core.job.Job):
def create(self):
self.fork32Bit = True
def report(self, handler, data, sanitize = False):
task = handler.get_header(self.options.get("UUIDHEADER"), False)
if task == self.options.get("DLLUUID"... | 0.38549 | 0.14777 |
import taichi as ti
import math
@ti.data_oriented
class SolarSystem:
def __init__(self, n, dt):
# initializer of the solar system simulator
self.n = n
self.dt = dt
self.x = ti.Vector(2, dt=ti.f32, shape=n)
self.v = ti.Vector(2, dt=ti.f32, shape=n)
self.center = ti.V... | examples/odop_solar.py | import taichi as ti
import math
@ti.data_oriented
class SolarSystem:
def __init__(self, n, dt):
# initializer of the solar system simulator
self.n = n
self.dt = dt
self.x = ti.Vector(2, dt=ti.f32, shape=n)
self.v = ti.Vector(2, dt=ti.f32, shape=n)
self.center = ti.V... | 0.625438 | 0.504883 |
"""JWT testing service API implementations in Python."""
import datetime
import io
import json
from typing import Tuple
import grpc
import tink
from tink import cleartext_keyset_handle
from tink import jwt
from proto.testing import testing_api_pb2
from proto.testing import testing_api_pb2_grpc
def _to_timestamp_... | testing/python/jwt_service.py | """JWT testing service API implementations in Python."""
import datetime
import io
import json
from typing import Tuple
import grpc
import tink
from tink import cleartext_keyset_handle
from tink import jwt
from proto.testing import testing_api_pb2
from proto.testing import testing_api_pb2_grpc
def _to_timestamp_... | 0.799873 | 0.263854 |
from wsgidav import util
import win32net #@UnresolvedImport
import win32security #@UnresolvedImport
import win32netcon #@UnresolvedImport
__docformat__ = "reStructuredText"
_logger = util.getModuleLogger(__name__)
class NTDomainController(object):
def __init__(self, presetdomain = None, pr... | thirdpart/wsgidav/addons/nt_domain_controller.py | from wsgidav import util
import win32net #@UnresolvedImport
import win32security #@UnresolvedImport
import win32netcon #@UnresolvedImport
__docformat__ = "reStructuredText"
_logger = util.getModuleLogger(__name__)
class NTDomainController(object):
def __init__(self, presetdomain = None, pr... | 0.219421 | 0.044535 |
import os
import inspect
import traceback
import sys
import logging
from functools import wraps
from os.path import dirname, join, isdir, expanduser
from more_kivy_app.config import apply_config, read_config_from_file, \
read_config_from_object, dump_config
if not os.environ.get('KIVY_DOC_INCLUDE', None):
fro... | more_kivy_app/app.py | import os
import inspect
import traceback
import sys
import logging
from functools import wraps
from os.path import dirname, join, isdir, expanduser
from more_kivy_app.config import apply_config, read_config_from_file, \
read_config_from_object, dump_config
if not os.environ.get('KIVY_DOC_INCLUDE', None):
fro... | 0.403214 | 0.078148 |
from spack import *
class HsaRocrDev(CMakePackage):
"""This repository includes the user mode API nterfaces and libraries
necessary for host applications to launch computer kernels to available
HSA ROCm kernel agents.AMD Heterogeneous System Architecture HSA -
Linux HSA Runtime for Boltzman... | var/spack/repos/builtin/packages/hsa-rocr-dev/package.py |
from spack import *
class HsaRocrDev(CMakePackage):
"""This repository includes the user mode API nterfaces and libraries
necessary for host applications to launch computer kernels to available
HSA ROCm kernel agents.AMD Heterogeneous System Architecture HSA -
Linux HSA Runtime for Boltzman... | 0.768473 | 0.304934 |
#---------------------DEFINE PACKAGE------------------------------------------
import numpy as np
import h5py
import matplotlib.pyplot as plt
import testCases
from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward
import lr_utils
np.random.seed(1)
#-------------------Programming Area------------------... | C1_W4/Multi-layer_nn.py | #---------------------DEFINE PACKAGE------------------------------------------
import numpy as np
import h5py
import matplotlib.pyplot as plt
import testCases
from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward
import lr_utils
np.random.seed(1)
#-------------------Programming Area------------------... | 0.521959 | 0.458531 |
import json
import os.path
import pytest
import shutil
import tempfile
import time
import re
from flaky import flaky
from testutils.common import create_org
from testutils.infra.container_manager import factory
from testutils.infra.container_manager.kubernetes_manager import isK8S
from testutils.infra.device import M... | tests/tests/test_mtls.py |
import json
import os.path
import pytest
import shutil
import tempfile
import time
import re
from flaky import flaky
from testutils.common import create_org
from testutils.infra.container_manager import factory
from testutils.infra.container_manager.kubernetes_manager import isK8S
from testutils.infra.device import M... | 0.218419 | 0.053899 |
import numpy
class NeuralNetworkWrapper():
'''A wrapper for a neural network model for use in pomegranate.
This wrapper will store a pointer to the model, as well as an indicator
of what class it represents. It needs information about the number of
dimensions of the input and the total number of ... | pomegranate/distributions/NeuralNetworkWrapper.py |
import numpy
class NeuralNetworkWrapper():
'''A wrapper for a neural network model for use in pomegranate.
This wrapper will store a pointer to the model, as well as an indicator
of what class it represents. It needs information about the number of
dimensions of the input and the total number of ... | 0.882833 | 0.928862 |
"""Group 1 Implementation. Mohammed and Mahmudda"""
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 13:17:18 2019
@author: INSTHassaM3
"""
# -*- coding: utf-8 -*-
import numpy as np
import networkx as nx
#chnge to dict
relations = {
'INCREASES': +1,
'DIRECTLY_INCREASES': +1,
'DECREASES': -1,
'DIREC... | src/pyrcr/rcr_1.py |
"""Group 1 Implementation. Mohammed and Mahmudda"""
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 13:17:18 2019
@author: INSTHassaM3
"""
# -*- coding: utf-8 -*-
import numpy as np
import networkx as nx
#chnge to dict
relations = {
'INCREASES': +1,
'DIRECTLY_INCREASES': +1,
'DECREASES': -1,
'DIREC... | 0.207938 | 0.29549 |
import datetime
import tensorflow as tf
import easytransfer.layers as layers
from easytransfer import preprocessors, model_zoo, FLAGS, base_model
from easytransfer.losses import softmax_cross_entropy
from easytransfer.evaluators import classification_eval_metrics, teacher_probes_eval_metrics
from easytransfer.app_zoo... | scripts/knowledge_distillation/main_teacher.py |
import datetime
import tensorflow as tf
import easytransfer.layers as layers
from easytransfer import preprocessors, model_zoo, FLAGS, base_model
from easytransfer.losses import softmax_cross_entropy
from easytransfer.evaluators import classification_eval_metrics, teacher_probes_eval_metrics
from easytransfer.app_zoo... | 0.894347 | 0.284818 |
import sys
from dataclasses import asdict, dataclass
from functools import partial
from json import dumps as sdumps
import pytest
try:
from ujson import dumps as udumps
NO_UJSON = False
DEFAULT_DUMPS = udumps
except ModuleNotFoundError:
NO_UJSON = True
DEFAULT_DUMPS = partial(sdumps, separators... | tests/test_json_encoding.py | import sys
from dataclasses import asdict, dataclass
from functools import partial
from json import dumps as sdumps
import pytest
try:
from ujson import dumps as udumps
NO_UJSON = False
DEFAULT_DUMPS = udumps
except ModuleNotFoundError:
NO_UJSON = True
DEFAULT_DUMPS = partial(sdumps, separators... | 0.446736 | 0.279478 |
import pytest
import torch
from torch.autograd import grad
from torch.distributions import constraints
import pyro
import pyro.optim as optim
from pyro.distributions import (
OneHotCategorical,
RelaxedBernoulli,
RelaxedBernoulliStraightThrough,
RelaxedOneHotCategorical,
RelaxedOneHotCategoricalStr... | tests/distributions/test_relaxed_straight_through.py |
import pytest
import torch
from torch.autograd import grad
from torch.distributions import constraints
import pyro
import pyro.optim as optim
from pyro.distributions import (
OneHotCategorical,
RelaxedBernoulli,
RelaxedBernoulliStraightThrough,
RelaxedOneHotCategorical,
RelaxedOneHotCategoricalStr... | 0.790894 | 0.647143 |
u"""
utilities.py
Written by <NAME> (03/2021)
Download and management utilities for syncing time and auxiliary files
UPDATE HISTORY:
Updated 03/2021: added sha1 option for retrieving file hashes
Updated 01/2021: added ftp connection check
Written 08/2020
"""
from __future__ import print_function
import sy... | cryosat_toolkit/utilities.py | u"""
utilities.py
Written by <NAME> (03/2021)
Download and management utilities for syncing time and auxiliary files
UPDATE HISTORY:
Updated 03/2021: added sha1 option for retrieving file hashes
Updated 01/2021: added ftp connection check
Written 08/2020
"""
from __future__ import print_function
import sy... | 0.517083 | 0.217836 |
import asyncio
import hashlib
import json
import logging
import struct
import sys
from threading import Timer
from typing import Optional, Dict, Any, Callable
import requests
from clients.MQTTClient import MQTTClient
from common.consts import *
from models.DahuaConfigData import DahuaConfigurationData
_LOGGER = logg... | DahuaVTO2MQTT/rootfs/app/clients/DahuaClient.py | import asyncio
import hashlib
import json
import logging
import struct
import sys
from threading import Timer
from typing import Optional, Dict, Any, Callable
import requests
from clients.MQTTClient import MQTTClient
from common.consts import *
from models.DahuaConfigData import DahuaConfigurationData
_LOGGER = logg... | 0.457864 | 0.097648 |
import argparse
import sys
from perf_insights import corpus_driver_cmdline
from perf_insights import corpus_query
from perf_insights import map_runner
from perf_insights import function_handle
from perf_insights.mre import job as job_module
from perf_insights.results import json_output_formatter
_CORPUS_QUERY_HELP =... | third_party/catapult/perf_insights/perf_insights/map_traces.py | import argparse
import sys
from perf_insights import corpus_driver_cmdline
from perf_insights import corpus_query
from perf_insights import map_runner
from perf_insights import function_handle
from perf_insights.mre import job as job_module
from perf_insights.results import json_output_formatter
_CORPUS_QUERY_HELP =... | 0.296247 | 0.105995 |
"""train CTPN and get checkpoint files."""
import os
import time
import argparse
import ast
import mindspore.common.dtype as mstype
from mindspore import context, Tensor
from mindspore.communication.management import init
from mindspore.train.callback import CheckpointConfig, ModelCheckpoint, TimeMonitor
from mindspor... | model_zoo/official/cv/ctpn/train.py |
"""train CTPN and get checkpoint files."""
import os
import time
import argparse
import ast
import mindspore.common.dtype as mstype
from mindspore import context, Tensor
from mindspore.communication.management import init
from mindspore.train.callback import CheckpointConfig, ModelCheckpoint, TimeMonitor
from mindspor... | 0.69035 | 0.125413 |
import FWCore.ParameterSet.Config as cms
EcalTrivialConditionRetriever = cms.ESSource("EcalTrivialConditionRetriever",
TotLumi = cms.untracked.double(0.0),
InstLumi = cms.untracked.double(0.0),
producedEcalChannelStatus = cms.untracked.bool(True),
producedEcalDQMTowerStatus = cms.untracked.bool(True),
... | CalibCalorimetry/EcalTrivialCondModules/python/EcalTrivialCondRetriever_cfi.py | import FWCore.ParameterSet.Config as cms
EcalTrivialConditionRetriever = cms.ESSource("EcalTrivialConditionRetriever",
TotLumi = cms.untracked.double(0.0),
InstLumi = cms.untracked.double(0.0),
producedEcalChannelStatus = cms.untracked.bool(True),
producedEcalDQMTowerStatus = cms.untracked.bool(True),
... | 0.500977 | 0.531149 |
import collections
import warnings
from pandas import Series, DataFrame
import pandas as pd
from .read.dinosurfacelevel import DinoSurfaceLevel
class SwSeries:
""" Surface water level series """
LOCPROPS_NAMES = [
'locname','alias','xcr','ycr',
'level_reference','grid_reference']
LEVELP... | acequia/swseries.py | import collections
import warnings
from pandas import Series, DataFrame
import pandas as pd
from .read.dinosurfacelevel import DinoSurfaceLevel
class SwSeries:
""" Surface water level series """
LOCPROPS_NAMES = [
'locname','alias','xcr','ycr',
'level_reference','grid_reference']
LEVELP... | 0.437343 | 0.146118 |
import os
import os.path
import unittest
from typing import Set, Union, Sequence
from xcube.constants import FORMAT_NAME_ZARR
from xcube.core.chunk import chunk_dataset
from xcube.core.dsio import rimraf
from xcube.core.new import new_cube
from xcube.core.optimize import optimize_dataset
TEST_CUBE = chunk_dataset(new... | test/core/test_optimize.py | import os
import os.path
import unittest
from typing import Set, Union, Sequence
from xcube.constants import FORMAT_NAME_ZARR
from xcube.core.chunk import chunk_dataset
from xcube.core.dsio import rimraf
from xcube.core.new import new_cube
from xcube.core.optimize import optimize_dataset
TEST_CUBE = chunk_dataset(new... | 0.672977 | 0.327803 |
import pytest
from fastapi.testclient import TestClient
from jsonschema import validate
from semesterstat.reciepts import StudentScoreReciept
def test_batch_get_all(client: TestClient):
res = client.get("/batch/")
data = res.json()
assert res.status_code == 200
assert isinstance(data, list)
asse... | tests/api/test_api_batch.py | import pytest
from fastapi.testclient import TestClient
from jsonschema import validate
from semesterstat.reciepts import StudentScoreReciept
def test_batch_get_all(client: TestClient):
res = client.get("/batch/")
data = res.json()
assert res.status_code == 200
assert isinstance(data, list)
asse... | 0.628863 | 0.445771 |
from django.shortcuts import render
from rest_framework import status, views
from rest_framework.response import Response
from beer.models import BeerModel
from beer.serializers import BeerModelSerializer
class BeerView(views.APIView):
serializer_class = BeerModelSerializer
def get(self, request, pk=None)... | moonshine/beer/views.py | from django.shortcuts import render
from rest_framework import status, views
from rest_framework.response import Response
from beer.models import BeerModel
from beer.serializers import BeerModelSerializer
class BeerView(views.APIView):
serializer_class = BeerModelSerializer
def get(self, request, pk=None)... | 0.499268 | 0.076442 |
import patyczki.green_functions
import numpy as np
import numpy.linalg
def coupling_matrix(mesh, mesh_sizes, w=1.0):
"""
Create coupling matrix out of locations of discretization points and sizes
of the discretized segments. A discretization of Green-Fredholm equation for
the solution of Laplaces prob... | patyczki/fredholm_solver.py | import patyczki.green_functions
import numpy as np
import numpy.linalg
def coupling_matrix(mesh, mesh_sizes, w=1.0):
"""
Create coupling matrix out of locations of discretization points and sizes
of the discretized segments. A discretization of Green-Fredholm equation for
the solution of Laplaces prob... | 0.89945 | 0.659563 |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os
import re
import sys
import urllib
import warnings
from django.core.management.color import color_style
from django.utils.http import http_date
from django.utils._os import safe_join
from django.contrib.staticfiles.handlers import StaticFilesHandl... | django/core/servers/basehttp.py | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os
import re
import sys
import urllib
import warnings
from django.core.management.color import color_style
from django.utils.http import http_date
from django.utils._os import safe_join
from django.contrib.staticfiles.handlers import StaticFilesHandl... | 0.517327 | 0.175962 |
import configparser
import datetime
import logging
import os
import zipfile
from pathlib import Path
import shutil
import sys
import tempfile
from termcolor import colored
_PROJ_DESC = __doc__.split('\n')[0]
_PROJ_PATH = Path(__file__)
_PROJ_NAME = _PROJ_PATH.stem
_PROJ_VERSION = '3.3.0'
class Archiver:
'''Archi... | src/beetools/beearchiver.py | import configparser
import datetime
import logging
import os
import zipfile
from pathlib import Path
import shutil
import sys
import tempfile
from termcolor import colored
_PROJ_DESC = __doc__.split('\n')[0]
_PROJ_PATH = Path(__file__)
_PROJ_NAME = _PROJ_PATH.stem
_PROJ_VERSION = '3.3.0'
class Archiver:
'''Archi... | 0.420362 | 0.281609 |
from iminuit.util import describe, make_func_code
from math import ldexp
import pytest
import platform
from functools import wraps
is_pypy = platform.python_implementation() == "PyPy"
def test_function():
def f(x, y):
# body is important
a = 1
b = 2
return a + b
assert descri... | tests/test_describe.py | from iminuit.util import describe, make_func_code
from math import ldexp
import pytest
import platform
from functools import wraps
is_pypy = platform.python_implementation() == "PyPy"
def test_function():
def f(x, y):
# body is important
a = 1
b = 2
return a + b
assert descri... | 0.823009 | 0.674104 |
import ast
import sys
import tokenize
from typing import Any, Optional
from pegen.parser import memoize, memoize_left_rec, logger, Parser
from ast import literal_eval
from pegen.grammar import (
Alt,
Cut,
Gather,
Group,
Item,
Lookahead,
LookaheadOrCut,
MetaTuple,
... | Tools/peg_generator/pegen/grammar_parser.py |
import ast
import sys
import tokenize
from typing import Any, Optional
from pegen.parser import memoize, memoize_left_rec, logger, Parser
from ast import literal_eval
from pegen.grammar import (
Alt,
Cut,
Gather,
Group,
Item,
Lookahead,
LookaheadOrCut,
MetaTuple,
... | 0.536313 | 0.152095 |
from __future__ import print_function
import unittest
import gpflow
import numpy as np
import tensorflow as tf
from gpflow import settings
from testing.gpflow_testcase import GPflowTestCase
float_type = settings.dtypes.float_type
def squareT(A):
"""
Returns (A Aᵀ)
"""
return A.dot(A.T)
class Diag... | GPflow/testing/test_kldiv.py | from __future__ import print_function
import unittest
import gpflow
import numpy as np
import tensorflow as tf
from gpflow import settings
from testing.gpflow_testcase import GPflowTestCase
float_type = settings.dtypes.float_type
def squareT(A):
"""
Returns (A Aᵀ)
"""
return A.dot(A.T)
class Diag... | 0.832066 | 0.568416 |
from scipy.integrate import quad
from numpy import inf, linspace
from matplotlib import pyplot as plt
class MemberFunct:
def __init__(self,field_name, memb_name,triangle_func=True,evaluate_funct=None,*args):
self.triangle_func = triangle_func
self.field_name = field_name
self.memb_name = m... | fuzzySys.py | from scipy.integrate import quad
from numpy import inf, linspace
from matplotlib import pyplot as plt
class MemberFunct:
def __init__(self,field_name, memb_name,triangle_func=True,evaluate_funct=None,*args):
self.triangle_func = triangle_func
self.field_name = field_name
self.memb_name = m... | 0.561696 | 0.416203 |
import asyncio
import os
import traceback
from datetime import datetime
from copy import deepcopy
from math import ceil
from random import choice, seed
from statistics import mean
from time import time
import cfg
import discord
import translate
import utils
from utils import log
try:
import patreon_info
except Im... | functions.py | import asyncio
import os
import traceback
from datetime import datetime
from copy import deepcopy
from math import ceil
from random import choice, seed
from statistics import mean
from time import time
import cfg
import discord
import translate
import utils
from utils import log
try:
import patreon_info
except Im... | 0.319971 | 0.112722 |
from typing import Tuple, Callable, Optional, Sequence, Union, Dict, Mapping, Set
from types import MappingProxyType
import numpy as np
import contextlib
import itertools
import functools
import warnings
import logging
try:
import tek_awg
except ImportError: # pragma: no cover
warnings.warn("Could not import ... | qupulse/hardware/awgs/tektronix.py | from typing import Tuple, Callable, Optional, Sequence, Union, Dict, Mapping, Set
from types import MappingProxyType
import numpy as np
import contextlib
import itertools
import functools
import warnings
import logging
try:
import tek_awg
except ImportError: # pragma: no cover
warnings.warn("Could not import ... | 0.897285 | 0.273362 |
# Copyright 2022 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This script supports visualizing all histograms found in an inspect snapshot.
To use you need to have a snapshot.zip file either generated by `ffx snapsh... | src/diagnostics/scripts/snapshot_histograms.py | $ unzip /path/to/snapshot.zip
$ python3 snapshot_histograms.py /path/to/unzipped/inspect.json
// open html in browser. | 0.393152 | 0.597256 |
import numpy as np
def e_exp(parameters, *data):
x,y=data
b=parameters
return ((np.exp(-b*x) - y)**2).mean()
def e_cumulative(parameters, *data):
x,y=data
t=parameters
return (((x<=t)*1 - y)**2).mean()
def e_cumulative_linear(parameters, *data):
x,y=data
t=parameters
return (((x<=... | tools/curve_funcs.py | import numpy as np
def e_exp(parameters, *data):
x,y=data
b=parameters
return ((np.exp(-b*x) - y)**2).mean()
def e_cumulative(parameters, *data):
x,y=data
t=parameters
return (((x<=t)*1 - y)**2).mean()
def e_cumulative_linear(parameters, *data):
x,y=data
t=parameters
return (((x<=... | 0.330363 | 0.495911 |
import os
import django
from django.conf import settings
def pytest_configure():
test_db = os.environ.get("TEST_DB", "sqlite")
installed_apps = [
"django.contrib.contenttypes",
"django.contrib.auth",
"tests.generic",
"tests.ambiguous",
"tests.ambiguous2",
]
us... | tests/conftest.py | import os
import django
from django.conf import settings
def pytest_configure():
test_db = os.environ.get("TEST_DB", "sqlite")
installed_apps = [
"django.contrib.contenttypes",
"django.contrib.auth",
"tests.generic",
"tests.ambiguous",
"tests.ambiguous2",
]
us... | 0.256366 | 0.123736 |
import numpy as np
import h5py
import sys
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from gensim.models import word2vec
from gensim.models import KeyedVectors
def main():
if len(sys.ar... | gen_text.py | import numpy as np
import h5py
import sys
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from gensim.models import word2vec
from gensim.models import KeyedVectors
def main():
if len(sys.ar... | 0.421433 | 0.367866 |
from typing import List, Tuple, Type, TypeVar, Union
from mpyc.finfields import PrimeFieldElement
from mpyc.runtime import mpc
from mpyc.sectypes import SecureFixedPoint, SecureInteger, SecureNumber
from numpy import array, concatenate, diagflat, reshape, tril_indices, triu_indices
from tno.mpc.mpyc.stubs.asyncoro im... | tno/mpc/mpyc/matrix_inverse/matrix_inverse.py | from typing import List, Tuple, Type, TypeVar, Union
from mpyc.finfields import PrimeFieldElement
from mpyc.runtime import mpc
from mpyc.sectypes import SecureFixedPoint, SecureInteger, SecureNumber
from numpy import array, concatenate, diagflat, reshape, tril_indices, triu_indices
from tno.mpc.mpyc.stubs.asyncoro im... | 0.919688 | 0.662759 |
import multiprocessing
import sys
from os.path import basename, join, splitext
from Bio.SeqIO.FastaIO import SimpleFastaParser
from Bio.SeqIO.QualityIO import FastqGeneralIterator
from . import blast, db, db_preprocessor, log, util
def preprocess(args):
"""Build the databases required by atram."""
log.setup... | bin/aTRAM-master/lib/core_preprocessor.py | import multiprocessing
import sys
from os.path import basename, join, splitext
from Bio.SeqIO.FastaIO import SimpleFastaParser
from Bio.SeqIO.QualityIO import FastqGeneralIterator
from . import blast, db, db_preprocessor, log, util
def preprocess(args):
"""Build the databases required by atram."""
log.setup... | 0.484868 | 0.13852 |
import gzip
import os
import random
import sys
import catboost
import geopandas
import numpy as np
import pandas
import pandas as pd
import xarray
from shapely.geometry import box
DATASETS_PATH = os.environ.get('DATASETS_PATH', '../data/')
MODELS_PATH = os.path.dirname(os.path.realpath(__file__))
OSM_GEO_DATA = os.pa... | catboost_ncep_osm/predict.py | import gzip
import os
import random
import sys
import catboost
import geopandas
import numpy as np
import pandas
import pandas as pd
import xarray
from shapely.geometry import box
DATASETS_PATH = os.environ.get('DATASETS_PATH', '../data/')
MODELS_PATH = os.path.dirname(os.path.realpath(__file__))
OSM_GEO_DATA = os.pa... | 0.305283 | 0.340732 |
import json
from os import cpu_count
from typing import Optional
import jwt
import requests
from flask import request, current_app, jsonify, g
from json.decoder import JSONDecodeError
from jwt import InvalidSignatureError, InvalidAudienceError, DecodeError
from requests.exceptions import ConnectionError, InvalidURL, H... | code/api/utils.py | import json
from os import cpu_count
from typing import Optional
import jwt
import requests
from flask import request, current_app, jsonify, g
from json.decoder import JSONDecodeError
from jwt import InvalidSignatureError, InvalidAudienceError, DecodeError
from requests.exceptions import ConnectionError, InvalidURL, H... | 0.675015 | 0.150621 |
from typing import overload
from UdonPie import System
from UdonPie.Undefined import *
class TimeZoneInfo:
def __new__(cls, arg1=None):
'''
:returns: TimeZoneInfo
:rtype: System.TimeZoneInfo
'''
pass
@staticmethod
def get_Id():
'''
:returns: String... | System/TimeZoneInfo/__init__.py | from typing import overload
from UdonPie import System
from UdonPie.Undefined import *
class TimeZoneInfo:
def __new__(cls, arg1=None):
'''
:returns: TimeZoneInfo
:rtype: System.TimeZoneInfo
'''
pass
@staticmethod
def get_Id():
'''
:returns: String... | 0.893359 | 0.133698 |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_rem... | ratings/migrations/0001_initial.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_rem... | 0.552781 | 0.101589 |
from __future__ import division
import enum
import errno
import json
import os
import pprint
import time
from abc import ABCMeta, abstractmethod, abstractproperty
from collections import namedtuple
import numpy as np
import click
class GoldenOutputNotAvailableError(Exception):
pass
class NoCorrectnessDesire... | plaidbench/plaidbench/core.py |
from __future__ import division
import enum
import errno
import json
import os
import pprint
import time
from abc import ABCMeta, abstractmethod, abstractproperty
from collections import namedtuple
import numpy as np
import click
class GoldenOutputNotAvailableError(Exception):
pass
class NoCorrectnessDesire... | 0.741206 | 0.09343 |
import numpy as np
from scipy.optimize import minimize
from scipy.linalg import null_space
from pymoo.model.algorithm import Algorithm
from pymoo.model.duplicate import DefaultDuplicateElimination
from pymoo.model.individual import Individual
from pymoo.model.initialization import Initialization
from multiprocessing im... | mobo/solver/pareto_discovery/pareto_discovery.py | import numpy as np
from scipy.optimize import minimize
from scipy.linalg import null_space
from pymoo.model.algorithm import Algorithm
from pymoo.model.duplicate import DefaultDuplicateElimination
from pymoo.model.individual import Individual
from pymoo.model.initialization import Initialization
from multiprocessing im... | 0.612541 | 0.488222 |
"""Tests for WENO reconstruction."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest # pylint: disable=g-bad-import-order
from absl.testing import parameterized
import numpy as np
from pde_superresolution import weno
cl... | pde_superresolution/weno_test.py | """Tests for WENO reconstruction."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest # pylint: disable=g-bad-import-order
from absl.testing import parameterized
import numpy as np
from pde_superresolution import weno
cl... | 0.75401 | 0.70517 |