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 |
|---|---|---|---|---|
# The __main__ function included with jsonrpc.py. Has not been ported to Python 3.
import sys
import dateutil.parser
from datetime import datetime as dt
from twisted.internet import reactor
from twisted.logger import Logger, textFileLogObserver
from asyncsteem import RpcClient
#When processing a block we call this f... | examples/jsonrpc_main.py |
# The __main__ function included with jsonrpc.py. Has not been ported to Python 3.
import sys
import dateutil.parser
from datetime import datetime as dt
from twisted.internet import reactor
from twisted.logger import Logger, textFileLogObserver
from asyncsteem import RpcClient
#When processing a block we call this f... | 0.371365 | 0.130285 |
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
from .config import Config
from .gif_encoder import GIFEncoder
from .opencv_encoder import OpenCVEncoder
from .text_format import irepr
from .text_painter import TextPainter
from .webp_encoder import WebPEncoder
WATERMARK = "Generated by vardbg"
SA... | vardbg/output/video_writer/renderer.py | from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
from .config import Config
from .gif_encoder import GIFEncoder
from .opencv_encoder import OpenCVEncoder
from .text_format import irepr
from .text_painter import TextPainter
from .webp_encoder import WebPEncoder
WATERMARK = "Generated by vardbg"
SA... | 0.736116 | 0.119049 |
import numpy as np
import torch
import pytest
from torch import tensor, cuda
from mrphy import γH, dt0, rfmax0, smax0
from mrphy import utils
if torch.cuda.is_available():
import cupy as cp
# TODO:
# unit_tests for other utils functions
def to_np(x):
return x.detach().cpu().numpy()
class Test_utils:
d... | tests/test_utils.py | import numpy as np
import torch
import pytest
from torch import tensor, cuda
from mrphy import γH, dt0, rfmax0, smax0
from mrphy import utils
if torch.cuda.is_available():
import cupy as cp
# TODO:
# unit_tests for other utils functions
def to_np(x):
return x.detach().cpu().numpy()
class Test_utils:
d... | 0.347094 | 0.729122 |
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import time
import json
import argparse
import random
# Arguments
parser = argparse.ArgumentParser()
parser.add_argument("--thing-name", action="store", required=True,
help="Name of the Thing that will run this program")
parser.add_argument("--c... | iot-simulator/iot_thing_simulator.py | from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import time
import json
import argparse
import random
# Arguments
parser = argparse.ArgumentParser()
parser.add_argument("--thing-name", action="store", required=True,
help="Name of the Thing that will run this program")
parser.add_argument("--c... | 0.439026 | 0.043447 |
import collections
import logging
import re
from google.appengine.api import users
from gae_libs.handlers.base_handler import BaseHandler, Permission
from gae_libs.dashboard_util import GetPagedResults
from handlers.code_coverage import utils
from libs.time_util import ConvertUTCToPST
from model.code_coverage import... | appengine/findit/handlers/code_coverage/serve_coverage.py |
import collections
import logging
import re
from google.appengine.api import users
from gae_libs.handlers.base_handler import BaseHandler, Permission
from gae_libs.dashboard_util import GetPagedResults
from handlers.code_coverage import utils
from libs.time_util import ConvertUTCToPST
from model.code_coverage import... | 0.548674 | 0.239549 |
import pyrogue as pr
import rogue.protocols.udp
import rogue.protocols.rssi
import rogue.protocols.packetizer
import time
class UdpRssiPack(pr.Device):
def __init__(self,*, port, host='127.0.0.1', jumbo=False, wait=True, packVer=1, pollInterval=1, enSsi=True, server=False, **kwargs):
super(self.__class__... | python/pyrogue/protocols/_Network.py | import pyrogue as pr
import rogue.protocols.udp
import rogue.protocols.rssi
import rogue.protocols.packetizer
import time
class UdpRssiPack(pr.Device):
def __init__(self,*, port, host='127.0.0.1', jumbo=False, wait=True, packVer=1, pollInterval=1, enSsi=True, server=False, **kwargs):
super(self.__class__... | 0.253676 | 0.068756 |
import datetime
import sys
from importlib import util as import_util
from setuptools import find_packages, setup
spec = import_util.spec_from_file_location("_metadata", "mava/_metadata.py")
_metadata = import_util.module_from_spec(spec) # type: ignore
spec.loader.exec_module(_metadata) # type: ignore
reverb_requir... | setup.py | import datetime
import sys
from importlib import util as import_util
from setuptools import find_packages, setup
spec = import_util.spec_from_file_location("_metadata", "mava/_metadata.py")
_metadata = import_util.module_from_spec(spec) # type: ignore
spec.loader.exec_module(_metadata) # type: ignore
reverb_requir... | 0.384681 | 0.324503 |
import time
from collections import defaultdict
import requests
import grpc
from tests.integration.aurorabridge_test.client import api
from tests.integration.stateless_job import list_jobs, StatelessJob
from tests.integration.util import load_config
TEST_CONFIG_DIR = "/aurorabridge_test/test_configs"
def wait_for_r... | tests/integration/aurorabridge_test/util.py | import time
from collections import defaultdict
import requests
import grpc
from tests.integration.aurorabridge_test.client import api
from tests.integration.stateless_job import list_jobs, StatelessJob
from tests.integration.util import load_config
TEST_CONFIG_DIR = "/aurorabridge_test/test_configs"
def wait_for_r... | 0.681939 | 0.184437 |
import os
from pprint import pprint
import pyrotein as pr
import numpy as np
# [[[ OBTAIN THE CONSENSUS SEQUENCE ]]]
# Read the sequence alignment result...
## fl_aln = 'step3.psa.fasta'
fl_aln = 'xfam.step4.psa.fil.fasta'
seq_dict = pr.fasta.read(fl_aln)
# Obtain the consensus sequence (super seq)...
tally_dic... | examples/fasta.get_label.py |
import os
from pprint import pprint
import pyrotein as pr
import numpy as np
# [[[ OBTAIN THE CONSENSUS SEQUENCE ]]]
# Read the sequence alignment result...
## fl_aln = 'step3.psa.fasta'
fl_aln = 'xfam.step4.psa.fil.fasta'
seq_dict = pr.fasta.read(fl_aln)
# Obtain the consensus sequence (super seq)...
tally_dic... | 0.324663 | 0.174797 |
import time
import random
import hashlib
from social.utils import setting_name, to_setting_name, module_member
from social.store import OpenIdStore
class BaseTemplateStrategy(object):
def __init__(self, strategy):
self.strategy = strategy
def render(self, tpl=None, html=None, context=None):
... | social/strategies/base.py | import time
import random
import hashlib
from social.utils import setting_name, to_setting_name, module_member
from social.store import OpenIdStore
class BaseTemplateStrategy(object):
def __init__(self, strategy):
self.strategy = strategy
def render(self, tpl=None, html=None, context=None):
... | 0.52902 | 0.086285 |
"""Interface for running and training the model."""
import numpy as np
import ttools
import torch as th
from sbmc import losses
from ttools.modules.image_operators import crop_like
from torch.optim import lr_scheduler
from tensorboardX import SummaryWriter
LOG = ttools.get_logger(__name__)
__all__ = ["SampleBasedD... | sbmc/interfaces.py | """Interface for running and training the model."""
import numpy as np
import ttools
import torch as th
from sbmc import losses
from ttools.modules.image_operators import crop_like
from torch.optim import lr_scheduler
from tensorboardX import SummaryWriter
LOG = ttools.get_logger(__name__)
__all__ = ["SampleBasedD... | 0.944048 | 0.390011 |
from six import add_metaclass
try:
from functools import total_ordering
except ImportError: # pragma: no cover
from .backports.total_ordering import total_ordering # pragma: no cover
def safe_string(value):
"""
consistently converts a value to a string
:param value:
:return: str
"""
... | limits/limits.py | from six import add_metaclass
try:
from functools import total_ordering
except ImportError: # pragma: no cover
from .backports.total_ordering import total_ordering # pragma: no cover
def safe_string(value):
"""
consistently converts a value to a string
:param value:
:return: str
"""
... | 0.742328 | 0.357315 |
from __future__ import absolute_import
# pylint: skip-file
# pylint: disable=C0103
import sys
from salt.ext.six.moves import map
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
import os
import stat
import time
import tempfile
import shutil
from ioflo.aid.odicting import odict... | salt/daemons/test/test_raetkey.py | from __future__ import absolute_import
# pylint: skip-file
# pylint: disable=C0103
import sys
from salt.ext.six.moves import map
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
import os
import stat
import time
import tempfile
import shutil
from ioflo.aid.odicting import odict... | 0.223971 | 0.161089 |
from engine.collision import CollisionCache, PositionalCollisionCache
from engine.collision import resolve_physical_collision
from engine.event_dispatcher import EventDispatcher
from engine.geometry import detect_overlap_2d
from .world_object import WorldObject, COLLIDER, TRIGGER
class World2d(EventDispatcher):
"... | engine/world/world_2d.py | from engine.collision import CollisionCache, PositionalCollisionCache
from engine.collision import resolve_physical_collision
from engine.event_dispatcher import EventDispatcher
from engine.geometry import detect_overlap_2d
from .world_object import WorldObject, COLLIDER, TRIGGER
class World2d(EventDispatcher):
"... | 0.937498 | 0.438064 |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['deprecated'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: avi_alert
author: <NAME> (<EMAIL>)
deprecated:
removed_in: '2.11'
why: Removed support for this module.
alternative: Use M(avi_api_... | library/_avi_alert.py |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['deprecated'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: avi_alert
author: <NAME> (<EMAIL>)
deprecated:
removed_in: '2.11'
why: Removed support for this module.
alternative: Use M(avi_api_... | 0.711932 | 0.303242 |
import sys
from unittest import TestCase
from kazoo.protocol import paths
if sys.version_info > (3, ): # pragma: nocover
def u(s):
return s
else: # pragma: nocover
def u(s):
return unicode(s, "unicode_escape")
class NormPathTestCase(TestCase):
def test_normpath(self):
self.as... | desktop/core/ext-py/kazoo-2.0/kazoo/tests/test_paths.py | import sys
from unittest import TestCase
from kazoo.protocol import paths
if sys.version_info > (3, ): # pragma: nocover
def u(s):
return s
else: # pragma: nocover
def u(s):
return unicode(s, "unicode_escape")
class NormPathTestCase(TestCase):
def test_normpath(self):
self.as... | 0.270095 | 0.343094 |
airy_jvm_deps = [
"com.amazonaws:aws-java-sdk-core:1.11.933",
"com.amazonaws:aws-java-sdk-s3:1.11.933",
"com.fasterxml.jackson.core:jackson-annotations:2.10.0",
"com.fasterxml.jackson.core:jackson-core:2.10.0",
"com.fasterxml.jackson.core:jackson-databind:2.10.0",
"com.fasterxml.jackson.module:j... | repositories.bzl | airy_jvm_deps = [
"com.amazonaws:aws-java-sdk-core:1.11.933",
"com.amazonaws:aws-java-sdk-s3:1.11.933",
"com.fasterxml.jackson.core:jackson-annotations:2.10.0",
"com.fasterxml.jackson.core:jackson-core:2.10.0",
"com.fasterxml.jackson.core:jackson-databind:2.10.0",
"com.fasterxml.jackson.module:j... | 0.566139 | 0.232158 |
from __future__ import unicode_literals
from django.db import models, migrations
import django
if django.VERSION[:2] >= (1, 11):
from django.contrib.postgres.fields import JSONField
DjangoJsonField = JSONField
else:
import django_pgjson.fields
DjangoJsonField = django_pgjson.fields.JsonBField
class M... | apps/configuration/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import models, migrations
import django
if django.VERSION[:2] >= (1, 11):
from django.contrib.postgres.fields import JSONField
DjangoJsonField = JSONField
else:
import django_pgjson.fields
DjangoJsonField = django_pgjson.fields.JsonBField
class M... | 0.625324 | 0.190009 |
from .fixtures import (
app_client,
make_app_client,
TestClient as _TestClient,
EXPECTED_PLUGINS,
)
import asyncio
from datasette.plugins import DEFAULT_PLUGINS
from datasette.cli import cli, serve
from datasette.version import __version__
from datasette.utils.sqlite import sqlite3
from click.testing im... | tests/test_cli.py | from .fixtures import (
app_client,
make_app_client,
TestClient as _TestClient,
EXPECTED_PLUGINS,
)
import asyncio
from datasette.plugins import DEFAULT_PLUGINS
from datasette.cli import cli, serve
from datasette.version import __version__
from datasette.utils.sqlite import sqlite3
from click.testing im... | 0.469277 | 0.326513 |
import numpy as np
import unittest
from rdkit import Chem
from deepchem.feat import coulomb_matrices as cm
from deepchem.utils import conformers
class TestCoulombMatrix(unittest.TestCase):
"""
Tests for CoulombMatrix.
"""
def setUp(self):
"""
Set up tests.
"""
smiles ... | deepchem/feat/tests/test_coulomb_matrices.py | import numpy as np
import unittest
from rdkit import Chem
from deepchem.feat import coulomb_matrices as cm
from deepchem.utils import conformers
class TestCoulombMatrix(unittest.TestCase):
"""
Tests for CoulombMatrix.
"""
def setUp(self):
"""
Set up tests.
"""
smiles ... | 0.776623 | 0.711869 |
import logging
import requests
import json
from ComunioScore.exceptions import ComunioAccessTokenError
class ComunioRequest:
""" class ComunioRequest to request basic api data from comunio
USAGE:
comrequest = ComunioRequest()
if comrequest.login(username='', password='')
... | ComunioScore/comunio_request.py | import logging
import requests
import json
from ComunioScore.exceptions import ComunioAccessTokenError
class ComunioRequest:
""" class ComunioRequest to request basic api data from comunio
USAGE:
comrequest = ComunioRequest()
if comrequest.login(username='', password='')
... | 0.411939 | 0.095898 |
import os
import sys
import time
import rumps
import numpy
import cv2
import threading
TOGGLE_OSASCRIPT = """osascript -e '
using terms from application "{}"
if player state of application "{}" is paused then
tell application "{}" to play
else
tell application "{}" to pause
end if
end using terms from'"""
XMLD... | voleter.py | import os
import sys
import time
import rumps
import numpy
import cv2
import threading
TOGGLE_OSASCRIPT = """osascript -e '
using terms from application "{}"
if player state of application "{}" is paused then
tell application "{}" to play
else
tell application "{}" to pause
end if
end using terms from'"""
XMLD... | 0.112101 | 0.171234 |
import os
import sys
import PythonQt
from PythonQt import QtCore, QtGui
import ddapp.applogic as app
from ddapp import jointcontrol
from ddapp import lcmUtils
from ddapp import robotstate
from ddapp.timercallback import TimerCallback
import functools
import drc as lcmdrc
class PlanChecker(object):
def __init__... | externals/director/src/python/scripts/collisionViewer.py | import os
import sys
import PythonQt
from PythonQt import QtCore, QtGui
import ddapp.applogic as app
from ddapp import jointcontrol
from ddapp import lcmUtils
from ddapp import robotstate
from ddapp.timercallback import TimerCallback
import functools
import drc as lcmdrc
class PlanChecker(object):
def __init__... | 0.268078 | 0.096025 |
# Author: <NAME> & <NAME>
# zachetie **at** gmail **dot* com
# Import all needed modules from NRPy+/Python:
import numpy as np
def compute_Hreal(m1=23., m2=10., EMgamma=0.577215664901532860606512090082402431, tortoise=1,
x=2.129681018601393e+01, y=0.000000000000000e+00, z=0.000000000000000e... | SEOBNR/SEOBNR_v3_Hamiltonian.py |
# Author: <NAME> & <NAME>
# zachetie **at** gmail **dot* com
# Import all needed modules from NRPy+/Python:
import numpy as np
def compute_Hreal(m1=23., m2=10., EMgamma=0.577215664901532860606512090082402431, tortoise=1,
x=2.129681018601393e+01, y=0.000000000000000e+00, z=0.000000000000000e... | 0.463201 | 0.448124 |
# Lint as: python2, python3
"""Reward functions for ML fairness gym.
These transforms are used to extract scalar rewards from state variables.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Any, Optional
import core
import numpy as... | rewards.py |
# Lint as: python2, python3
"""Reward functions for ML fairness gym.
These transforms are used to extract scalar rewards from state variables.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Any, Optional
import core
import numpy as... | 0.904447 | 0.665679 |
import config
class Infer:
def __init__(self, graph):
# self.config = config
self.graph = graph.getInstance(config.NEO4F_CONF)
self.relationship_keyword = {
"朋友": "friend"
}
def similar_entity(self, entity_list_from_st: list, rules: [dict]) -> list:
"""
... | util/infer.py | import config
class Infer:
def __init__(self, graph):
# self.config = config
self.graph = graph.getInstance(config.NEO4F_CONF)
self.relationship_keyword = {
"朋友": "friend"
}
def similar_entity(self, entity_list_from_st: list, rules: [dict]) -> list:
"""
... | 0.323487 | 0.223737 |
from __future__ import print_function
# the following is a hack to get the baseclient to import whether we're in a
# package or not. This makes pep8 unhappy hence the annotations.
try:
# baseclient and this client are in a package
from .baseclient import BaseClient as _BaseClient # @UnusedImport
except:
#... | lib/KBaseReport/KBaseReportClient.py |
from __future__ import print_function
# the following is a hack to get the baseclient to import whether we're in a
# package or not. This makes pep8 unhappy hence the annotations.
try:
# baseclient and this client are in a package
from .baseclient import BaseClient as _BaseClient # @UnusedImport
except:
#... | 0.719482 | 0.144119 |
import os
import subprocess
import traceback
import time
import string
import random
import requests
requests.packages.urllib3.disable_warnings()
def main():
build_path = "file://%s/%s" % (os.path.dirname(os.path.realpath(__file__)),
"quickstart-build.tar.gz")
host_inf... | deploy-sentinel/quickstart.py |
import os
import subprocess
import traceback
import time
import string
import random
import requests
requests.packages.urllib3.disable_warnings()
def main():
build_path = "file://%s/%s" % (os.path.dirname(os.path.realpath(__file__)),
"quickstart-build.tar.gz")
host_inf... | 0.193719 | 0.044101 |
from sawtooth_sdk.processor.exceptions import InvalidTransaction
from rbac.common import addresser
from rbac.common.protobuf import proposal_state_pb2
from rbac.processor import message_accessor, state_accessor
from rbac.processor.role import role_validator
from rbac.processor.task import task_validator
def has_no... | rbac/processor/proposal_validator.py |
from sawtooth_sdk.processor.exceptions import InvalidTransaction
from rbac.common import addresser
from rbac.common.protobuf import proposal_state_pb2
from rbac.processor import message_accessor, state_accessor
from rbac.processor.role import role_validator
from rbac.processor.task import task_validator
def has_no... | 0.654895 | 0.230422 |
import functools
import sys
import warnings
import arviz as az
def map_args(func):
swaps = [
('varnames', 'var_names')
]
@functools.wraps(func)
def wrapped(*args, **kwargs):
for (old, new) in swaps:
if old in kwargs and new not in kwargs:
warnings.warn('Keyw... | pymc3/plots/__init__.py | import functools
import sys
import warnings
import arviz as az
def map_args(func):
swaps = [
('varnames', 'var_names')
]
@functools.wraps(func)
def wrapped(*args, **kwargs):
for (old, new) in swaps:
if old in kwargs and new not in kwargs:
warnings.warn('Keyw... | 0.565539 | 0.203391 |
import time
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn, optim
import torchvision
import dataloader
import utils
class MaskedConv2d(nn.Conv2d):
def __init__(self, mask_type, *args, **kwargs):
super(MaskedConv2d, self).__init__(*args, **kwargs)
assert mask... | pixelcnn.py | import time
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn, optim
import torchvision
import dataloader
import utils
class MaskedConv2d(nn.Conv2d):
def __init__(self, mask_type, *args, **kwargs):
super(MaskedConv2d, self).__init__(*args, **kwargs)
assert mask... | 0.847795 | 0.598048 |
from dfg import checkCandidate, get_dfg_graph
import matplotlib.pyplot as plt
import numpy as np
import os ... | src/custom_utils.py | from dfg import checkCandidate, get_dfg_graph
import matplotlib.pyplot as plt
import numpy as np
import os ... | 0.400046 | 0.387574 |
from biokbase.narrative.jobs.appmanager import AppManager
import biokbase.narrative.jobs.specmanager as specmanager
import biokbase.narrative.app_util as app_util
from biokbase.narrative.jobs.job import Job
from IPython.display import HTML
import unittest
import mock
from .narrative_mock.mockclients import get_mock_cli... | src/biokbase/narrative/tests/test_appmanager.py | from biokbase.narrative.jobs.appmanager import AppManager
import biokbase.narrative.jobs.specmanager as specmanager
import biokbase.narrative.app_util as app_util
from biokbase.narrative.jobs.job import Job
from IPython.display import HTML
import unittest
import mock
from .narrative_mock.mockclients import get_mock_cli... | 0.580471 | 0.171755 |
import math
import tensorflow as tf
from tensorflow.python.util import nest
import collections
import pdb
_FRUStateTuple = collections.namedtuple("FRUStateTuple", ("state", "t"))
class FRUStateTuple(_FRUStateTuple):
"""Tuple used by FRU Cells for `state_size`, `zero_state`, and output state.
Stores two ele... | code/fru.py | import math
import tensorflow as tf
from tensorflow.python.util import nest
import collections
import pdb
_FRUStateTuple = collections.namedtuple("FRUStateTuple", ("state", "t"))
class FRUStateTuple(_FRUStateTuple):
"""Tuple used by FRU Cells for `state_size`, `zero_state`, and output state.
Stores two ele... | 0.85341 | 0.582847 |
from numpydoc.docscrape import NumpyDocString, Reader
#------------------------------------------------------------------------------
class FixedReader(Reader):
# TODO: see `FixedNumpyDocString`
def read_to_next_empty_line(self):
return super(FixedReader, self).read_to_next_empty_line() + ['']
#--------------... | pyramid_describe/syntax/numpydoc/extractor.py | from numpydoc.docscrape import NumpyDocString, Reader
#------------------------------------------------------------------------------
class FixedReader(Reader):
# TODO: see `FixedNumpyDocString`
def read_to_next_empty_line(self):
return super(FixedReader, self).read_to_next_empty_line() + ['']
#--------------... | 0.246533 | 0.21564 |
from oslo_utils import uuidutils
import testtools
from neutron.agent.linux import ip_lib
from neutron.common import utils as common_utils
from neutron.privileged.agent.linux import ip_lib as priv_ip_lib
from neutron.tests.functional import base as functional_base
class GetDeviceNamesTestCase(functional_base.BaseSud... | neutron/tests/functional/privileged/agent/linux/test_ip_lib.py |
from oslo_utils import uuidutils
import testtools
from neutron.agent.linux import ip_lib
from neutron.common import utils as common_utils
from neutron.privileged.agent.linux import ip_lib as priv_ip_lib
from neutron.tests.functional import base as functional_base
class GetDeviceNamesTestCase(functional_base.BaseSud... | 0.383641 | 0.242749 |
import os
import sys
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import nevergrad as ng
from tqdm.notebook import tqdm
from src.graph import Node, Edge, Graph
from src.processing import process_embedding_from_words
class NoPrint:
def __enter__(self):
self... | factor_graph/utils_taxonomy.py | import os
import sys
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import nevergrad as ng
from tqdm.notebook import tqdm
from src.graph import Node, Edge, Graph
from src.processing import process_embedding_from_words
class NoPrint:
def __enter__(self):
self... | 0.405213 | 0.319931 |
import tensorflow as tf
def resnet(x, residual_depth, training):
"""Residual convolutional neural network with global average pooling"""
x = tf.layers.conv3d(x, 16, [3, 3, 3], strides=1, padding='SAME', use_bias=False,
kernel_initializer=tf.contrib.layers.variance_scaling_initializer... | charles-university/deep-learning/labs/06/resnet.py | import tensorflow as tf
def resnet(x, residual_depth, training):
"""Residual convolutional neural network with global average pooling"""
x = tf.layers.conv3d(x, 16, [3, 3, 3], strides=1, padding='SAME', use_bias=False,
kernel_initializer=tf.contrib.layers.variance_scaling_initializer... | 0.945235 | 0.748674 |
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | lra_benchmarks/models/local/local_attention.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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | 0.96184 | 0.557364 |
import ast
import copy
import inspect
import sys
from typing import Any, Dict, List, Optional, Tuple
from dace import data, symbolic
from dace.config import Config
from dace.frontend.python import ndloop, wrappers
from dace.frontend.python import astutils
from dace.frontend.python.astutils import unparse, rname
from d... | dace/frontend/python/tasklet_runner.py | import ast
import copy
import inspect
import sys
from typing import Any, Dict, List, Optional, Tuple
from dace import data, symbolic
from dace.config import Config
from dace.frontend.python import ndloop, wrappers
from dace.frontend.python import astutils
from dace.frontend.python.astutils import unparse, rname
from d... | 0.64232 | 0.416085 |
import pytest
from xchainpy.xchainpy_binance.clients import Client
from xchainpy.xchainpy_util.asset import Asset
class TestClient:
# Note: This phrase is created by https://iancoleman.io/bip39/ and will never been used in a real-world
phrase = 'rural bright ball negative already grass good grant nation scree... | xchainpy/xchainpy_binance/test/test_clients.py | import pytest
from xchainpy.xchainpy_binance.clients import Client
from xchainpy.xchainpy_util.asset import Asset
class TestClient:
# Note: This phrase is created by https://iancoleman.io/bip39/ and will never been used in a real-world
phrase = 'rural bright ball negative already grass good grant nation scree... | 0.657318 | 0.604282 |
import os
import sys
import time
import warnings
from typing import Dict, List
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sb
import sfaira
# Set global variables.
print(f'sys.argv: {sys.argv}')
N_DRAWS = 320_000
LEN_IDX = 5_000_000
BATCH_SIZE = 1 # must be 0 or 1
OBS_K... | sfaira/data/utils_scripts/test_store.py |
import os
import sys
import time
import warnings
from typing import Dict, List
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sb
import sfaira
# Set global variables.
print(f'sys.argv: {sys.argv}')
N_DRAWS = 320_000
LEN_IDX = 5_000_000
BATCH_SIZE = 1 # must be 0 or 1
OBS_K... | 0.408513 | 0.214373 |
import os
import re
import sh
import pytest
from binaryornot.check import is_binary
PATTERN = '{{(\s?cookiecutter)[.](.*?)}}'
RE_OBJ = re.compile(PATTERN)
@pytest.fixture
def context():
return {
'project_name': 'My Test Project',
'project_slug': 'my_test_project',
'author_name': 'Test A... | tests/test_cookiecutter_generation.py |
import os
import re
import sh
import pytest
from binaryornot.check import is_binary
PATTERN = '{{(\s?cookiecutter)[.](.*?)}}'
RE_OBJ = re.compile(PATTERN)
@pytest.fixture
def context():
return {
'project_name': 'My Test Project',
'project_slug': 'my_test_project',
'author_name': 'Test A... | 0.511717 | 0.313538 |
profile_name_xpath = "//h1[@dir='auto']"
profile_bio_xpath = "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/span[1]/span[1]"
profil = "//a//img" # elements
i = 1
post_liker1 = "/html[1]/... | fb_xpath.py | profile_name_xpath = "//h1[@dir='auto']"
profile_bio_xpath = "/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/span[1]/span[1]"
profil = "//a//img" # elements
i = 1
post_liker1 = "/html[1]/... | 0.022297 | 0.050144 |
import logging
import ssl
import time
import traceback
from circuits import BaseComponent, Timer
from circuits.core.handlers import handler
from stompest.config import StompConfig
from stompest.protocol import StompSpec, StompSession
from stompest.sync import Stomp
from stompest.error import StompConnectionError, Stomp... | resilient-circuits/resilient_circuits/stomp_component.py | import logging
import ssl
import time
import traceback
from circuits import BaseComponent, Timer
from circuits.core.handlers import handler
from stompest.config import StompConfig
from stompest.protocol import StompSpec, StompSession
from stompest.sync import Stomp
from stompest.error import StompConnectionError, Stomp... | 0.40486 | 0.043855 |
import csv
from functools import lru_cache
import os
import time
from itertools import chain
from typing import Dict, List
from frameioclient import FrameioClient
class ClientNotTokenized(Exception):
pass
class RootAssetIDNotFound(Exception):
pass
@lru_cache()
def get_teams_from_account(client: Frameio... | examples/assets/asset_scraper.py |
import csv
from functools import lru_cache
import os
import time
from itertools import chain
from typing import Dict, List
from frameioclient import FrameioClient
class ClientNotTokenized(Exception):
pass
class RootAssetIDNotFound(Exception):
pass
@lru_cache()
def get_teams_from_account(client: Frameio... | 0.730097 | 0.214836 |
import base64
import json
import pprint
import urllib2
import collectd
import metric_info
# Global constants
DEFAULT_API_TIMEOUT = 60 # Seconds to wait for the RabbitMQ API to respond
DEFAULT_FIELD_LENGTH = 1023 # Assumes usage of the SignalFx fork of collectd
DEFAULT_METRIC_TYPE = 'gauge'
DEFAULT_REALM = 'Rabbit... | rabbitmq.py |
import base64
import json
import pprint
import urllib2
import collectd
import metric_info
# Global constants
DEFAULT_API_TIMEOUT = 60 # Seconds to wait for the RabbitMQ API to respond
DEFAULT_FIELD_LENGTH = 1023 # Assumes usage of the SignalFx fork of collectd
DEFAULT_METRIC_TYPE = 'gauge'
DEFAULT_REALM = 'Rabbit... | 0.767341 | 0.17621 |
import numpy as np
# Custom imports
from params import *
from datasets_utils import *
model = load_model('Depth5/best_0.1_12_2.h5', custom_objects={'tf': tf}, compile=False)
model.summary()
# Load image dataset
imgs, n_imgs, height, width, n_channels = load_img_dataset(shape_dir,
... | predict_images.py |
import numpy as np
# Custom imports
from params import *
from datasets_utils import *
model = load_model('Depth5/best_0.1_12_2.h5', custom_objects={'tf': tf}, compile=False)
model.summary()
# Load image dataset
imgs, n_imgs, height, width, n_channels = load_img_dataset(shape_dir,
... | 0.678433 | 0.272849 |
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['MVCNN', 'mvcnn']
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
class MVCNN(nn.Module):
def __init__(self, num_classes=1000):
super(MVCNN, self).__init__()
... | models/mvcnn.py | import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['MVCNN', 'mvcnn']
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
class MVCNN(nn.Module):
def __init__(self, num_classes=1000):
super(MVCNN, self).__init__()
... | 0.931431 | 0.429071 |
from flask import Flask,redirect, url_for, request
from random import *
import time
from .. import Application
from .. import Profit_Calculator
from .. import Risk_Calculator
from operator import add
from functools import reduce
import csv
def initialize():
global minShortMA
global maxShortMA
global stepS... | optimization/Strategies/StrategyOptimizer_MACD.py | from flask import Flask,redirect, url_for, request
from random import *
import time
from .. import Application
from .. import Profit_Calculator
from .. import Risk_Calculator
from operator import add
from functools import reduce
import csv
def initialize():
global minShortMA
global maxShortMA
global stepS... | 0.286269 | 0.193338 |
import talib
# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
context.s1 = "000001.XSHE"
# 使用MACD需要设置长短均线和macd平均线的参数
context.SHORTPERIOD = 12
context.LONGPERIOD = 26
context.SMOOTHPERIOD = 9
context.OBSERVATION = 100
# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
def handl... | performance/5.py | import talib
# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
context.s1 = "000001.XSHE"
# 使用MACD需要设置长短均线和macd平均线的参数
context.SHORTPERIOD = 12
context.LONGPERIOD = 26
context.SMOOTHPERIOD = 9
context.OBSERVATION = 100
# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
def handl... | 0.136321 | 0.403449 |
import argparse
import pandas as pd
from jqdatasdk import auth, logout, get_bars
from zvdata import IntervalLevel
from zvdata.api import df_to_db
from zvdata.recorder import FixedCycleDataRecorder
from zvdata.utils.pd_utils import pd_is_not_null
from zvdata.utils.time_utils import to_time_str, now_pd_timestamp, TIME_... | zvt/recorders/joinquant/quotes/jq_stock_kdata_recorder.py | import argparse
import pandas as pd
from jqdatasdk import auth, logout, get_bars
from zvdata import IntervalLevel
from zvdata.api import df_to_db
from zvdata.recorder import FixedCycleDataRecorder
from zvdata.utils.pd_utils import pd_is_not_null
from zvdata.utils.time_utils import to_time_str, now_pd_timestamp, TIME_... | 0.339828 | 0.148047 |
import sys
import os
import importlib
import matplotlib.pyplot as plt
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
#### Load own packages
import picasso_addon.io as io
import spt.analyze as analyze
import spt.analytic_expressions as anexpress
importlib.reload(analyze)
plt.style.use('~/lbFCS/st... | scripts/plotting/evaluate_immobile.py | import sys
import os
import importlib
import matplotlib.pyplot as plt
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
#### Load own packages
import picasso_addon.io as io
import spt.analyze as analyze
import spt.analytic_expressions as anexpress
importlib.reload(analyze)
plt.style.use('~/lbFCS/st... | 0.369884 | 0.270083 |
import frappe
import os
import redis
redis_server = None
@frappe.whitelist()
def get_pending_tasks_for_doc(doctype, docname):
return frappe.db.sql_list("select name from `tabAsync Task` where status in ('Queued', 'Running') and reference_doctype=%s and reference_name=%s", (doctype, docname))
def publish_progress... | frappe/realtime.py |
import frappe
import os
import redis
redis_server = None
@frappe.whitelist()
def get_pending_tasks_for_doc(doctype, docname):
return frappe.db.sql_list("select name from `tabAsync Task` where status in ('Queued', 'Running') and reference_doctype=%s and reference_name=%s", (doctype, docname))
def publish_progress... | 0.42656 | 0.088544 |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: fmgr_ha
notes:
- Full Documentation at U(https://ftnt-ansible-docs.readthedocs.io/en/latest/).
author:
- <NAME> (@lweighall)
- <NAME> (@Ghilli3)
- <NAME> (@p4r4n0y1ng)
short_descriptio... | lib/python3.8/site-packages/ansible_collections/community/network/plugins/modules/network/fortimanager/fmgr_ha.py |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: fmgr_ha
notes:
- Full Documentation at U(https://ftnt-ansible-docs.readthedocs.io/en/latest/).
author:
- <NAME> (@lweighall)
- <NAME> (@Ghilli3)
- <NAME> (@p4r4n0y1ng)
short_descriptio... | 0.771499 | 0.240953 |
import os
import sys
import string
from tkinter import messagebox
ROOT_DIR = os.path.abspath("../")
sys.path.append(ROOT_DIR)
from image_embedding.gen_vec_register import gen_vec_register
from image_embedding.gen_vec_add import gen_vec_add
from train_clf.train_svm import train_svm
from train_clf.train_knn import train... | btn_funcs/registers.py | import os
import sys
import string
from tkinter import messagebox
ROOT_DIR = os.path.abspath("../")
sys.path.append(ROOT_DIR)
from image_embedding.gen_vec_register import gen_vec_register
from image_embedding.gen_vec_add import gen_vec_add
from train_clf.train_svm import train_svm
from train_clf.train_knn import train... | 0.362066 | 0.180269 |
from celery.schedules import crontab
# CELERY
CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
PERIOD_BETWEEN_TASK = crontab(hour="*/6")
TIMEZONE = 'Europe/Warsaw'
# DATABASE
DB_NAME = 'contaggr'
DB_USER = 'postgres'
DB_PASSWORD = ''
DB_HOST = ''
DB_PORT = ''
# SITES VA... | config.py | from celery.schedules import crontab
# CELERY
CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
PERIOD_BETWEEN_TASK = crontab(hour="*/6")
TIMEZONE = 'Europe/Warsaw'
# DATABASE
DB_NAME = 'contaggr'
DB_USER = 'postgres'
DB_PASSWORD = ''
DB_HOST = ''
DB_PORT = ''
# SITES VA... | 0.127015 | 0.056835 |
from collections import deque
from ophyd import (
EpicsMotor,
PVPositioner,
PVPositionerPC,
EpicsSignal,
EpicsSignalRO,
Device,
)
from ophyd import Component as Cpt
from ophyd import FormattedComponent as FmtCpt
from ophyd import DynamicDeviceComponent as DDC
from ophyd import DeviceStatus, Ord... | startup/17-temperature_controllers.py | from collections import deque
from ophyd import (
EpicsMotor,
PVPositioner,
PVPositionerPC,
EpicsSignal,
EpicsSignalRO,
Device,
)
from ophyd import Component as Cpt
from ophyd import FormattedComponent as FmtCpt
from ophyd import DynamicDeviceComponent as DDC
from ophyd import DeviceStatus, Ord... | 0.587352 | 0.219955 |
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app.my_module.repdic import *
from app.my_module.scheduleparser import *
from app.my_module.stringformat import *
from app.my_module.process import *
from app.my_module.button import *
from... | app/views.py | from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app.my_module.repdic import *
from app.my_module.scheduleparser import *
from app.my_module.stringformat import *
from app.my_module.process import *
from app.my_module.button import *
from... | 0.1941 | 0.198258 |
import json
from common.object_validation import ObjectValidator
from common.type_validation import TypeValidator
from project import WALLET_URL
import lemoncheesecake.api as lcc
from echopy.echoapi.ws.simplewebsocket import SimpleWebsocket
class WalletBaseTest:
def __init__(self):
self.wallet_ws = Si... | common/wallet_base_test.py |
import json
from common.object_validation import ObjectValidator
from common.type_validation import TypeValidator
from project import WALLET_URL
import lemoncheesecake.api as lcc
from echopy.echoapi.ws.simplewebsocket import SimpleWebsocket
class WalletBaseTest:
def __init__(self):
self.wallet_ws = Si... | 0.380529 | 0.123921 |
from entities import *
class Model:
def __init__(self, *entities):
self.entities = entities
self.inputs = {}
self.outputs = {}
def define_input(self, name, conn, channels):
self.inputs[name] = (conn, channels)
def define_output(self, name, conn, channels):
self.ou... | main.py | from entities import *
class Model:
def __init__(self, *entities):
self.entities = entities
self.inputs = {}
self.outputs = {}
def define_input(self, name, conn, channels):
self.inputs[name] = (conn, channels)
def define_output(self, name, conn, channels):
self.ou... | 0.657428 | 0.234911 |
import sys
import os
import Fs.Nsp as Nsp
import Fs.Xci as Xci
import sq_tools
import Hex
from binascii import hexlify as hx, unhexlify as uhx
import listmanager
def get_key_fromdict(fp):
if fp.endswith('.nsp') or fp.endswith('.nsx'):
files_list=sq_tools.ret_nsp_offsets(fp)
files=list();filesizes=list... | py/ztools/lib/management.py | import sys
import os
import Fs.Nsp as Nsp
import Fs.Xci as Xci
import sq_tools
import Hex
from binascii import hexlify as hx, unhexlify as uhx
import listmanager
def get_key_fromdict(fp):
if fp.endswith('.nsp') or fp.endswith('.nsx'):
files_list=sq_tools.ret_nsp_offsets(fp)
files=list();filesizes=list... | 0.02198 | 0.054324 |
def menu():
from time import sleep
print('\33[34;1m' + '-' * 40 + f'\n{" MENU ":^40}\n' + '-' * 40 + '\33[m') # Impressão do cabeçalho do Menu
print('\33[33;1m1\33[m - \33[30mVer pessoas cadastradas\33[m')
print('\33[33;1m2\33[m - \33[30mCadastrar nova pessoa\33[m')
print('\33[33;1m3\33[m - \33[30m... | exs/mundo_3/python/ex115_modulo/__init__.py | def menu():
from time import sleep
print('\33[34;1m' + '-' * 40 + f'\n{" MENU ":^40}\n' + '-' * 40 + '\33[m') # Impressão do cabeçalho do Menu
print('\33[33;1m1\33[m - \33[30mVer pessoas cadastradas\33[m')
print('\33[33;1m2\33[m - \33[30mCadastrar nova pessoa\33[m')
print('\33[33;1m3\33[m - \33[30m... | 0.084773 | 0.138113 |
import time
from logger import logger
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.tests.index import IndexTest, DevIndexTest
class QueryTest(IndexTest):
"""
The base test which defines workflow for different view query tests. Access
phase represents mixed KV workload and queries... | perfrunner/tests/query.py | import time
from logger import logger
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.tests.index import IndexTest, DevIndexTest
class QueryTest(IndexTest):
"""
The base test which defines workflow for different view query tests. Access
phase represents mixed KV workload and queries... | 0.615319 | 0.479626 |
# Author: <NAME>
# Created: 24 August 2011
# Purpose: Reimplementation of the Q-learning perturbation
# testbed for multiple metacognition levels.
# ==============================================================
# directions
# =====================... | Constants.py |
# Author: <NAME>
# Created: 24 August 2011
# Purpose: Reimplementation of the Q-learning perturbation
# testbed for multiple metacognition levels.
# ==============================================================
# directions
# =====================... | 0.26971 | 0.142232 |
import os
import sys
import argparse
import mxnet as mx
def create_parser():
parser = argparse.ArgumentParser(
description=('Converts a dataset in MXNET RecordIO format '
'into a JPG format'))
parser.add_argument('rec_path', type=str,
help='specify the MXN... | train/tools/rec2jpg.py |
import os
import sys
import argparse
import mxnet as mx
def create_parser():
parser = argparse.ArgumentParser(
description=('Converts a dataset in MXNET RecordIO format '
'into a JPG format'))
parser.add_argument('rec_path', type=str,
help='specify the MXN... | 0.316686 | 0.211549 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import numpy as np
from six.moves import xrange as range_
from rlgraph import get_backend
from rlgraph.spaces import Space
from rlgraph.utils.initializer import Initializer
from rlgraph.utils.util ... | rlgraph/spaces/box_space.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import numpy as np
from six.moves import xrange as range_
from rlgraph import get_backend
from rlgraph.spaces import Space
from rlgraph.utils.initializer import Initializer
from rlgraph.utils.util ... | 0.914085 | 0.428174 |
from lenet import LeNet5
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.datasets.mnist import MNIST
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import visdom
import onnx
import pandas as pd
import numpy... | main.py | from lenet import LeNet5
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.datasets.mnist import MNIST
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import visdom
import onnx
import pandas as pd
import numpy... | 0.668988 | 0.47384 |
import gzip
import json
import os
import pprint
import pytest
import uuid
from base64 import b64decode
from mock import patch
from src import function
from test.mock_http_response import MockHttpResponse
from test.aws_log_events import AwsLogEvents
import asyncio
from asynctest import CoroutineMock
US_URL = "https:/... | test/log_ingestion_test.py | import gzip
import json
import os
import pprint
import pytest
import uuid
from base64 import b64decode
from mock import patch
from src import function
from test.mock_http_response import MockHttpResponse
from test.aws_log_events import AwsLogEvents
import asyncio
from asynctest import CoroutineMock
US_URL = "https:/... | 0.40392 | 0.167015 |
import os
import shutil
import datetime
TAG_CONST = "강의 Convex_Optimization"
def create_header(title: str, tag: str) -> str:
return f"---\ntitle: {title}\ntags: {tag}\nmathjax: true\n---"
def find_files(target_path: str) -> (str, str):
markdown = ""
directory = ""
for file in os.listdir(target_pat... | notion_converter.py | import os
import shutil
import datetime
TAG_CONST = "강의 Convex_Optimization"
def create_header(title: str, tag: str) -> str:
return f"---\ntitle: {title}\ntags: {tag}\nmathjax: true\n---"
def find_files(target_path: str) -> (str, str):
markdown = ""
directory = ""
for file in os.listdir(target_pat... | 0.315947 | 0.136148 |
import graphviz
import numpy as np
from rfa_toolbox.graphs import EnrichedNetworkNode
def node_id(node: EnrichedNetworkNode) -> str:
"""Provide a unique string for each node based on its name and object id.
This makes the node-id human readable while also easy to process since it contains
human interpret... | rfa_toolbox/vizualize.py | import graphviz
import numpy as np
from rfa_toolbox.graphs import EnrichedNetworkNode
def node_id(node: EnrichedNetworkNode) -> str:
"""Provide a unique string for each node based on its name and object id.
This makes the node-id human readable while also easy to process since it contains
human interpret... | 0.860779 | 0.609234 |
import io
import boto3
import requests
import pandas as pd
from zipfile import ZipFile
def read_zip(zip_url, filename):
"""
Reads a csv file from a zip file online. Example: 'public2018.csv' from
'https://www.federalreserve.gov/consumerscommunities/files/SHED_public_use_data_2018_(CSV).zip'
"""
z ... | kauffman/tools/etl.py | import io
import boto3
import requests
import pandas as pd
from zipfile import ZipFile
def read_zip(zip_url, filename):
"""
Reads a csv file from a zip file online. Example: 'public2018.csv' from
'https://www.federalreserve.gov/consumerscommunities/files/SHED_public_use_data_2018_(CSV).zip'
"""
z ... | 0.447943 | 0.296591 |
from dataclasses import dataclass
from typing import Dict, List, Sequence, Tuple
from django.conf import settings
from django.core.management.base import BaseCommand
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from gnosis.eth import EthereumClientProvider
from gnosis.eth.ethereum_client impo... | safe_transaction_service/history/management/commands/setup_service.py | from dataclasses import dataclass
from typing import Dict, List, Sequence, Tuple
from django.conf import settings
from django.core.management.base import BaseCommand
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from gnosis.eth import EthereumClientProvider
from gnosis.eth.ethereum_client impo... | 0.756088 | 0.187244 |
from django.test import TestCase
# tests for models
from mod_man.models import *
class ModelsTest(TestCase):
def setUp(self):
# get some tags first
tags_str = ["existing_tag_1","existing_tag_2"]
tags_obj = [Tags.objects.get_or_create(title=each_str)[0] for each_str in tags_str]
... | mod_man/tests/test_models.py | from django.test import TestCase
# tests for models
from mod_man.models import *
class ModelsTest(TestCase):
def setUp(self):
# get some tags first
tags_str = ["existing_tag_1","existing_tag_2"]
tags_obj = [Tags.objects.get_or_create(title=each_str)[0] for each_str in tags_str]
... | 0.409339 | 0.376279 |
__all__ = ("Client", )
from .logger import getLogger, logging_levels
from .configuration import dc_conf, EnvVars
import paho.mqtt.client
import logging
import threading
logger = getLogger(__name__.split(".", 1)[-1])
mqtt_logger = logging.getLogger("mqtt-client")
mqtt_logger.setLevel(logging_levels.setdefault(dc_co... | dc/mqtt_client.py | __all__ = ("Client", )
from .logger import getLogger, logging_levels
from .configuration import dc_conf, EnvVars
import paho.mqtt.client
import logging
import threading
logger = getLogger(__name__.split(".", 1)[-1])
mqtt_logger = logging.getLogger("mqtt-client")
mqtt_logger.setLevel(logging_levels.setdefault(dc_co... | 0.332202 | 0.042962 |
from scipy.constants import e as qe
from ..fieldmaps.bigaussian import BiGaussianFieldMap, BiGaussianFieldMapData
from ..general import _pkg_root
import xobjects as xo
import xtrack as xt
class BeamBeamBiGaussian2D(xt.BeamElement):
"""
Simulates the effect of beam-beam on a bunch.
Args:
context... | xfields/beam_elements/beambeam.py | from scipy.constants import e as qe
from ..fieldmaps.bigaussian import BiGaussianFieldMap, BiGaussianFieldMapData
from ..general import _pkg_root
import xobjects as xo
import xtrack as xt
class BeamBeamBiGaussian2D(xt.BeamElement):
"""
Simulates the effect of beam-beam on a bunch.
Args:
context... | 0.887966 | 0.528655 |
import glob
from MfccWavLoader import MfccWavLoader
import numpy
import os
from SoundTagJsonReader import SoundTagJsonReader
# To ensure that all wavs generate comparable MFCCs, we need to ensure the top end
# of the MFCC bucketing range is consistent. The default MFCC generation takes
# the wav's rateHz / 2. We have ... | src/InstrumentLoader.py | import glob
from MfccWavLoader import MfccWavLoader
import numpy
import os
from SoundTagJsonReader import SoundTagJsonReader
# To ensure that all wavs generate comparable MFCCs, we need to ensure the top end
# of the MFCC bucketing range is consistent. The default MFCC generation takes
# the wav's rateHz / 2. We have ... | 0.326593 | 0.237819 |
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponseRedirect
from django.views import View
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login,logout
from django.utils.decorators import method_decorator
from django.... | account/views.py | from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponseRedirect
from django.views import View
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login,logout
from django.utils.decorators import method_decorator
from django.... | 0.347869 | 0.053255 |
from contextlib import contextmanager
import os
import select
import sys
# TODO: move in here? They're currently platform-agnostic...
from .util import has_fileno, isatty
WINDOWS = (sys.platform == 'win32')
"""
Whether or not the current platform appears to be Windows in nature.
Note that Cygwin's Python is actuall... | invoke/terminals.py | from contextlib import contextmanager
import os
import select
import sys
# TODO: move in here? They're currently platform-agnostic...
from .util import has_fileno, isatty
WINDOWS = (sys.platform == 'win32')
"""
Whether or not the current platform appears to be Windows in nature.
Note that Cygwin's Python is actuall... | 0.467089 | 0.216529 |
# pylint: disable=unused-import, superfluous-parens, line-too-long, missing-module-docstring, unused-variable, missing-function-docstring, invalid-name
import glob
import pytest
import numpy as np
import cv2
import sksurgeryimage.calibration.charuco as ch
import sksurgeryimage.calibration.charuco_plus_chessboard_poin... | tests/video/test_charuco_plus_chessboard.py |
# pylint: disable=unused-import, superfluous-parens, line-too-long, missing-module-docstring, unused-variable, missing-function-docstring, invalid-name
import glob
import pytest
import numpy as np
import cv2
import sksurgeryimage.calibration.charuco as ch
import sksurgeryimage.calibration.charuco_plus_chessboard_poin... | 0.389663 | 0.326084 |
import os
import unittest
from Pegasus import exitcode
from Pegasus.exitcode import JobFailed
dirname = os.path.abspath(os.path.dirname(__file__))
class ExitcodeTestCase(unittest.TestCase):
def test_unquote_message(self):
self.assertTrue(exitcode.unquote_message(" "), " ")
self.assertTrue(exitcod... | lib/pegasus/python/Pegasus/test/test_exitcode.py | import os
import unittest
from Pegasus import exitcode
from Pegasus.exitcode import JobFailed
dirname = os.path.abspath(os.path.dirname(__file__))
class ExitcodeTestCase(unittest.TestCase):
def test_unquote_message(self):
self.assertTrue(exitcode.unquote_message(" "), " ")
self.assertTrue(exitcod... | 0.349644 | 0.370225 |
from typing import Dict
from dbt.logger import (
DbtStatusMessage,
TextOnly,
)
from dbt.events.functions import fire_event
from dbt.events.types import (
EmptyLine, RunResultWarning, RunResultFailure, StatsLine, RunResultError,
RunResultErrorNoMessage, SQLCompiledPath, CheckNodeTestFailure, FirstRunResu... | core/dbt/task/printer.py | from typing import Dict
from dbt.logger import (
DbtStatusMessage,
TextOnly,
)
from dbt.events.functions import fire_event
from dbt.events.types import (
EmptyLine, RunResultWarning, RunResultFailure, StatsLine, RunResultError,
RunResultErrorNoMessage, SQLCompiledPath, CheckNodeTestFailure, FirstRunResu... | 0.472197 | 0.189596 |
from __future__ import with_statement
import os
from distutils.core import setup
import imp
def get_version():
" Get version & version_info without importing markdown.__init__ "
path = os.path.join(os.path.dirname(__file__), 'zmarkdown')
fp, pathname, desc = imp.find_module('__version__', [path])
try... | setup.py |
from __future__ import with_statement
import os
from distutils.core import setup
import imp
def get_version():
" Get version & version_info without importing markdown.__init__ "
path = os.path.join(os.path.dirname(__file__), 'zmarkdown')
fp, pathname, desc = imp.find_module('__version__', [path])
try... | 0.460289 | 0.104432 |
import hydra
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as T
from hydra.core.config_store import ConfigStore
from hydra.utils import to_absolute_path
import kornia as K
from kornia.x import Configuration, EarlyStopping, ImageClassifierTrainer, ModelCheckpoint
cs = ConfigStore.... | examples/train/image_classifier/main.py | import hydra
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as T
from hydra.core.config_store import ConfigStore
from hydra.utils import to_absolute_path
import kornia as K
from kornia.x import Configuration, EarlyStopping, ImageClassifierTrainer, ModelCheckpoint
cs = ConfigStore.... | 0.852675 | 0.322393 |
from f5.common.logger import Log
from f5.common import constants as const
from f5.bigip.interfaces import icontrol_rest_folder
from f5.bigip import exceptions
from f5.bigip.interfaces import log
import json
class Rule(object):
""" Class for managing iRules on bigip """
def __init__(self, bigip):
sel... | common/f5/bigip/interfaces/rule.py |
from f5.common.logger import Log
from f5.common import constants as const
from f5.bigip.interfaces import icontrol_rest_folder
from f5.bigip import exceptions
from f5.bigip.interfaces import log
import json
class Rule(object):
""" Class for managing iRules on bigip """
def __init__(self, bigip):
sel... | 0.429071 | 0.069922 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import codecs
import re
from .ddict import defaultdict
from itertools import chain
from nine import iteritems, str
from shlex import split as shlex_split # Prior to Python 2.7.3, the
from sys import version_in... | kajiki/text.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import codecs
import re
from .ddict import defaultdict
from itertools import chain
from nine import iteritems, str
from shlex import split as shlex_split # Prior to Python 2.7.3, the
from sys import version_in... | 0.408867 | 0.189165 |
# In[ ]:
#importing the required libraries
import pandas as pd
from sklearn import preprocessing
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn import neighbors
knn=neighbors.KNeighborsClassifier(n_neighbors=3... | python/scikit learn-pandas- K Nearest Neighbour(KNN) Algorithm/scikit learn-pandas- K Nearest Neighbour(KNN) Algorithm.py |
# In[ ]:
#importing the required libraries
import pandas as pd
from sklearn import preprocessing
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn import neighbors
knn=neighbors.KNeighborsClassifier(n_neighbors=3... | 0.360264 | 0.373162 |
import argparse
import os
import numpy as np
import math
import itertools
import sys
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torch.utils.data import DataLoader
from torch.autograd import Variable
from models import *
from datasets import *
import torch.nn... | implementation/srgan/processImage.py | import argparse
import os
import numpy as np
import math
import itertools
import sys
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torch.utils.data import DataLoader
from torch.autograd import Variable
from models import *
from datasets import *
import torch.nn... | 0.591133 | 0.319201 |
import datetime
import itertools
import dl
import xypath
import messytables
import orm
"""Value: dsID, region, indID, period, value, source, is_number
DataSet: dsID, last_updated, last_scraped, name
Indicator: indID, name, units
"""
url = "http://www.emdat.be/advanced_search/php/downloadCsv.php?continent=&re... | emdat.py | import datetime
import itertools
import dl
import xypath
import messytables
import orm
"""Value: dsID, region, indID, period, value, source, is_number
DataSet: dsID, last_updated, last_scraped, name
Indicator: indID, name, units
"""
url = "http://www.emdat.be/advanced_search/php/downloadCsv.php?continent=&re... | 0.130313 | 0.248819 |
import random
import torch
import torch.nn as nn
from nntools.nnet import register_loss
class MultiLabelSoftBinaryCrossEntropy(nn.Module):
def __init__(self, smooth_factor: float = 0, weighted: bool = True,
mcb: bool = False, hp_lambda: int = 10,
epsilon: float = 0.1, logits=Tru... | tools/losses.py | import random
import torch
import torch.nn as nn
from nntools.nnet import register_loss
class MultiLabelSoftBinaryCrossEntropy(nn.Module):
def __init__(self, smooth_factor: float = 0, weighted: bool = True,
mcb: bool = False, hp_lambda: int = 10,
epsilon: float = 0.1, logits=Tru... | 0.906275 | 0.464841 |
from __future__ import annotations
from datetime import datetime
from typing import Any, Callable
from hatasmota import switch as tasmota_switch
from hatasmota.entity import TasmotaEntity as HATasmotaEntity
from hatasmota.models import DiscoveryHashType
from homeassistant.components import binary_sensor
from homeass... | homeassistant/components/tasmota/binary_sensor.py | from __future__ import annotations
from datetime import datetime
from typing import Any, Callable
from hatasmota import switch as tasmota_switch
from hatasmota.entity import TasmotaEntity as HATasmotaEntity
from hatasmota.models import DiscoveryHashType
from homeassistant.components import binary_sensor
from homeass... | 0.897984 | 0.131368 |
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
from timeit import default_timer as timer
lam1 = None
lam2 = None
lam3 = None
def get_random_start_params(min_val, max_val):
""" Generates random start values for x and y
"""
return np.array([np.random.randint(min_va... | 04_regression/regression.py | import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
from timeit import default_timer as timer
lam1 = None
lam2 = None
lam3 = None
def get_random_start_params(min_val, max_val):
""" Generates random start values for x and y
"""
return np.array([np.random.randint(min_va... | 0.503418 | 0.738846 |
# Copyright: (c) 2019, <NAME> (<EMAIL>)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: vexata_volume
short_description: Manage volumes on Vexata VX100 ... | Collections-a-installer/community-general-2.4.0/plugins/modules/vexata_volume.py |
# Copyright: (c) 2019, <NAME> (<EMAIL>)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: vexata_volume
short_description: Manage volumes on Vexata VX100 ... | 0.752286 | 0.345823 |
import glob
import importlib
import logging
import os
import shutil
from abc import ABC, abstractmethod
from datetime import datetime
from typing import TextIO, List, Dict, Tuple
from airflow import conf
from airflow.exceptions import AirflowConfigException
logger = logging.getLogger(__name__)
logger.setLevel(logging... | src/airtunnel/data_store.py | import glob
import importlib
import logging
import os
import shutil
from abc import ABC, abstractmethod
from datetime import datetime
from typing import TextIO, List, Dict, Tuple
from airflow import conf
from airflow.exceptions import AirflowConfigException
logger = logging.getLogger(__name__)
logger.setLevel(logging... | 0.812235 | 0.319652 |
# pylint: disable=unused-argument
import os
import subprocess
import sys
from pathlib import Path
from tempfile import NamedTemporaryFile
import anyconfig
import pytest
from click.testing import CliRunner
from kedro.context import KEDRO_ENV_VAR
from kedro.runner import ParallelRunner, SequentialRunner
@pytest.fixt... | tests/template/test_kedro_cli.py |
# pylint: disable=unused-argument
import os
import subprocess
import sys
from pathlib import Path
from tempfile import NamedTemporaryFile
import anyconfig
import pytest
from click.testing import CliRunner
from kedro.context import KEDRO_ENV_VAR
from kedro.runner import ParallelRunner, SequentialRunner
@pytest.fixt... | 0.535098 | 0.199055 |
import importlib
from datetime import datetime
from masonite.response import Response
from ..interfaces.instant_article_interface import InstantArticleInterface
from .instant_article import InstantArticle
class InstantArticleResolver:
_title = ""
_description = ""
_language = "en-us"
_url = ""
_... | src/instant_article/models/instant_article_resolver.py | import importlib
from datetime import datetime
from masonite.response import Response
from ..interfaces.instant_article_interface import InstantArticleInterface
from .instant_article import InstantArticle
class InstantArticleResolver:
_title = ""
_description = ""
_language = "en-us"
_url = ""
_... | 0.516595 | 0.129073 |
import bz2
import lzma
import zlib
from abc import abstractproperty
from enum import IntEnum
from importlib import import_module
from typing import Any, Callable, Dict, Tuple
from umsgpack import ext_serializable, packb, _ext_classes
BASE_MESSAGE_CODE = 0
def identity(foo: bytes) -> bytes:
"""Return yourself, ... | src/protocol/__init__.py | import bz2
import lzma
import zlib
from abc import abstractproperty
from enum import IntEnum
from importlib import import_module
from typing import Any, Callable, Dict, Tuple
from umsgpack import ext_serializable, packb, _ext_classes
BASE_MESSAGE_CODE = 0
def identity(foo: bytes) -> bytes:
"""Return yourself, ... | 0.834643 | 0.427576 |
import errno
import logging
import os
import sys
from concurrent import futures
import grpc
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import autoreload
from django_socio_grpc.settings import grpc_settings
logger = logging.getLogger("django_socio_grpc")
c... | django_socio_grpc/management/commands/grpcrunserver.py | import errno
import logging
import os
import sys
from concurrent import futures
import grpc
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import autoreload
from django_socio_grpc.settings import grpc_settings
logger = logging.getLogger("django_socio_grpc")
c... | 0.408749 | 0.063193 |
# 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... | thewalrus/_hermite_multidimensional.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.962045 | 0.573678 |
import nextcord, json, os, sys
from nextcord.ext import commands
from nextcord.ui import View, button
from Functions.Embed import *
# Get Settings.json
with open("Settings/Options.json", "r") as Settings:
Options = json.load(Settings)
# Buttons array for developer commands
class ButtonArray(View):
def _... | Commands/Developer.py | import nextcord, json, os, sys
from nextcord.ext import commands
from nextcord.ui import View, button
from Functions.Embed import *
# Get Settings.json
with open("Settings/Options.json", "r") as Settings:
Options = json.load(Settings)
# Buttons array for developer commands
class ButtonArray(View):
def _... | 0.395951 | 0.22933 |