code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from pathlib import Path
import shutil
import pytest
import yaml
from openpecha.blupdate import Blupdate
@pytest.fixture(params=[{'srcbl': 'abefghijkl', 'dstbl': 'abcdefgkl'}])
def inputs(request):
return request.param
@pytest.fixture(params=[{'expected_result': [(0,2,0), (2,5,2), (8,10,-1)]}])
def compute_... | tests/test_blupdate.py | from pathlib import Path
import shutil
import pytest
import yaml
from openpecha.blupdate import Blupdate
@pytest.fixture(params=[{'srcbl': 'abefghijkl', 'dstbl': 'abcdefgkl'}])
def inputs(request):
return request.param
@pytest.fixture(params=[{'expected_result': [(0,2,0), (2,5,2), (8,10,-1)]}])
def compute_... | 0.66454 | 0.548674 |
import tweepy
import sys, os
import csv
import logging
import traceback, signal
import time, random
import json
from tweepy.error import TweepError
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
from tweets_crawler import db as DB
class TweepySpider():
auths = []
proxies = []
credenti... | spider.py | import tweepy
import sys, os
import csv
import logging
import traceback, signal
import time, random
import json
from tweepy.error import TweepError
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
from tweets_crawler import db as DB
class TweepySpider():
auths = []
proxies = []
credenti... | 0.111398 | 0.052546 |
import os
import json
from typing import Dict, List
from pprint import pprint
import collections
TokenRewardSummary = collections.namedtuple(
"TokenRewardSummary",
field_names=["total_num_tokens", "reward_totals", "reward_pcts"])
AirdropGroup = str # Osmosis, SOMM app, or UNI v3
Wallet = str
class TokenRe... | summary_of_token_rewards.py |
import os
import json
from typing import Dict, List
from pprint import pprint
import collections
TokenRewardSummary = collections.namedtuple(
"TokenRewardSummary",
field_names=["total_num_tokens", "reward_totals", "reward_pcts"])
AirdropGroup = str # Osmosis, SOMM app, or UNI v3
Wallet = str
class TokenRe... | 0.461017 | 0.236935 |
from datetime import datetime
from fhirclient_file import *
import pandas
import simplejson
import ipdb
#Read in population Data
population_data = pandas.read_csv('mocked_population_health_data.csv')
aggregated_popdata= pandas.read_csv('aggregated_population_health_data.csv')
#End App Setup
condition_name_to_snomed... | data_helpers.py | from datetime import datetime
from fhirclient_file import *
import pandas
import simplejson
import ipdb
#Read in population Data
population_data = pandas.read_csv('mocked_population_health_data.csv')
aggregated_popdata= pandas.read_csv('aggregated_population_health_data.csv')
#End App Setup
condition_name_to_snomed... | 0.274838 | 0.273309 |
import unittest
import logging
import functools
import concurrent.futures
from hypothesis import given, strategies as st
from eolearn.core import EOTask, EOWorkflow, Dependency, WorkflowResults, LinearWorkflow
from eolearn.core.eoworkflow import CyclicDependencyError, _UniqueIdGenerator
from eolearn.core.graph import... | core/eolearn/tests/test_eoworkflow.py | import unittest
import logging
import functools
import concurrent.futures
from hypothesis import given, strategies as st
from eolearn.core import EOTask, EOWorkflow, Dependency, WorkflowResults, LinearWorkflow
from eolearn.core.eoworkflow import CyclicDependencyError, _UniqueIdGenerator
from eolearn.core.graph import... | 0.553988 | 0.478894 |
import bpy
from . import myutil
from . import vcf
class VCF_OT_VCFLauncher(bpy.types.Operator):
bl_idname = "object.launch_vcf"
bl_label = "VCF Launch"
bl_description = "Launch the VCF in scene."
@classmethod
def __launch(cls, context):
scene = context.scene
print("St... | vcf/vcf_launcher.py | import bpy
from . import myutil
from . import vcf
class VCF_OT_VCFLauncher(bpy.types.Operator):
bl_idname = "object.launch_vcf"
bl_label = "VCF Launch"
bl_description = "Launch the VCF in scene."
@classmethod
def __launch(cls, context):
scene = context.scene
print("St... | 0.35768 | 0.145874 |
import sys
def ba_list():
fruits1 = ['grape', 'apple', 'strawberry', 'waxberry']
fruits1 += ['pitaya', 'pear', 'mango']
print('fruit1 is ', fruits1)
# 循环遍历列表元素
for fruit in fruits1:
print(fruit.title(), end='\t')
print(fruit)
# 列表切片
fruits2 = fruits1[1:4]
print('fruit2 ... | hdd/day6.py | import sys
def ba_list():
fruits1 = ['grape', 'apple', 'strawberry', 'waxberry']
fruits1 += ['pitaya', 'pear', 'mango']
print('fruit1 is ', fruits1)
# 循环遍历列表元素
for fruit in fruits1:
print(fruit.title(), end='\t')
print(fruit)
# 列表切片
fruits2 = fruits1[1:4]
print('fruit2 ... | 0.153899 | 0.553867 |
# standard modules
import logging
# extra modules
dependencies_missing = False
try:
import socket
import sys
import hashlib
except ImportError:
dependencies_missing = True
from metasploit import module
metadata = {
'name': 'Mikrotik Winbox Arbitrary File Read',
'description': '''
Mik... | modules/auxiliary/gather/mikrotik_winbox_fileread.py |
# standard modules
import logging
# extra modules
dependencies_missing = False
try:
import socket
import sys
import hashlib
except ImportError:
dependencies_missing = True
from metasploit import module
metadata = {
'name': 'Mikrotik Winbox Arbitrary File Read',
'description': '''
Mik... | 0.348423 | 0.291277 |
import math
import streamlit as st
from openpyxl import load_workbook
nGauge=0
para_list=[]
para_per_gauge=[]
methdStr=''
blnReady2calc= False
blnInputLoad = False
class para:
case=0
ta=0.
tb=0.
def __init__(self, nm,gauge,unit,ts,val):
self.nm=nm
self.gaugeID=gauge... | wql.py | import math
import streamlit as st
from openpyxl import load_workbook
nGauge=0
para_list=[]
para_per_gauge=[]
methdStr=''
blnReady2calc= False
blnInputLoad = False
class para:
case=0
ta=0.
tb=0.
def __init__(self, nm,gauge,unit,ts,val):
self.nm=nm
self.gaugeID=gauge... | 0.221351 | 0.111507 |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, List
from enums import Opcode, Operand, OperandType
if TYPE_CHECKING:
from zmachine import ZMachine
def _btm_4(num: int) -> int:
return num & 0b0000_1111
def _btm_5(num: int) -> int:
return num & 0b00... | zinstruction.py | from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, List
from enums import Opcode, Operand, OperandType
if TYPE_CHECKING:
from zmachine import ZMachine
def _btm_4(num: int) -> int:
return num & 0b0000_1111
def _btm_5(num: int) -> int:
return num & 0b00... | 0.55254 | 0.47658 |
from decimal import Decimal
from cypherpunkpay.app import App
from test.acceptance.app_test_case import CypherpunkpayAppTestCase
class ChargeViewsTest(CypherpunkpayAppTestCase):
def test_get_charge_root(self):
res = self.webapp.get('/cypherpunkpay/charge/abcd1234', status=302)
self.assertMatch('... | test/acceptance/views/charge_views_test.py | from decimal import Decimal
from cypherpunkpay.app import App
from test.acceptance.app_test_case import CypherpunkpayAppTestCase
class ChargeViewsTest(CypherpunkpayAppTestCase):
def test_get_charge_root(self):
res = self.webapp.get('/cypherpunkpay/charge/abcd1234', status=302)
self.assertMatch('... | 0.555194 | 0.31832 |
from datetime import datetime
from enum import Enum
from typing import List
class PolicyEffect(Enum):
ALLOW = "allow"
DENY = "deny"
class Policy:
def __init__(self, scope: str, access: PolicyEffect = PolicyEffect.ALLOW):
self.scope = scope
self.effect = access
self.created_at = d... | targe/policy.py | from datetime import datetime
from enum import Enum
from typing import List
class PolicyEffect(Enum):
ALLOW = "allow"
DENY = "deny"
class Policy:
def __init__(self, scope: str, access: PolicyEffect = PolicyEffect.ALLOW):
self.scope = scope
self.effect = access
self.created_at = d... | 0.702428 | 0.1661 |
"""Manage templates located on Github."""
from piecutter.loaders.github import GithubLoader
from piecutter.utils import temporary_directory
from diecutter.local import LocalService
class GithubService(LocalService):
"""A diecutter service that uses Github as template storage."""
def get(self, request):
... | diecutter/github.py | """Manage templates located on Github."""
from piecutter.loaders.github import GithubLoader
from piecutter.utils import temporary_directory
from diecutter.local import LocalService
class GithubService(LocalService):
"""A diecutter service that uses Github as template storage."""
def get(self, request):
... | 0.551332 | 0.250649 |
from __future__ import print_function
from __future__ import absolute_import
import itertools
from snppipeline import utils
from snppipeline.utils import verbose_print
def calculate_snp_distances(args):
"""Calculate pairwise sample SNP distances.
Calculate pairwise SNP distances from the multi-fasta SNP ma... | snppipeline/distance.py | from __future__ import print_function
from __future__ import absolute_import
import itertools
from snppipeline import utils
from snppipeline.utils import verbose_print
def calculate_snp_distances(args):
"""Calculate pairwise sample SNP distances.
Calculate pairwise SNP distances from the multi-fasta SNP ma... | 0.809201 | 0.461502 |
from __future__ import absolute_import, division, print_function
import copy
import logging
import pytest
import six
import numpy as np
from numpy.testing import (assert_equal, assert_array_almost_equal,
assert_array_equal, assert_raises)
from skbeam.core.fitting.base.parameter_data import ... | skbeam/core/fitting/tests/test_xrf_fit.py | from __future__ import absolute_import, division, print_function
import copy
import logging
import pytest
import six
import numpy as np
from numpy.testing import (assert_equal, assert_array_almost_equal,
assert_array_equal, assert_raises)
from skbeam.core.fitting.base.parameter_data import ... | 0.726329 | 0.452052 |
# This notebook was prepared by [<NAME>](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Determine whether there is a path between two nodes in a graph.
#
# * [Constraints](#Constraints)
# * [T... | graphs_trees/graph_path_exists/path_exists_solution.py |
# This notebook was prepared by [<NAME>](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Determine whether there is a path between two nodes in a graph.
#
# * [Constraints](#Constraints)
# * [T... | 0.881857 | 0.703479 |
def escape_special_characters(value):
""" Escapes special characters in argument """
pass
def remove_special_characters(value):
""" Remove special characters from argument
:param value - a string containing special characters to remove
:returns a string with special characters removed
"""
... | coronacli/utils.py | def escape_special_characters(value):
""" Escapes special characters in argument """
pass
def remove_special_characters(value):
""" Remove special characters from argument
:param value - a string containing special characters to remove
:returns a string with special characters removed
"""
... | 0.862439 | 0.64944 |
import unittest
import helpers
from latexpp.fixes import newcommand
class TestExpand(unittest.TestCase):
maxDiff = None
def test_simple(self):
latex = r"""
\documentclass[11pt]{article}
\newcommand{\a}{<NAME>}
\newcommand\max[1]{Max #1}
\begin{document}
\a{} and \max{Planck} both though... | test/test_fixes_newcommand.py | import unittest
import helpers
from latexpp.fixes import newcommand
class TestExpand(unittest.TestCase):
maxDiff = None
def test_simple(self):
latex = r"""
\documentclass[11pt]{article}
\newcommand{\a}{<NAME>}
\newcommand\max[1]{Max #1}
\begin{document}
\a{} and \max{Planck} both though... | 0.4917 | 0.404566 |
import time
from GPS import gps
from GPS import redisHelper
from GPS import helper
from GPS import args
argument_parser = args.ArgumentParser()
arguments = argument_parser.parse_worker_command_line_arguments()
R = redisHelper.connect(host=arguments['redis_host'],
port=arguments['redis_port'],... | run_gps_worker.py | import time
from GPS import gps
from GPS import redisHelper
from GPS import helper
from GPS import args
argument_parser = args.ArgumentParser()
arguments = argument_parser.parse_worker_command_line_arguments()
R = redisHelper.connect(host=arguments['redis_host'],
port=arguments['redis_port'],... | 0.244543 | 0.115686 |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import pandas as pd
import numpy as np
from torch.utils.data import DataLoader, TensorDataset
class BottomModelA(nn.Module):
def __init__(self):
super(BottomModelA, self).__init__()
self.... | federated learning/vertical FL.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import pandas as pd
import numpy as np
from torch.utils.data import DataLoader, TensorDataset
class BottomModelA(nn.Module):
def __init__(self):
super(BottomModelA, self).__init__()
self.... | 0.898271 | 0.461927 |
import random
#All functions contain pictures for each
#phase of the game
def pic1():
print("""\
______
| |
| |
|
|
|
|
|
===========
""")
def pic2():
... | hangman.py | import random
#All functions contain pictures for each
#phase of the game
def pic1():
print("""\
______
| |
| |
|
|
|
|
|
===========
""")
def pic2():
... | 0.055126 | 0.257648 |
import six.moves.urllib.parse as parser
from oslo_config import cfg
from osprofiler.drivers import base
from osprofiler import exc
class ElasticsearchDriver(base.Driver):
def __init__(self, connection_str, index_name="osprofiler-notifications",
project=None, service=None, host=None, conf=cfg.CO... | osprofiler/drivers/elasticsearch_driver.py |
import six.moves.urllib.parse as parser
from oslo_config import cfg
from osprofiler.drivers import base
from osprofiler import exc
class ElasticsearchDriver(base.Driver):
def __init__(self, connection_str, index_name="osprofiler-notifications",
project=None, service=None, host=None, conf=cfg.CO... | 0.717804 | 0.091951 |
import math, copy, random, time
from cmu_112_graphics import *
from pieces import *
#Splash Screen Mode and Player vs Player standard mode
class SplashScreenMode(Mode):
def appStarted(self):
#background image taken from online url
self.backgroundURL = 'https://wallpaperaccess.com/full/1307... | Project CodeBase/HumanBattle.py | import math, copy, random, time
from cmu_112_graphics import *
from pieces import *
#Splash Screen Mode and Player vs Player standard mode
class SplashScreenMode(Mode):
def appStarted(self):
#background image taken from online url
self.backgroundURL = 'https://wallpaperaccess.com/full/1307... | 0.305594 | 0.148109 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['SecretCiphertextArgs', 'SecretCiphertext']
@pulumi.input_type
class SecretCiphertextArgs:
def __init__(__self__, *,
crypto_key: pulumi.In... | sdk/python/pulumi_gcp/kms/secret_ciphertext.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['SecretCiphertextArgs', 'SecretCiphertext']
@pulumi.input_type
class SecretCiphertextArgs:
def __init__(__self__, *,
crypto_key: pulumi.In... | 0.891389 | 0.131118 |
import bpy
from maviz import *
from bl_ui_draw_pose import Bl_Ui_Draw_Pose as budp
from bl_op_flag import Bl_Op_Flag as bof
class IKMover:
CMD_UP = 0
CMD_DOWN = 1
CMD_LEFT = 2
CMD_RIGHT = 3
CMD_MOVE = 4
CMD_NUM_1 = 5
CMD_NUM_3 = 6
CMD_NUM_4 = 7
CMD_NUM_5 = 8
CMD_N... | src/IkMover.py | import bpy
from maviz import *
from bl_ui_draw_pose import Bl_Ui_Draw_Pose as budp
from bl_op_flag import Bl_Op_Flag as bof
class IKMover:
CMD_UP = 0
CMD_DOWN = 1
CMD_LEFT = 2
CMD_RIGHT = 3
CMD_MOVE = 4
CMD_NUM_1 = 5
CMD_NUM_3 = 6
CMD_NUM_4 = 7
CMD_NUM_5 = 8
CMD_N... | 0.312055 | 0.114369 |
import os, base64, tempfile, io
from os import path
from setuptools import setup, Command
from distutils.command.build_scripts import build_scripts
from setuptools.dist import Distribution as _Distribution
LONG="""
Versioneer is a tool to automatically update version strings (in setup.py and
the conventional 'from PR... | setup.py |
import os, base64, tempfile, io
from os import path
from setuptools import setup, Command
from distutils.command.build_scripts import build_scripts
from setuptools.dist import Distribution as _Distribution
LONG="""
Versioneer is a tool to automatically update version strings (in setup.py and
the conventional 'from PR... | 0.364891 | 0.14734 |
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import qpimage
import qpsphere
# load the experimental data
edata = np.load("./data/hologram_cell.npz")
# create QPImage instance
qpi = qpimage.QPImage(data=edata["data"],
bg_data=edata["bg_data"],
which_da... | examples/cell_edge.py | import matplotlib
import matplotlib.pylab as plt
import numpy as np
import qpimage
import qpsphere
# load the experimental data
edata = np.load("./data/hologram_cell.npz")
# create QPImage instance
qpi = qpimage.QPImage(data=edata["data"],
bg_data=edata["bg_data"],
which_da... | 0.657209 | 0.59514 |
"""Slicing Variable Model"""
from __future__ import (absolute_import, print_function,
division, unicode_literals)
from sqlalchemy import Column, Integer, Text, TIMESTAMP, select, alias
from sqlalchemy import PrimaryKeyConstraint, ForeignKeyConstraint
from sqlalchemy.orm import aliased
from ..... | now/persistence/models/variable.py |
"""Slicing Variable Model"""
from __future__ import (absolute_import, print_function,
division, unicode_literals)
from sqlalchemy import Column, Integer, Text, TIMESTAMP, select, alias
from sqlalchemy import PrimaryKeyConstraint, ForeignKeyConstraint
from sqlalchemy.orm import aliased
from ..... | 0.684686 | 0.176654 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.autograd import Variable
from torch.nn.utils import weight_norm
from trilinear import TriAttention, TCNet
from fc import FCNet
import numpy as np
class Fusion(nn.Module):
""" Crazy multi-modal fusion: negativ... | dfaf.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.autograd import Variable
from torch.nn.utils import weight_norm
from trilinear import TriAttention, TCNet
from fc import FCNet
import numpy as np
class Fusion(nn.Module):
""" Crazy multi-modal fusion: negativ... | 0.944664 | 0.499817 |
import json
import requests
from bitsv.network.meta import Unspent
from bitsv.network.transaction import Transaction, TxInput, TxOutput
from decimal import Decimal
class BitIndex3:
"""
Implements version 3 of the BitIndex API
:param network: select 'main', 'test', or 'stn'
:type network: ``str``
... | bitsv/network/services/bitindex3.py | import json
import requests
from bitsv.network.meta import Unspent
from bitsv.network.transaction import Transaction, TxInput, TxOutput
from decimal import Decimal
class BitIndex3:
"""
Implements version 3 of the BitIndex API
:param network: select 'main', 'test', or 'stn'
:type network: ``str``
... | 0.790813 | 0.199308 |
import logging
from pyls import hookimpl
from pyls.lsp import SymbolKind
log = logging.getLogger(__name__)
@hookimpl
def pyls_document_symbols(config, document):
all_scopes = config.plugin_settings('jedi_symbols').get('all_scopes', True)
definitions = document.jedi_names(all_scopes=all_scopes)
return [{
... | pyls/plugins/symbols.py | import logging
from pyls import hookimpl
from pyls.lsp import SymbolKind
log = logging.getLogger(__name__)
@hookimpl
def pyls_document_symbols(config, document):
all_scopes = config.plugin_settings('jedi_symbols').get('all_scopes', True)
definitions = document.jedi_names(all_scopes=all_scopes)
return [{
... | 0.688049 | 0.101322 |
from yt.fields.field_info_container import FieldInfoContainer
# We need to specify which fields we might have in our dataset. The field info
# container subclass here will define which fields it knows about. There are
# optionally methods on it that get called which can be subclassed.
class CM1FieldInfo(FieldInfoC... | yt/frontends/nc4_cm1/fields.py | from yt.fields.field_info_container import FieldInfoContainer
# We need to specify which fields we might have in our dataset. The field info
# container subclass here will define which fields it knows about. There are
# optionally methods on it that get called which can be subclassed.
class CM1FieldInfo(FieldInfoC... | 0.58166 | 0.406803 |
from typing import List
from icarus_simulator.strategies.atk_path_filtering.base_path_filtering_strat import (
BasePathFilteringStrat,
)
from icarus_simulator.structure_definitions import (
Edge,
PathData,
EdgeData,
DirectionData,
)
class DirectionalFilteringStrat(BasePathFilteringStrat):
@pr... | icarus_simulator/strategies/atk_path_filtering/directional_filtering_strat.py | from typing import List
from icarus_simulator.strategies.atk_path_filtering.base_path_filtering_strat import (
BasePathFilteringStrat,
)
from icarus_simulator.structure_definitions import (
Edge,
PathData,
EdgeData,
DirectionData,
)
class DirectionalFilteringStrat(BasePathFilteringStrat):
@pr... | 0.787523 | 0.380701 |
from functions import read_ncs, get_vectors, create_batch, train, get_non_comp_args, \
get_poly_features, rank_with_score, write_score, read_eval, build_model, regression_score
from baseline import weighted_add_score
from gensim.models.keyedvectors import KeyedVectors
import logging
from config import logging_confi... | non-comp.py | from functions import read_ncs, get_vectors, create_batch, train, get_non_comp_args, \
get_poly_features, rank_with_score, write_score, read_eval, build_model, regression_score
from baseline import weighted_add_score
from gensim.models.keyedvectors import KeyedVectors
import logging
from config import logging_confi... | 0.427158 | 0.294063 |
from collections import namedtuple
from datetime import timezone
Job = namedtuple('Job', ['job_id',
'user_id',
'status',
'run_dt',
'url',
'tries',
'delay_s'])
def bui... | up/dao.py | from collections import namedtuple
from datetime import timezone
Job = namedtuple('Job', ['job_id',
'user_id',
'status',
'run_dt',
'url',
'tries',
'delay_s'])
def bui... | 0.596316 | 0.155335 |
class BinaryTreeNode:
"""Binary Tree Node class"""
def __init__(self, key, value, left=None, right=None, parent=None):
"""Create new Tree Node"""
self._key = key
self._value = value
self._child_left = left
self._child_right = right
self._parent = parent
def ... | source/pythonds3/trees/binary_search_tree.py | class BinaryTreeNode:
"""Binary Tree Node class"""
def __init__(self, key, value, left=None, right=None, parent=None):
"""Create new Tree Node"""
self._key = key
self._value = value
self._child_left = left
self._child_right = right
self._parent = parent
def ... | 0.90109 | 0.471953 |
from . import GlobalConstants as GC
from . import Image_Modification, Engine
class MovingBackground(object):
def __init__(self, BGSurf):
self.lastBackgroundUpdate = Engine.get_time()
self.change_counter = 0
self.backgroundCounter = 0
self.BGSurf = BGSurf
def draw(self... | Code/Background.py | from . import GlobalConstants as GC
from . import Image_Modification, Engine
class MovingBackground(object):
def __init__(self, BGSurf):
self.lastBackgroundUpdate = Engine.get_time()
self.change_counter = 0
self.backgroundCounter = 0
self.BGSurf = BGSurf
def draw(self... | 0.541651 | 0.143248 |
import re
import shlex
import requests
from lpipe.exceptions import GraphQLError, InvalidTaxonomyURI
def query_graphql(raw_query, endpoint):
"""Query a graphql API handle errors."""
query = " ".join(shlex.split(raw_query, posix=False))
r = requests.get(endpoint, params={"query": query})
if r.status_... | lpipe/taxonomy.py | import re
import shlex
import requests
from lpipe.exceptions import GraphQLError, InvalidTaxonomyURI
def query_graphql(raw_query, endpoint):
"""Query a graphql API handle errors."""
query = " ".join(shlex.split(raw_query, posix=False))
r = requests.get(endpoint, params={"query": query})
if r.status_... | 0.796925 | 0.25228 |
from src.Model.PropositionalExpressionTree import Impl, Atom
from src.TableauxBuilder.BaseTableauxBuilder import *
from src.TableauxBuilder.PropositionalTableauxBuilder import PropositionalTableauxBuilder
class IpcTableauxBuilder(PropositionalTableauxBuilder):
left_side_sign = "P"
right_side_sign = "C"
... | src/TableauxBuilder/IpcTableauxBuilder.py | from src.Model.PropositionalExpressionTree import Impl, Atom
from src.TableauxBuilder.BaseTableauxBuilder import *
from src.TableauxBuilder.PropositionalTableauxBuilder import PropositionalTableauxBuilder
class IpcTableauxBuilder(PropositionalTableauxBuilder):
left_side_sign = "P"
right_side_sign = "C"
... | 0.492432 | 0.254277 |
from django.contrib.admin.filters import RelatedFieldListFilter
from django.db.models.fields.related import ForeignObjectRel
from django.db.models.query_utils import Q
from django.utils.encoding import smart_str
from django.utils.translation import gettext as _
from .mixin import MediaDefinitionFilter, WrappperMixin
f... | src/adminfilters/checkbox.py | from django.contrib.admin.filters import RelatedFieldListFilter
from django.db.models.fields.related import ForeignObjectRel
from django.db.models.query_utils import Q
from django.utils.encoding import smart_str
from django.utils.translation import gettext as _
from .mixin import MediaDefinitionFilter, WrappperMixin
f... | 0.40486 | 0.106691 |
import datetime
from gnes.preprocessor.base import BaseVideoPreprocessor
from gnes.proto import gnes_pb2, blob2array
class MySQLPreprocessor(BaseVideoPreprocessor):
def __init__(self, user: str,
password: str,
host: str,
port: str,
database: ... | preprocessor/mysql/mysql.py |
import datetime
from gnes.preprocessor.base import BaseVideoPreprocessor
from gnes.proto import gnes_pb2, blob2array
class MySQLPreprocessor(BaseVideoPreprocessor):
def __init__(self, user: str,
password: str,
host: str,
port: str,
database: ... | 0.424293 | 0.06727 |
import jwt
from flask import current_app
from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, IntegerField
from wtforms import FieldList, FormField, Form, HiddenField
import wtforms.validators as validator
from app.models import User
... | app/auth/forms.py | import jwt
from flask import current_app
from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, IntegerField
from wtforms import FieldList, FormField, Form, HiddenField
import wtforms.validators as validator
from app.models import User
... | 0.434701 | 0.098036 |
from django.urls import resolve, reverse_lazy
from django.views.generic import TemplateView
import pytest
from ratelimit.mixins import RatelimitMixin
from redirects.forms import RedirectModelForm
from redirects.models import Redirect
from redirects.views import RedirectFormView, ActualRedirectView
class TestRedirec... | tests/redirects/test_views.py | from django.urls import resolve, reverse_lazy
from django.views.generic import TemplateView
import pytest
from ratelimit.mixins import RatelimitMixin
from redirects.forms import RedirectModelForm
from redirects.models import Redirect
from redirects.views import RedirectFormView, ActualRedirectView
class TestRedirec... | 0.75985 | 0.401219 |
import hashlib
import json
import time
# An example block header - do not change any fields except nonce and coinbase_addr
example_block_header = {'height': 1478503,
'prev_block': '0000000000000da6cff8a34298ddb42e80204669367b781c87c88cf00787fcf6',
'total': 38982714093,
... | pow_mining_puzzle.py | import hashlib
import json
import time
# An example block header - do not change any fields except nonce and coinbase_addr
example_block_header = {'height': 1478503,
'prev_block': '0000000000000da6cff8a34298ddb42e80204669367b781c87c88cf00787fcf6',
'total': 38982714093,
... | 0.487307 | 0.302089 |
import sys
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import common.file_utils as file_utils
import common.logger as logger
from common.crawl_manager import *
from common.db_manager import DatabaseManager
PROJECT_NAME = "crawl"
RESULT_TEXT_FILE_NAME = "./result/result_{}.tx... | crawl.py | import sys
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import common.file_utils as file_utils
import common.logger as logger
from common.crawl_manager import *
from common.db_manager import DatabaseManager
PROJECT_NAME = "crawl"
RESULT_TEXT_FILE_NAME = "./result/result_{}.tx... | 0.115923 | 0.088308 |
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import scout_apm.core
from scout_apm.compat import ContextDecorator, text
from scout_apm.core.config import ScoutConfig
from scout_apm.core.error import ErrorMonitor
from scout_apm.core.tracked_request import TrackedRequest
... | src/scout_apm/api/__init__.py | from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import scout_apm.core
from scout_apm.compat import ContextDecorator, text
from scout_apm.core.config import ScoutConfig
from scout_apm.core.error import ErrorMonitor
from scout_apm.core.tracked_request import TrackedRequest
... | 0.580709 | 0.152947 |
import sys
from pathlib import Path
import subprocess
from types import SimpleNamespace
import pytest
from pytest_mock import MockerFixture
from mock import MagicMock
import stubber.minify as minify
@pytest.mark.parametrize("source", ["createstubs.py", "createstubs_mem.py", "createstubs_db.py"])
@pytest.mark.slow
de... | tests/integration/minify_test.py | import sys
from pathlib import Path
import subprocess
from types import SimpleNamespace
import pytest
from pytest_mock import MockerFixture
from mock import MagicMock
import stubber.minify as minify
@pytest.mark.parametrize("source", ["createstubs.py", "createstubs_mem.py", "createstubs_db.py"])
@pytest.mark.slow
de... | 0.349422 | 0.486271 |
import os
import nltk
import numpy as np
import pickle
import random
padToken, goToken, eosToken, unknownToken = 0, 1, 2, 3
class Batch:
def __init__(self):
self.encoder_inputs = []
self.encoder_inputs_length = []
self.decoder_targets = []
self.decoder_targets_length = []
def l... | chat_bot_seq2seq_attention/data_loader.py | import os
import nltk
import numpy as np
import pickle
import random
padToken, goToken, eosToken, unknownToken = 0, 1, 2, 3
class Batch:
def __init__(self):
self.encoder_inputs = []
self.encoder_inputs_length = []
self.decoder_targets = []
self.decoder_targets_length = []
def l... | 0.214609 | 0.212538 |
import json
import os
from tkinter import *
import color_helper
# ペイント後の色計算式、テラリアより抜粋し,python用に調整したもの
# base_color(タイル + 壁の色リスト) paint_color(ペンキの色リスト) painted(着色されたタイルと壁)
def painted_color(base_color, paint_color, wall):
red = base_color[0] / 255
green = base_color[1] / 255
blue = base_color[2] / 255
... | tile_searcher.py |
import json
import os
from tkinter import *
import color_helper
# ペイント後の色計算式、テラリアより抜粋し,python用に調整したもの
# base_color(タイル + 壁の色リスト) paint_color(ペンキの色リスト) painted(着色されたタイルと壁)
def painted_color(base_color, paint_color, wall):
red = base_color[0] / 255
green = base_color[1] / 255
blue = base_color[2] / 255
... | 0.384334 | 0.25856 |
import sublime
import sublime_plugin
import subprocess
import os
# Testrun: type: 'PACKAGE, FILE, TEST', file_names / test_name / working_dir
last_testrun = None
# This helper does the work of saving the previous invocation regardless of the calling command
def run_go_tests(window, testrun):
test_args = []
... | go_test_runner.py | import sublime
import sublime_plugin
import subprocess
import os
# Testrun: type: 'PACKAGE, FILE, TEST', file_names / test_name / working_dir
last_testrun = None
# This helper does the work of saving the previous invocation regardless of the calling command
def run_go_tests(window, testrun):
test_args = []
... | 0.476823 | 0.279716 |
import unittest
from module.calc import Calculator
NUMBER_1 = 3.0
NUMBER_2 = 2.0
FAILURE = 'incorrect value'
class CalculatorTest(unittest.TestCase):
def setUp(self):
""" Setup class for testing examples. """
self.calc = Calculator()
def test_last_answer_init(self):
""" Test Last Ans... | tests/test_calc.py | import unittest
from module.calc import Calculator
NUMBER_1 = 3.0
NUMBER_2 = 2.0
FAILURE = 'incorrect value'
class CalculatorTest(unittest.TestCase):
def setUp(self):
""" Setup class for testing examples. """
self.calc = Calculator()
def test_last_answer_init(self):
""" Test Last Ans... | 0.738858 | 0.466299 |
from decimal import Decimal
import itertools
from django.db import models as m
from django.contrib.auth.models import User
from django.db.models.signals import post_save
DATE_FMT = '%Y-%m-%d %H:%M:%S'
currency_field = lambda **kwargs: m.ForeignKey('Currency', related_name='+', **kwargs)
class CurrencyMixin(m.Model)... | src/openlets/core/models.py | from decimal import Decimal
import itertools
from django.db import models as m
from django.contrib.auth.models import User
from django.db.models.signals import post_save
DATE_FMT = '%Y-%m-%d %H:%M:%S'
currency_field = lambda **kwargs: m.ForeignKey('Currency', related_name='+', **kwargs)
class CurrencyMixin(m.Model)... | 0.744378 | 0.268486 |
from enum import Enum as CreateEnum
from . import type
from .check import *
from . utils import *
class CodeTypeMap:
def __init__(self):
self._type_map = {}
self._enums = {}
self._structs = {}
def __getitem__(self, item):
if item in self._type_map:
return self._ty... | core/code.py |
from enum import Enum as CreateEnum
from . import type
from .check import *
from . utils import *
class CodeTypeMap:
def __init__(self):
self._type_map = {}
self._enums = {}
self._structs = {}
def __getitem__(self, item):
if item in self._type_map:
return self._ty... | 0.708717 | 0.137532 |
from __future__ import absolute_import, division, print_function
from itertools import izip, chain
import os
import time
import weakref
try:
from ipyparallel import Client, TimeoutError
HAVE_IPYTHON = True
except ImportError:
try:
from IPython.parallel import Client, TimeoutError
HAVE_IP... | src/pymor/parallel/ipython.py |
from __future__ import absolute_import, division, print_function
from itertools import izip, chain
import os
import time
import weakref
try:
from ipyparallel import Client, TimeoutError
HAVE_IPYTHON = True
except ImportError:
try:
from IPython.parallel import Client, TimeoutError
HAVE_IP... | 0.395484 | 0.116011 |
import argparse
import datetime
import gzip
import multiprocessing
import os
import subprocess
import sys
import tarfile
import urllib.request
import about
import check
import shared
import tax
def parse_arguments():
date = str(datetime.datetime.now().date())
parser = argparse.ArgumentParser(prog='CAT ... | CAT_pack/prepare.py |
import argparse
import datetime
import gzip
import multiprocessing
import os
import subprocess
import sys
import tarfile
import urllib.request
import about
import check
import shared
import tax
def parse_arguments():
date = str(datetime.datetime.now().date())
parser = argparse.ArgumentParser(prog='CAT ... | 0.360377 | 0.113973 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from mpl_toolkits.axes_grid1 import AxesGrid
import matplotlib as mpl
import os
from matplotlib.colors import LinearSegmentedColormap
#-------------------------------------------------------------------------------
# set display width
np.g... | figure/Figure4D.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from mpl_toolkits.axes_grid1 import AxesGrid
import matplotlib as mpl
import os
from matplotlib.colors import LinearSegmentedColormap
#-------------------------------------------------------------------------------
# set display width
np.g... | 0.192274 | 0.480235 |
# TODO: extensive commenting on calculations
import cv2
import numpy as np
class FieldDetection:
"""
The soccer field is determined by the position of the center spot, the
angle of the center line and the size of the center circle.
Since the diameter of the center circle is fixed at 20.5 cm, all othe... | FieldDetecter.py |
# TODO: extensive commenting on calculations
import cv2
import numpy as np
class FieldDetection:
"""
The soccer field is determined by the position of the center spot, the
angle of the center line and the size of the center circle.
Since the diameter of the center circle is fixed at 20.5 cm, all othe... | 0.429429 | 0.63868 |
__copyright__ = 'Copyright(c) <NAME> 2017'
"""
"""
import graphene
from graphene import Node
from graphql_relay.connection.arrayconnection import cursor_to_offset, offset_to_cursor
from unittest.mock import Mock
from a_tuin.api.connection import node_connection_field
from a_tuin.unittests.api.graphql_schema_test_c... | src/a_tuin/unittests/api/test_connection.py | __copyright__ = 'Copyright(c) <NAME> 2017'
"""
"""
import graphene
from graphene import Node
from graphql_relay.connection.arrayconnection import cursor_to_offset, offset_to_cursor
from unittest.mock import Mock
from a_tuin.api.connection import node_connection_field
from a_tuin.unittests.api.graphql_schema_test_c... | 0.761361 | 0.310851 |
from pprint import pprint
import warnings
from aiida.cmdline.utils.decorators import with_dbenv
from aiida.common import NotExistentAttributeError
from aiida.orm import (load_node,
Node)
from phonopy import Phonopy
from twinpy.interfaces.aiida.base import (check_process_class,
... | twinpy/interfaces/aiida/phonopy.py | from pprint import pprint
import warnings
from aiida.cmdline.utils.decorators import with_dbenv
from aiida.common import NotExistentAttributeError
from aiida.orm import (load_node,
Node)
from phonopy import Phonopy
from twinpy.interfaces.aiida.base import (check_process_class,
... | 0.655777 | 0.150903 |
import base64
import requests
from keepasshttp import AES_256_CBC
# fmt: off
data = {
"associate": b'{"RequestType":"associate","Success":true,"Id":"unittest_tmp","Count":0,"Version":"1.8.4.2",'
b'"Hash":"46e1d15ab37d8a2700b0c1755244433514b7a13f","Nonce":"SDfFtzkTrrrajXYfi0/wYA==",'
... | tests/mock.py | import base64
import requests
from keepasshttp import AES_256_CBC
# fmt: off
data = {
"associate": b'{"RequestType":"associate","Success":true,"Id":"unittest_tmp","Count":0,"Version":"1.8.4.2",'
b'"Hash":"46e1d15ab37d8a2700b0c1755244433514b7a13f","Nonce":"SDfFtzkTrrrajXYfi0/wYA==",'
... | 0.312685 | 0.205236 |
import socket
import termcolor
import json
import os
import threading
def reliable_recv(target):
data = ''
while True:
try:
data = data + target.recv(1024).decode().rstrip()
return json.loads(data)
except ValueError:
continue
def reliable_send(target, data):... | Backdoor/cmd.py | import socket
import termcolor
import json
import os
import threading
def reliable_recv(target):
data = ''
while True:
try:
data = data + target.recv(1024).decode().rstrip()
return json.loads(data)
except ValueError:
continue
def reliable_send(target, data):... | 0.084578 | 0.115262 |
from typing import Union, List, Dict, Any, Optional
from tqdm import tqdm
import layoutparser as lp
from mmda.types.names import *
from mmda.types.document import Document
from mmda.types.box import Box
from mmda.types.annotation import BoxGroup, Annotation
from mmda.predictors.base_predictors.base_predictor import B... | mmda/predictors/lp_predictors.py | from typing import Union, List, Dict, Any, Optional
from tqdm import tqdm
import layoutparser as lp
from mmda.types.names import *
from mmda.types.document import Document
from mmda.types.box import Box
from mmda.types.annotation import BoxGroup, Annotation
from mmda.predictors.base_predictors.base_predictor import B... | 0.949306 | 0.242946 |
from datetime import date
from p01_kennenlernen import PythonLib
from p01_kennenlernen.PythonLib import celsius_nach_fahrenheit
temperaturenGC = [0.7, 2.1, 4.2, 8.2, 12.5, 15.6, 16.9, 16.3, 13.6, 9.5, 4.6, 2.3] #Durchschnittstemp. in Bielefeld
print("Temperaturen in °C:", temperaturenGC)
daniel = ["Daniel", ... | ___Python/Torsten/Python-Kurs/p03_lambda/m06_filtern.py | from datetime import date
from p01_kennenlernen import PythonLib
from p01_kennenlernen.PythonLib import celsius_nach_fahrenheit
temperaturenGC = [0.7, 2.1, 4.2, 8.2, 12.5, 15.6, 16.9, 16.3, 13.6, 9.5, 4.6, 2.3] #Durchschnittstemp. in Bielefeld
print("Temperaturen in °C:", temperaturenGC)
daniel = ["Daniel", ... | 0.221267 | 0.358465 |
import os, os.path, signal, subprocess, unittest
# Copyright 2018, 2020 <NAME>, <EMAIL>
#
# 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
#
# ... | test/test.py | import os, os.path, signal, subprocess, unittest
# Copyright 2018, 2020 <NAME>, <EMAIL>
#
# 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
#
# ... | 0.502686 | 0.260689 |
import os
import sys
import zipfile
import py
import pytest
ast = pytest.importorskip("ast")
if sys.platform.startswith("java"):
# XXX should be xfail
pytest.skip("assert rewrite does currently not work on jython")
from _pytest.assertion import util
from _pytest.assertion.rewrite import rewrite_asserts, PYTES... | testing/test_assertrewrite.py | import os
import sys
import zipfile
import py
import pytest
ast = pytest.importorskip("ast")
if sys.platform.startswith("java"):
# XXX should be xfail
pytest.skip("assert rewrite does currently not work on jython")
from _pytest.assertion import util
from _pytest.assertion.rewrite import rewrite_asserts, PYTES... | 0.374791 | 0.540014 |
import re
import spacy
from spacy.symbols import ORTH
from .spacy_tokenizer import SpacyTokenizer
from .utils import DateRegex, CleanRegex, ClinicalRegex
def read_abbreviations():
import importlib.resources as pkg_resources
from . import abbreviations
abbrevs = []
with pkg_resources.open_text(abbreviat... | src/robust_deid/ner_datasets/preprocessing/tokenizers/clinical_spacy_tokenizer.py | import re
import spacy
from spacy.symbols import ORTH
from .spacy_tokenizer import SpacyTokenizer
from .utils import DateRegex, CleanRegex, ClinicalRegex
def read_abbreviations():
import importlib.resources as pkg_resources
from . import abbreviations
abbrevs = []
with pkg_resources.open_text(abbreviat... | 0.514888 | 0.214465 |
from django.db import models
from datetime import datetime
from django.utils.timezone import now
import uuid
from django_extensions.db.fields import AutoSlugField
from core.utils_no_dependencies import rgetattr
import unicodedata
import re
#managed_value = False
managed_tables = True
managed_views = False
class RetU... | escalate/core/models/core_tables.py | from django.db import models
from datetime import datetime
from django.utils.timezone import now
import uuid
from django_extensions.db.fields import AutoSlugField
from core.utils_no_dependencies import rgetattr
import unicodedata
import re
#managed_value = False
managed_tables = True
managed_views = False
class RetU... | 0.572723 | 0.132262 |
import numpy
import unittest
import sys
PyRLA_dir = '../../'
sys.path.append(PyRLA_dir)
from optimization import cg_cond
class TestCgCondSRFT(unittest.TestCase):
def test_converge1(self):
w_solved_vec, is_converged_bool = cg_cond.cg_cond(x_mat, y_vec, t2_mat, tol=1e-3)
dist_vec = numpy.dot(x_mat... | optimization/test/test_cg_cond.py | import numpy
import unittest
import sys
PyRLA_dir = '../../'
sys.path.append(PyRLA_dir)
from optimization import cg_cond
class TestCgCondSRFT(unittest.TestCase):
def test_converge1(self):
w_solved_vec, is_converged_bool = cg_cond.cg_cond(x_mat, y_vec, t2_mat, tol=1e-3)
dist_vec = numpy.dot(x_mat... | 0.309232 | 0.722386 |
from django.contrib import admin
from . import models
from clouds.base.admin import StaticModelAdmin, OwnershipModelAdmin, OperatableAdminMixin, OperationAdmin
from django.utils.html import format_html
from django.urls import reverse
from django.shortcuts import redirect
from django import forms
from django.db.models i... | pk1/data/admin.py | from django.contrib import admin
from . import models
from clouds.base.admin import StaticModelAdmin, OwnershipModelAdmin, OperatableAdminMixin, OperationAdmin
from django.utils.html import format_html
from django.urls import reverse
from django.shortcuts import redirect
from django import forms
from django.db.models i... | 0.470737 | 0.053403 |
import pytest
import github3
from .helper import (UnitHelper, UnitIteratorHelper, create_url_helper,)
url_for = create_url_helper(
'https://api.github.com/users/octocat'
)
example_data = {
"login": "octocat",
"id": 1,
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_i... | tests/unit/test_users.py | import pytest
import github3
from .helper import (UnitHelper, UnitIteratorHelper, create_url_helper,)
url_for = create_url_helper(
'https://api.github.com/users/octocat'
)
example_data = {
"login": "octocat",
"id": 1,
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_i... | 0.655997 | 0.521837 |
import unittest
import itertools
import os
import sys
from streamsx.topology.topology import *
from streamsx.topology.topology import Topology
from streamsx.topology.context import submit, ContextTypes, ConfigParams, JobConfig
class TestEdge(unittest.TestCase):
def _is_not_blank(self, s):
if s is None:
... | test/python/topology/test2_edge.py | import unittest
import itertools
import os
import sys
from streamsx.topology.topology import *
from streamsx.topology.topology import Topology
from streamsx.topology.context import submit, ContextTypes, ConfigParams, JobConfig
class TestEdge(unittest.TestCase):
def _is_not_blank(self, s):
if s is None:
... | 0.187579 | 0.263931 |
from copy import deepcopy
from lqc.model.element_tree import ElementTree
from lqc.model.style_map import StyleMap
class RunSubject:
html_tree: ElementTree
# Format: html_tree = {
# tag: 'div',
# id: '12981283',
# children: [html_tree, ...]
# }
base_styles: StyleMap
# Forma... | src/lqc/model/run_subject.py | from copy import deepcopy
from lqc.model.element_tree import ElementTree
from lqc.model.style_map import StyleMap
class RunSubject:
html_tree: ElementTree
# Format: html_tree = {
# tag: 'div',
# id: '12981283',
# children: [html_tree, ...]
# }
base_styles: StyleMap
# Forma... | 0.612426 | 0.139778 |
import os
import torch
import numpy as np
import torchvision
import transforms as T
import utils
from PIL import Image
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
from engine import train_one_epoch, evaluate
from torch.utils... | train.py | import os
import torch
import numpy as np
import torchvision
import transforms as T
import utils
from PIL import Image
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
from engine import train_one_epoch, evaluate
from torch.utils... | 0.804598 | 0.51812 |
from typing import Callable, List, Optional, Tuple, Dict, Any
from inspect import getfullargspec, getdoc
import re
from .rule import SubcommandRule
from .rule_factory import argument, arguments, flag, parameter, subcommand
def create_decorated_subcommand(function: Callable[..., None], keyword: str) -> SubcommandRule... | nuclear/builder/decorator_builder.py | from typing import Callable, List, Optional, Tuple, Dict, Any
from inspect import getfullargspec, getdoc
import re
from .rule import SubcommandRule
from .rule_factory import argument, arguments, flag, parameter, subcommand
def create_decorated_subcommand(function: Callable[..., None], keyword: str) -> SubcommandRule... | 0.71103 | 0.116638 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future import standard_library
from future.builtins import * # noqa: F401, F403
standard_library.install_aliases()
__metaclass__ = type
# ===============================================================... | fallout-cli/tests/conftest.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future import standard_library
from future.builtins import * # noqa: F401, F403
standard_library.install_aliases()
__metaclass__ = type
# ===============================================================... | 0.382141 | 0.160036 |
import configparser
import logging
import logging.config
import os
import sys
import toml
def load_logging() -> None:
"""Load logging configuration."""
try:
logging.config.fileConfig("config/logging.ini")
except KeyError as inst:
logging_config_recovery(inst)
except FileNotFoundError a... | utils/lib.py | import configparser
import logging
import logging.config
import os
import sys
import toml
def load_logging() -> None:
"""Load logging configuration."""
try:
logging.config.fileConfig("config/logging.ini")
except KeyError as inst:
logging_config_recovery(inst)
except FileNotFoundError a... | 0.441432 | 0.093347 |
import unittest
from io import BytesIO
from pathlib import Path
from cw.xsens import XSensParser, XDI, StatusWordType
from cw.object_hierarchies import object_hierarchy_equals
from cw.flex_file import flex_load
import pprint
pprint = pprint.PrettyPrinter(indent=4).pprint
test_dir_path = Path(__file__).parent
cla... | cw/test/test_xsens.py | import unittest
from io import BytesIO
from pathlib import Path
from cw.xsens import XSensParser, XDI, StatusWordType
from cw.object_hierarchies import object_hierarchy_equals
from cw.flex_file import flex_load
import pprint
pprint = pprint.PrettyPrinter(indent=4).pprint
test_dir_path = Path(__file__).parent
cla... | 0.258326 | 0.351673 |
import torch.nn as nn
import segmentation_models_pytorch as smp
import torch
from torch.cuda.amp import autocast
class seg_qyl(nn.Module):
def __init__(self, model_name, n_class):
super(seg_qyl,self).__init__()
self.model = smp.Unet(# UnetPlusPlus
encoder_name=model_name, # c... | python_developer_tools/cv/bases/model_modify.py | import torch.nn as nn
import segmentation_models_pytorch as smp
import torch
from torch.cuda.amp import autocast
class seg_qyl(nn.Module):
def __init__(self, model_name, n_class):
super(seg_qyl,self).__init__()
self.model = smp.Unet(# UnetPlusPlus
encoder_name=model_name, # c... | 0.941476 | 0.350394 |
from .DAVIS.DAVIS import DAVISDataset, DAVIS2017Dataset
from datasets.Custom.Custom import CustomDataset
from datasets.DAVIS.DAVIS2017_oneshot import Davis2017OneshotDataset
from datasets.DAVIS.DAVIS_oneshot import DavisOneshotDataset
from datasets.PascalVOC.PascalVOC_instance import PascalVOCInstanceDataset
from datas... | datasets/Loader.py | from .DAVIS.DAVIS import DAVISDataset, DAVIS2017Dataset
from datasets.Custom.Custom import CustomDataset
from datasets.DAVIS.DAVIS2017_oneshot import Davis2017OneshotDataset
from datasets.DAVIS.DAVIS_oneshot import DavisOneshotDataset
from datasets.PascalVOC.PascalVOC_instance import PascalVOCInstanceDataset
from datas... | 0.509276 | 0.439988 |
from django.conf.urls import url
from .views import (
StaffIndex,
OrganizationStaffListView,
OrganizationStaffDetailView,
InvoiceStaffView,
InvoicePhantomJSView,
BillingLogCreateView,
OrganizationBillingLogListingView,
OrganizationExportExcel,
OrganizationStaffNoContactListView,
... | members/crm/urls_staff.py | from django.conf.urls import url
from .views import (
StaffIndex,
OrganizationStaffListView,
OrganizationStaffDetailView,
InvoiceStaffView,
InvoicePhantomJSView,
BillingLogCreateView,
OrganizationBillingLogListingView,
OrganizationExportExcel,
OrganizationStaffNoContactListView,
... | 0.274449 | 0.112795 |
import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import numpy as np
import mnist_inference
import mnist_train
from numpy.random import RandomState
import os
# generate new random dataset for test in 3 secs after close figure window manually
... | img_proc/mnist_eval.py | import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import numpy as np
import mnist_inference
import mnist_train
from numpy.random import RandomState
import os
# generate new random dataset for test in 3 secs after close figure window manually
... | 0.326379 | 0.564579 |
uName = input("what's your name? ").strip().capitalize()
uCountry = input("what's your country? ").strip().lower()
isStudent = input("Are You Student(yes or no)? ").strip().lower()
cName = "Python Basic's"
cPrice = 100
cDiscount = None
if uCountry == "sudan" or uCountry == "south sudan":
if isStudent == "yes":
... | Nested IF/index.py | uName = input("what's your name? ").strip().capitalize()
uCountry = input("what's your country? ").strip().lower()
isStudent = input("Are You Student(yes or no)? ").strip().lower()
cName = "Python Basic's"
cPrice = 100
cDiscount = None
if uCountry == "sudan" or uCountry == "south sudan":
if isStudent == "yes":
... | 0.226869 | 0.351728 |
from os import listdir
from pathlib import Path
from typing import Any
import pytest
from prefect import Flow
from prefect import Task
from prefect import task
from prefect.engine.state import State
from drem.utilities.visualize import VisualizeMixin
graphviz = pytest.importorskip("graphviz")
@task
def do_compli... | tests/unit/utilities/test_visualize.py | from os import listdir
from pathlib import Path
from typing import Any
import pytest
from prefect import Flow
from prefect import Task
from prefect import task
from prefect.engine.state import State
from drem.utilities.visualize import VisualizeMixin
graphviz = pytest.importorskip("graphviz")
@task
def do_compli... | 0.761893 | 0.362574 |
import os,sys,gzip,zipfile
from xml.etree.ElementTree import ElementTree
import numpy as np
class FEBParser(object):
def __init__(self, fname):
self.fname = fname
self.root = None
self.tree = None
self.ext = os.path.splitext(fname)[1].upper()
self._parse_xml()
def _pars... | feblender/io/febio.py | import os,sys,gzip,zipfile
from xml.etree.ElementTree import ElementTree
import numpy as np
class FEBParser(object):
def __init__(self, fname):
self.fname = fname
self.root = None
self.tree = None
self.ext = os.path.splitext(fname)[1].upper()
self._parse_xml()
def _pars... | 0.097632 | 0.09277 |
import tkinter as tk
import cv2
import numpy as np
import face_recognition
import os
from datetime import datetime
import mysql.connector
from PIL import Image, ImageTk
from time import strftime
def takeattendance(btn):
tablename=btn["text"]
path = 'Image_Dataset'
images = []
classNames... | SourceCode.py | import tkinter as tk
import cv2
import numpy as np
import face_recognition
import os
from datetime import datetime
import mysql.connector
from PIL import Image, ImageTk
from time import strftime
def takeattendance(btn):
tablename=btn["text"]
path = 'Image_Dataset'
images = []
classNames... | 0.222109 | 0.129293 |
import io
import logging
import os
import pandas as pd
import dataflow.core.nodes.sinks as dtfconosin
import helpers.hunit_test as hunitest
_LOG = logging.getLogger(__name__)
class TestWriteDf(hunitest.TestCase):
def test_write(self) -> None:
"""
Round-trip test on df serializing/deserializing.... | dataflow/core/nodes/test/test_sinks.py | import io
import logging
import os
import pandas as pd
import dataflow.core.nodes.sinks as dtfconosin
import helpers.hunit_test as hunitest
_LOG = logging.getLogger(__name__)
class TestWriteDf(hunitest.TestCase):
def test_write(self) -> None:
"""
Round-trip test on df serializing/deserializing.... | 0.576065 | 0.31538 |
import logging
import contextlib
import random
import time
import gevent
import json
import math
from teuthology import misc as teuthology
from tasks import ceph_manager
log = logging.getLogger(__name__)
def _get_mons(ctx):
"""
Get monitor names from the context value.
"""
mons = [f[len('mon.'):] for ... | qa/tasks/mon_thrash.py | import logging
import contextlib
import random
import time
import gevent
import json
import math
from teuthology import misc as teuthology
from tasks import ceph_manager
log = logging.getLogger(__name__)
def _get_mons(ctx):
"""
Get monitor names from the context value.
"""
mons = [f[len('mon.'):] for ... | 0.548674 | 0.237532 |
import types
from flask_apispec import (FlaskApiSpec, MethodResource, ResourceMeta, doc,
marshal_with, use_kwargs, utils)
from flask_apispec.apidoc import ResourceConverter, ViewConverter
from flask_apispec.extension import make_apispec
from .constants import CREATE, GET, LIST, POST
from .u... | backend/api/docs.py | import types
from flask_apispec import (FlaskApiSpec, MethodResource, ResourceMeta, doc,
marshal_with, use_kwargs, utils)
from flask_apispec.apidoc import ResourceConverter, ViewConverter
from flask_apispec.extension import make_apispec
from .constants import CREATE, GET, LIST, POST
from .u... | 0.55254 | 0.06165 |
import numpy
# TODO the first two functions could go into a helper and be shared with tri
def _parsed_strings_to_array(strings):
return numpy.array(
"".join(strings).replace("&", "").replace("/", "").replace("D", "e").split(","),
dtype=float,
)
def _parse():
# The Fortran file contains mu... | tools/xiao_gimbutas/import_xiao_gimbutas_tet.py | import numpy
# TODO the first two functions could go into a helper and be shared with tri
def _parsed_strings_to_array(strings):
return numpy.array(
"".join(strings).replace("&", "").replace("/", "").replace("D", "e").split(","),
dtype=float,
)
def _parse():
# The Fortran file contains mu... | 0.243822 | 0.580084 |
from medcam import medcam
import torchvision.models as tvmodels
import torch
import torch.nn as nn
try:
from wama.utils import show2D
# https://github.com/WAMAWAMA/wama_medic
# a medical image precessing toolbox
flag = True
except:
flag = False
pass
def tensor2numpy(tensor):
return tensor.d... | demos/MultiInput_MultiOutput_demo.py | from medcam import medcam
import torchvision.models as tvmodels
import torch
import torch.nn as nn
try:
from wama.utils import show2D
# https://github.com/WAMAWAMA/wama_medic
# a medical image precessing toolbox
flag = True
except:
flag = False
pass
def tensor2numpy(tensor):
return tensor.d... | 0.902183 | 0.531817 |
import csv
import torch
import librosa
import numpy as np
from pathlib import Path
from svd.adversaries.adv_audio import get_feature
def str_to_bool(str_bool):
""" Helper function to convert string to boolean. """
if str_bool == "False":
return False
return True
def check_convergence(log_file):... | svd/adversaries/log_analysis.py | import csv
import torch
import librosa
import numpy as np
from pathlib import Path
from svd.adversaries.adv_audio import get_feature
def str_to_bool(str_bool):
""" Helper function to convert string to boolean. """
if str_bool == "False":
return False
return True
def check_convergence(log_file):... | 0.615435 | 0.484868 |
import random
from random import randrange
from disco.types.channel import ChannelType
from disco.types.permissions import Permissions
from disco.types.message import MessageEmbed
from GamesKeeper.models.guild import Guild
from GamesKeeper import bot_config
from GamesKeeper import NO_EMOJI_ID, YES_EMOJI_ID, NO_EMOJI, Y... | GamesKeeper/games/uno_justin.py | import random
from random import randrange
from disco.types.channel import ChannelType
from disco.types.permissions import Permissions
from disco.types.message import MessageEmbed
from GamesKeeper.models.guild import Guild
from GamesKeeper import bot_config
from GamesKeeper import NO_EMOJI_ID, YES_EMOJI_ID, NO_EMOJI, Y... | 0.351979 | 0.1844 |
from pathlib import Path
# Third party libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.table import Table
# Local imports
from ..logs import logging
logger = logging.getLogger("tool box")
def create_directory(directory_path:str) -> None:
"""Create new folder in path"""
Path(direc... | algorl/src/tool_box.py | from pathlib import Path
# Third party libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.table import Table
# Local imports
from ..logs import logging
logger = logging.getLogger("tool box")
def create_directory(directory_path:str) -> None:
"""Create new folder in path"""
Path(direc... | 0.810291 | 0.392453 |
import datetime
import os
import random
from typing import Tuple, Union, TypeVar, List, Callable
import libnacl.secret
from base58 import b58decode
from common.serializers.serialization import serialize_msg_for_signing
from plenum.common.types import f
from plenum.common.util import isHex, cryptonymToHex
from common.e... | indy_common/util.py | import datetime
import os
import random
from typing import Tuple, Union, TypeVar, List, Callable
import libnacl.secret
from base58 import b58decode
from common.serializers.serialization import serialize_msg_for_signing
from plenum.common.types import f
from plenum.common.util import isHex, cryptonymToHex
from common.e... | 0.561575 | 0.159021 |
import os
import sys
import time
import codecs
import requests
import numpy as np
import xmlrpc.client as xc
from flask import Flask, render_template, request
from flask_pymongo import PyMongo
app = Flask(__name__)
MAX_LENGTH=50 # the maximum sentence length of word alignment visualization
MAX_TERMS=15 # the maxi... | ChrEnTranslator.py | import os
import sys
import time
import codecs
import requests
import numpy as np
import xmlrpc.client as xc
from flask import Flask, render_template, request
from flask_pymongo import PyMongo
app = Flask(__name__)
MAX_LENGTH=50 # the maximum sentence length of word alignment visualization
MAX_TERMS=15 # the maxi... | 0.286369 | 0.181662 |
from vimeo.logger import LoggerSingleton
# GENERIC EXCEPTION
class VimeoException(Exception):
error_text = None
def __init__(self, write_log=True):
self.logger = LoggerSingleton()
if write_log:
self.write_log(self.error_text)
def __str__(self):
return repr(self.error_... | src/vimeo/exceptions.py | from vimeo.logger import LoggerSingleton
# GENERIC EXCEPTION
class VimeoException(Exception):
error_text = None
def __init__(self, write_log=True):
self.logger = LoggerSingleton()
if write_log:
self.write_log(self.error_text)
def __str__(self):
return repr(self.error_... | 0.715722 | 0.061933 |
import json
import random
from datetime import datetime
from django.conf import settings
from django.core.cache import caches
CACHE_CONFIG_NAME = 'session' if 'session' in settings.CACHES.keys() else next(iter(settings.CACHES.keys()))
def get_random_string(length=12,
allowed_chars='abcdefghij... | mt_jwt_auth/jwt_user/storages/django_cache.py | import json
import random
from datetime import datetime
from django.conf import settings
from django.core.cache import caches
CACHE_CONFIG_NAME = 'session' if 'session' in settings.CACHES.keys() else next(iter(settings.CACHES.keys()))
def get_random_string(length=12,
allowed_chars='abcdefghij... | 0.390825 | 0.125574 |
# In[317]:
import numpy as np
import os
class Ply(object):
"""Class to represent a ply in memory, read plys, and write plys.
"""
def __init__(self, ply_path=None, triangles=None, points=None, normals=None, colors=None):
"""Initialize the in memory ply representation.
Args:
... | Read_Write_PLY.py |
# In[317]:
import numpy as np
import os
class Ply(object):
"""Class to represent a ply in memory, read plys, and write plys.
"""
def __init__(self, ply_path=None, triangles=None, points=None, normals=None, colors=None):
"""Initialize the in memory ply representation.
Args:
... | 0.382372 | 0.48749 |
import pytest
import responses
import gitlab
@pytest.fixture
def resp_groups():
content = {"name": "name", "id": 1, "path": "path"}
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/groups/1"... | venv/lib/python3.7/site-packages/gitlab/tests/objects/test_groups.py | import pytest
import responses
import gitlab
@pytest.fixture
def resp_groups():
content = {"name": "name", "id": 1, "path": "path"}
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/groups/1"... | 0.358802 | 0.33928 |
import os
from updating_config_loader import UpdatingConfigLoader
TEST_URL = "https://gist.githubusercontent.com/tazard/ecdd907a01b1c35d46347f6c8557ee65/raw/b41bba2ed414701fbce5d235a62879479ea673bb/config_dummy.json"
TEST_URL_BAD_JSON = "https://gist.githubusercontent.com/tazard/d0f3f90014b38353249d6d55215bacc2/raw/91... | test_updating_config_loader.py | import os
from updating_config_loader import UpdatingConfigLoader
TEST_URL = "https://gist.githubusercontent.com/tazard/ecdd907a01b1c35d46347f6c8557ee65/raw/b41bba2ed414701fbce5d235a62879479ea673bb/config_dummy.json"
TEST_URL_BAD_JSON = "https://gist.githubusercontent.com/tazard/d0f3f90014b38353249d6d55215bacc2/raw/91... | 0.201106 | 0.163646 |