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 |
|---|---|---|---|---|
try:
import simplejson as json
except ImportError:
import json
from bigml.bigmlconnection import DOWNLOAD_DIR
from bigml.resourcehandler import ResourceHandler
from bigml.resourcehandler import (check_resource_type,
get_batch_topic_distribution_id)
from bigml.constants import... | bigml/batchtopicdistributionhandler.py | try:
import simplejson as json
except ImportError:
import json
from bigml.bigmlconnection import DOWNLOAD_DIR
from bigml.resourcehandler import ResourceHandler
from bigml.resourcehandler import (check_resource_type,
get_batch_topic_distribution_id)
from bigml.constants import... | 0.611498 | 0.198491 |
all_logs = "9253a0d GDYendell: Move some functionality to helper (RELEASE: 2-1)\n" \
"9253a0d GDYendell: Move some functionality to helper\n" \
"1dd77cd GDYendell: Add helper module\n" \
"e20bad5 GDYendell: Implement test changes (RELEASE: 2-0)\n" \
"e20bad5 GDYendell: Implem... | system_testing/logs_since_release/logs.py | all_logs = "9253a0d GDYendell: Move some functionality to helper (RELEASE: 2-1)\n" \
"9253a0d GDYendell: Move some functionality to helper\n" \
"1dd77cd GDYendell: Add helper module\n" \
"e20bad5 GDYendell: Implement test changes (RELEASE: 2-0)\n" \
"e20bad5 GDYendell: Implem... | 0.399226 | 0.404919 |
from brownie import DynamicAddressQueue as queue
from brownie import accounts
from scripts.utils import get_account
import pytest
def test_queue_is_empty():
acc = get_account()
q = queue.deploy({'from': acc})
assert q.isEmpty() == True
def test_enqueue_and_dequeue_one_address():
main_acc = get_account... | tests/test_queue_unit.py | from brownie import DynamicAddressQueue as queue
from brownie import accounts
from scripts.utils import get_account
import pytest
def test_queue_is_empty():
acc = get_account()
q = queue.deploy({'from': acc})
assert q.isEmpty() == True
def test_enqueue_and_dequeue_one_address():
main_acc = get_account... | 0.50952 | 0.528838 |
import argparse
import os
import shutil
from subprocess import PIPE
from subprocess import Popen
import sys
from _pkg_meta import version
from coverage import generate_coverage
from reports import compile_reports
from reports import get_coverage_reports
def delete_folder(folder):
"""Delete a folder using the giv... | goverge/main.py | import argparse
import os
import shutil
from subprocess import PIPE
from subprocess import Popen
import sys
from _pkg_meta import version
from coverage import generate_coverage
from reports import compile_reports
from reports import get_coverage_reports
def delete_folder(folder):
"""Delete a folder using the giv... | 0.459561 | 0.194043 |
import folium
import pandas as pd
from vincent import Axis
from vincent import Data
from vincent import DataRef
from vincent import Mark
from vincent import MarkProperties
from vincent import MarkRef
from vincent import PropertySet
from vincent import Scale
from vincent import ValueRef
from vincent import Visualization... | plbmng/lib/full_map.py | import folium
import pandas as pd
from vincent import Axis
from vincent import Data
from vincent import DataRef
from vincent import Mark
from vincent import MarkProperties
from vincent import MarkRef
from vincent import PropertySet
from vincent import Scale
from vincent import ValueRef
from vincent import Visualization... | 0.682256 | 0.44559 |
import numpy as np
def header4classifiers(classifiers):
text = ""
text += "\\begin{table}[!ht]\n"
text += "\\centering\n"
text += "\\scriptsize\n"
text += "\\begin{tabular}{l|\n"
for i, clf in enumerate(classifiers):
text += "S[table-format=0.3, table-figures-uncertainty=1]%s\n" % (
... | latextabs.py | import numpy as np
def header4classifiers(classifiers):
text = ""
text += "\\begin{table}[!ht]\n"
text += "\\centering\n"
text += "\\scriptsize\n"
text += "\\begin{tabular}{l|\n"
for i, clf in enumerate(classifiers):
text += "S[table-format=0.3, table-figures-uncertainty=1]%s\n" % (
... | 0.376852 | 0.255392 |
import csv
table_1_raw = """E.C., Voc, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10
VCB, 0.6, -0.04287, 1.035, -0.083, 0, 0, -4.783E-09, 1.962E-06, -0.000229, 0.003141, 1.092
VCB, 2.7, 0.0065, 1.001, -0.024, -1.557E-12, 4.556E-10, -4.186E-08, 8.346E-07, 5.482E-05, -0.003191, 0.9729
VCB, 14.3, 0.005795, 1.015, -0.011, -1.5... | ieee_1584/tables.py |
import csv
table_1_raw = """E.C., Voc, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10
VCB, 0.6, -0.04287, 1.035, -0.083, 0, 0, -4.783E-09, 1.962E-06, -0.000229, 0.003141, 1.092
VCB, 2.7, 0.0065, 1.001, -0.024, -1.557E-12, 4.556E-10, -4.186E-08, 8.346E-07, 5.482E-05, -0.003191, 0.9729
VCB, 14.3, 0.005795, 1.015, -0.011, -1.5... | 0.171408 | 0.249882 |
import discord
import os
import comeback
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
aw... | src/example_bot.py |
import discord
import os
import comeback
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
aw... | 0.260484 | 0.067979 |
import re
import ast
import random
import time
from .helpers import VariableNameGenerator, RandomDataTypeGenerator
import regex
def one_liner(code):
# TODO: strings with \n at top
formatted_code = re.sub(
r"(;)\1+",
";",
"""exec(\"\"\"{};\"\"\")""".format(
code.replace("\n"... | python_obfuscator/techniques.py | import re
import ast
import random
import time
from .helpers import VariableNameGenerator, RandomDataTypeGenerator
import regex
def one_liner(code):
# TODO: strings with \n at top
formatted_code = re.sub(
r"(;)\1+",
";",
"""exec(\"\"\"{};\"\"\")""".format(
code.replace("\n"... | 0.128143 | 0.188772 |
from dash.development.base_component import Component, _explicitize_args
class DashArcherElement(Component):
"""A DashArcherElement component.
DashArcherElement component is a wrapper for ArcherElement component
from react-archer module. See usage: https://github.com/pierpo/react-archer
Keyword arguments:
- chi... | dash_archer/DashArcherElement.py |
from dash.development.base_component import Component, _explicitize_args
class DashArcherElement(Component):
"""A DashArcherElement component.
DashArcherElement component is a wrapper for ArcherElement component
from react-archer module. See usage: https://github.com/pierpo/react-archer
Keyword arguments:
- chi... | 0.856917 | 0.256774 |
# Streaming
# before you can start writing a stream listener script, following libraries have to be imported
# time library will be used create a time-out feature for the script
# os library will be used to set your working directory
import time
from tweepy import Stream
from tweepy import OAuthHandler
from ... | Twitter-Data-Analysis/tweepy2.py |
# Streaming
# before you can start writing a stream listener script, following libraries have to be imported
# time library will be used create a time-out feature for the script
# os library will be used to set your working directory
import time
from tweepy import Stream
from tweepy import OAuthHandler
from ... | 0.345878 | 0.080213 |
from nintendo.pia.types import StationConnectionInfo, IdentificationInfo
from nintendo.common import scheduler
import random
import time
class ConnectionState:
DISCONNECTED = 0
WAIT_INVERSE_REQUEST = 1
WAIT_INVERSE_RESPONSE = 2
WAIT_RESPONSE = 3
CONNECTED = 4
ERROR = 5
class Station:
def __init__(self):
se... | nintendo/pia/stations.py | from nintendo.pia.types import StationConnectionInfo, IdentificationInfo
from nintendo.common import scheduler
import random
import time
class ConnectionState:
DISCONNECTED = 0
WAIT_INVERSE_REQUEST = 1
WAIT_INVERSE_RESPONSE = 2
WAIT_RESPONSE = 3
CONNECTED = 4
ERROR = 5
class Station:
def __init__(self):
se... | 0.296552 | 0.118029 |
from xlrd import open_workbook,cellname
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import smtplib
import re
import json
class Certificate_G... | certificate_generator.py |
from xlrd import open_workbook,cellname
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import smtplib
import re
import json
class Certificate_G... | 0.25992 | 0.076339 |
import io
from Crypto.PublicKey import RSA
from decimal import Decimal
from twisted.internet import defer
from lbrynet.core import PTCWallet
from lbrynet.core import BlobAvailability
from lbrynet.daemon import ExchangeRateManager as ERM
from lbrynet import conf
KB = 2**10
class FakeLBRYFile(object):
def __init... | tests/mocks.py | import io
from Crypto.PublicKey import RSA
from decimal import Decimal
from twisted.internet import defer
from lbrynet.core import PTCWallet
from lbrynet.core import BlobAvailability
from lbrynet.daemon import ExchangeRateManager as ERM
from lbrynet import conf
KB = 2**10
class FakeLBRYFile(object):
def __init... | 0.542621 | 0.095307 |
import pytest
import copy
import json
from django.db import DatabaseError
from awx.main.utils.common import (
model_instance_diff,
model_to_dict,
get_model_for_type
)
from awx.main import models
@pytest.mark.django_db
def test_model_to_dict_user(alice):
username = copy.copy(alice.username)
pass... | awx/main/tests/functional/utils/test_common.py | import pytest
import copy
import json
from django.db import DatabaseError
from awx.main.utils.common import (
model_instance_diff,
model_to_dict,
get_model_for_type
)
from awx.main import models
@pytest.mark.django_db
def test_model_to_dict_user(alice):
username = copy.copy(alice.username)
pass... | 0.510985 | 0.472197 |
import logging
import coloredlogs
import os
from tempfile import NamedTemporaryFile
from cyvcf2 import VCF
from pybedtools import BedTool
LOG = logging.getLogger(__name__)
def vcf_intersect(vcf_path, bed_panel):
"""Uses Pybedtoolst a.intersect(b) to ectract from VCF variants mapping in the gene panel intervals
... | cgbeacon/utils/vcf_panel_filter.py |
import logging
import coloredlogs
import os
from tempfile import NamedTemporaryFile
from cyvcf2 import VCF
from pybedtools import BedTool
LOG = logging.getLogger(__name__)
def vcf_intersect(vcf_path, bed_panel):
"""Uses Pybedtoolst a.intersect(b) to ectract from VCF variants mapping in the gene panel intervals
... | 0.757974 | 0.453383 |
import datetime
import io
from itertools import islice
from os.path import exists
from typing import Union
import numpy as np
from openpyxl import load_workbook
from qf_lib.common.utils.logging.qf_parent_logger import qf_logger
from qf_lib.containers.dataframe.qf_dataframe import QFDataFrame
from qf_lib.containers.s... | qf_lib/documents_utils/excel/excel_importer.py |
import datetime
import io
from itertools import islice
from os.path import exists
from typing import Union
import numpy as np
from openpyxl import load_workbook
from qf_lib.common.utils.logging.qf_parent_logger import qf_logger
from qf_lib.containers.dataframe.qf_dataframe import QFDataFrame
from qf_lib.containers.s... | 0.867962 | 0.45423 |
import argparse
import logging
import logging.handlers
import warnings
import os
from datetime import datetime
import itertools
import torch
import torch.nn as nn
from maxsmi.utils_data import data_retrieval
from maxsmi.utils_smiles import (
smiles_to_canonical,
is_connected,
ALL_SMILES_DICT,
)
from maxsm... | maxsmi/full_workflow_optimal.py | import argparse
import logging
import logging.handlers
import warnings
import os
from datetime import datetime
import itertools
import torch
import torch.nn as nn
from maxsmi.utils_data import data_retrieval
from maxsmi.utils_smiles import (
smiles_to_canonical,
is_connected,
ALL_SMILES_DICT,
)
from maxsm... | 0.584864 | 0.238556 |
from unittest import TestCase, main
from t2t.util import combine_alignments, reroot, unzip
from skbio import TreeNode
__author__ = "<NAME>"
__copyright__ = "Copyright 2011, The tax2tree project"
__credits__ = ["<NAME>"]
__license__ = "BSD"
__version__ = "1.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__... | tests/test_util.py |
from unittest import TestCase, main
from t2t.util import combine_alignments, reroot, unzip
from skbio import TreeNode
__author__ = "<NAME>"
__copyright__ = "Copyright 2011, The tax2tree project"
__credits__ = ["<NAME>"]
__license__ = "BSD"
__version__ = "1.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__... | 0.6488 | 0.46041 |
from pynwb import NWBFile
from pynwb.behavior import BehavioralEvents
from nwb_conversion_tools.converter import NWBConverter
from pathlib import Path
from datetime import datetime
from scipy.io import loadmat
import pandas as pd
import numpy as np
import uuid
class Bpod2NWB(NWBConverter):
def __init__(self, nwb... | nwb_conversion_tools/behavior/bpod/bpod.py | from pynwb import NWBFile
from pynwb.behavior import BehavioralEvents
from nwb_conversion_tools.converter import NWBConverter
from pathlib import Path
from datetime import datetime
from scipy.io import loadmat
import pandas as pd
import numpy as np
import uuid
class Bpod2NWB(NWBConverter):
def __init__(self, nwb... | 0.654674 | 0.187616 |
import numpy as np
import scipy.integrate as integrate
from typing import Iterable, List, Tuple
class FourierSeries:
"""Represent 1D fourier series over a particular domain.
Provides interface for functions.
example usage:
x = np.linspace(0, 12)
fs = FourierSeries(x)
series = np.e... | cosmic/fourier_series.py | import numpy as np
import scipy.integrate as integrate
from typing import Iterable, List, Tuple
class FourierSeries:
"""Represent 1D fourier series over a particular domain.
Provides interface for functions.
example usage:
x = np.linspace(0, 12)
fs = FourierSeries(x)
series = np.e... | 0.942295 | 0.879458 |
rule function_humann2:
"""
Runs HUMAnN2 pipeline using general defaults.
Other HUMAnN2 parameters can be specified as a quoted string in
PARAMS: HUMANN2: OTHER.
Going to do just R1 reads for now. Because of how I've split PE vs SE
processing and naming, still will need to make a separate rule ... | Snakefile_staging.py | rule function_humann2:
"""
Runs HUMAnN2 pipeline using general defaults.
Other HUMAnN2 parameters can be specified as a quoted string in
PARAMS: HUMANN2: OTHER.
Going to do just R1 reads for now. Because of how I've split PE vs SE
processing and naming, still will need to make a separate rule ... | 0.52683 | 0.544438 |
import subprocess
import shutil
import sys
import neutron.plugins.ml2.models as ml2_db
from oslo_log import log as logging
if __name__ == '__main__':
sys.path.append(r'/home/xiongjun/work/networking-tn/')
LOG = logging.getLogger(None).logger
# LOG.addHandler(streamlog)
LOG.setLevel(logging.DEBUG)
els... | networking_tn/tnosclient/tnos_driver.py |
import subprocess
import shutil
import sys
import neutron.plugins.ml2.models as ml2_db
from oslo_log import log as logging
if __name__ == '__main__':
sys.path.append(r'/home/xiongjun/work/networking-tn/')
LOG = logging.getLogger(None).logger
# LOG.addHandler(streamlog)
LOG.setLevel(logging.DEBUG)
els... | 0.117724 | 0.050752 |
from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath
from epsilon.extime import Time
from nevow import loaders, rend
from nevow.testutil import renderPage, renderLivePage
from axiom.store import Store
from axiom.dependency import installOn
from xmantissa.people import Person, Ema... | xquotient/test/test_rendering.py | from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath
from epsilon.extime import Time
from nevow import loaders, rend
from nevow.testutil import renderPage, renderLivePage
from axiom.store import Store
from axiom.dependency import installOn
from xmantissa.people import Person, Ema... | 0.59843 | 0.290578 |
import os
import requests
from matroid import error
from matroid.src.helpers import api_call
# https://staging.dev.matroid.com/docs/api/index.html#api-Videos-PostDetectorsDetector_idClassify_video
@api_call(error.InvalidQueryError)
def classify_video(self, detectorId, url=None, file=None, **options):
"""
Classify... | matroid/src/videos.py | import os
import requests
from matroid import error
from matroid.src.helpers import api_call
# https://staging.dev.matroid.com/docs/api/index.html#api-Videos-PostDetectorsDetector_idClassify_video
@api_call(error.InvalidQueryError)
def classify_video(self, detectorId, url=None, file=None, **options):
"""
Classify... | 0.599837 | 0.184363 |
import unittest
import sys
import pynagios
class ReadmeExamples(unittest.TestCase):
def test_example1(self):
# 2a. create the first service
service1 = pynagios.Service("Service1")
service1.value = 23
service1.max_level = 100
service1.warn_level = 85
service1.cr... | unittests.py |
import unittest
import sys
import pynagios
class ReadmeExamples(unittest.TestCase):
def test_example1(self):
# 2a. create the first service
service1 = pynagios.Service("Service1")
service1.value = 23
service1.max_level = 100
service1.warn_level = 85
service1.cr... | 0.325842 | 0.514583 |
import torch
import numpy as np
import math
import random
import numbers
import random
from itertools import repeat
import warnings
class Center(object):
r"""Centers node positions around the origin."""
def __init__(self, attr):
self.attr = attr
def __call__(self, data):
for key in self.... | utils/transform.py | import torch
import numpy as np
import math
import random
import numbers
import random
from itertools import repeat
import warnings
class Center(object):
r"""Centers node positions around the origin."""
def __init__(self, attr):
self.attr = attr
def __call__(self, data):
for key in self.... | 0.909624 | 0.522933 |
import understand
import json
import os
import argparse
def extract_understand_entities(db_path, result_path):
# db = understand.open("/root/project_example/coreutils/project.udb.und")
db = understand.open(db_path)
file_contains_entity = {}
for entity in db.ents("file"):
entity_relname = enti... | ground_truth_building/extract_source_information/use_understand_to_extract_entity.py | import understand
import json
import os
import argparse
def extract_understand_entities(db_path, result_path):
# db = understand.open("/root/project_example/coreutils/project.udb.und")
db = understand.open(db_path)
file_contains_entity = {}
for entity in db.ents("file"):
entity_relname = enti... | 0.113543 | 0.124639 |
# third party
from django.test import TestCase
from django.core.exceptions import ValidationError
from testfixtures import LogCapture
# local
from aggregator.reservoirs.models import Reservoir
from target.followees.models import Followee, LegalName, Account, Alias
from tests.fixture_manager import get_fixtures
class... | Incident-Response/Tools/cyphon/cyphon/target/followees/tests/test_models.py | # third party
from django.test import TestCase
from django.core.exceptions import ValidationError
from testfixtures import LogCapture
# local
from aggregator.reservoirs.models import Reservoir
from target.followees.models import Followee, LegalName, Account, Alias
from tests.fixture_manager import get_fixtures
class... | 0.603698 | 0.2505 |
import logging
from contextlib import contextmanager
from functools import lru_cache
from multiprocessing.connection import Client
from os import environ
from threading import RLock
from typing import Sequence
from .server import RTN_SERVER_LOGGER_NAME
__all__ = ['TextNormalizerProxy', 'rtn_ctx', 'get_rtn']
_RTN_PO... | src/text_normalizer/api/ipc/client.py |
import logging
from contextlib import contextmanager
from functools import lru_cache
from multiprocessing.connection import Client
from os import environ
from threading import RLock
from typing import Sequence
from .server import RTN_SERVER_LOGGER_NAME
__all__ = ['TextNormalizerProxy', 'rtn_ctx', 'get_rtn']
_RTN_PO... | 0.567218 | 0.074838 |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.db import models
from mock import patch
from sentry.models import (
AuditLogEntry, AuditLogEntryEvent, AuthIdentity, AuthProvider,
Organization, OrganizationMember, TotpInterface
)
from sentry.testutils import Auth... | tests/sentry/web/frontend/test_organization_auth_settings.py | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.db import models
from mock import patch
from sentry.models import (
AuditLogEntry, AuditLogEntryEvent, AuthIdentity, AuthProvider,
Organization, OrganizationMember, TotpInterface
)
from sentry.testutils import Auth... | 0.533884 | 0.177116 |
import argparse
import sys
from typing import List
# Based on code at
# http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console
def print_progress(iteration: int, total: int, prefix: str='', suffix: str='',
decimals: int=2, bar_length: int=68) -> None:
"""Print progress ba... | homeassistant/scripts/influxdb_migrator.py |
import argparse
import sys
from typing import List
# Based on code at
# http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console
def print_progress(iteration: int, total: int, prefix: str='', suffix: str='',
decimals: int=2, bar_length: int=68) -> None:
"""Print progress ba... | 0.521471 | 0.185191 |
import numpy as np
def rotate(im):
'''Rotate an image by 90 degrees clockwise.
This version crates a new image and copies pixels from the input.
Arguments:
im (2D array):
The image being rotated.
Returns:
A new 2D array which is like ``im`` but rotated.
'''
# Cre... | 2018-10-29/image_rotation.py | import numpy as np
def rotate(im):
'''Rotate an image by 90 degrees clockwise.
This version crates a new image and copies pixels from the input.
Arguments:
im (2D array):
The image being rotated.
Returns:
A new 2D array which is like ``im`` but rotated.
'''
# Cre... | 0.937854 | 0.840259 |
import discord
import time
import asyncio
import pickle
import random
import re
VOTE_TIMEOUT = 2
SIMP_BASETIME = 7.5
VOTE_TIME = 30
reserved = ['simpintro','simp','unsimp','unsimpall']
class BotClient( discord.Client ):
blacklist = {}
simped = {}
simptime = []
inprogress = 0
def __init__(self, ):
... | botClient.py | import discord
import time
import asyncio
import pickle
import random
import re
VOTE_TIMEOUT = 2
SIMP_BASETIME = 7.5
VOTE_TIME = 30
reserved = ['simpintro','simp','unsimp','unsimpall']
class BotClient( discord.Client ):
blacklist = {}
simped = {}
simptime = []
inprogress = 0
def __init__(self, ):
... | 0.110231 | 0.105165 |
from http import HTTPStatus
from fastapi import Query
from fastapi.params import Depends
from starlette.exceptions import HTTPException
from lnbits.core import update_user_extension
from lnbits.core.crud import get_user
from lnbits.decorators import WalletTypeInfo, get_key_type
from . import discordbot_ext
from .cru... | lnbits/extensions/discordbot/views_api.py | from http import HTTPStatus
from fastapi import Query
from fastapi.params import Depends
from starlette.exceptions import HTTPException
from lnbits.core import update_user_extension
from lnbits.core.crud import get_user
from lnbits.decorators import WalletTypeInfo, get_key_type
from . import discordbot_ext
from .cru... | 0.411702 | 0.127462 |
import json
import re
from datetime import timedelta
import logging
from datetime import datetime
#gran valaue map,supported grain by hive db engine
GRAIN_VALUE_MAP = {
'PT1S' : 1,
'PT1M' : 60,
'PT1H' : 3600,
'P1D' : 86400,
'P1W' : 604800, # 7 days
'P1M' : 2592000, # 30 days
'P3M' : ... | superset/hive_query.py |
import json
import re
from datetime import timedelta
import logging
from datetime import datetime
#gran valaue map,supported grain by hive db engine
GRAIN_VALUE_MAP = {
'PT1S' : 1,
'PT1M' : 60,
'PT1H' : 3600,
'P1D' : 86400,
'P1W' : 604800, # 7 days
'P1M' : 2592000, # 30 days
'P3M' : ... | 0.246171 | 0.170301 |
import os
import time
import argparse
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
from datasets import process_query_sysu, process_gallery_sy... | test.py | import os
import time
import argparse
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
from datasets import process_query_sysu, process_gallery_sy... | 0.235021 | 0.130313 |
import requests
from bs4 import BeautifulSoup
import lxml
from multiprocessing import Process, Queue
import random
import json
import time
import requests
class Proxies(object):
"""docstring for Proxies"""
def __init__(self, page=3):
self.proxies = []
self.verify_pro = []
self.page... | beauty/spiders/proxes.py | import requests
from bs4 import BeautifulSoup
import lxml
from multiprocessing import Process, Queue
import random
import json
import time
import requests
class Proxies(object):
"""docstring for Proxies"""
def __init__(self, page=3):
self.proxies = []
self.verify_pro = []
self.page... | 0.144028 | 0.048631 |
from abc import ABCMeta
from enum import Enum
import pickle
import os
import jsonpickle
import luigi.target
class Serialization(Enum):
"""
These are the supported serialization methods.
"""
JSON = 'json'
BINARY = 'binary'
def touch(local_target: luigi.LocalTarget):
"""
You can use this f... | luijo/targets.py | from abc import ABCMeta
from enum import Enum
import pickle
import os
import jsonpickle
import luigi.target
class Serialization(Enum):
"""
These are the supported serialization methods.
"""
JSON = 'json'
BINARY = 'binary'
def touch(local_target: luigi.LocalTarget):
"""
You can use this f... | 0.72662 | 0.154121 |
import unittest
from nose.plugins.attrib import attr
from jnpr.healthbot import HealthBotClient
from jnpr.healthbot import PlaybookSchema
from jnpr.healthbot import PlayBookInstanceBuilder
from mock import patch
from requests.models import Response
from . import _mock_user_login
@attr('unit')
class TestPlaybooks(unit... | tests/unit/modules/test_playbook.py | import unittest
from nose.plugins.attrib import attr
from jnpr.healthbot import HealthBotClient
from jnpr.healthbot import PlaybookSchema
from jnpr.healthbot import PlayBookInstanceBuilder
from mock import patch
from requests.models import Response
from . import _mock_user_login
@attr('unit')
class TestPlaybooks(unit... | 0.506347 | 0.253745 |
def part1(numbers):
device = numbers[-1] + 3
diff_1_jolt = 0
diff_2_jolt = 0
diff_3_jolt = 0
current_joltage = 0
index = 0
while current_joltage < device:
for i in range(index, len(numbers)):
diff = numbers[i] - current_joltage
if diff == 1:
c... | 2020/day10/day10.py | def part1(numbers):
device = numbers[-1] + 3
diff_1_jolt = 0
diff_2_jolt = 0
diff_3_jolt = 0
current_joltage = 0
index = 0
while current_joltage < device:
for i in range(index, len(numbers)):
diff = numbers[i] - current_joltage
if diff == 1:
c... | 0.161618 | 0.553988 |
from Cryptodome.Signature.pss import MGF1
import Cryptodome.Hash.SHA1
from Cryptodome.Util.py3compat import bord, _copy_bytes
import Cryptodome.Util.number
from Cryptodome.Util.number import ceil_div, bytes_to_long, long_to_bytes
from Cryptodome.Util.strxor import strxor
from Cryptodome import Random
class PKCS1... | system/Python/Lib/site-packages/Cryptodome/Cipher/PKCS1_OAEP.py |
from Cryptodome.Signature.pss import MGF1
import Cryptodome.Hash.SHA1
from Cryptodome.Util.py3compat import bord, _copy_bytes
import Cryptodome.Util.number
from Cryptodome.Util.number import ceil_div, bytes_to_long, long_to_bytes
from Cryptodome.Util.strxor import strxor
from Cryptodome import Random
class PKCS1... | 0.880759 | 0.352174 |
__author__ = '<NAME>'
__date__ = '2021-02-18'
__copyright__ = '(C) 2021 by <NAME>'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from qgis.core import QgsProcessingProvider
from qgis.PyQt.QtGui import QIcon
from lftools.processing_provider.Cart_inom2utm imp... | lftools_provider.py | __author__ = '<NAME>'
__date__ = '2021-02-18'
__copyright__ = '(C) 2021 by <NAME>'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from qgis.core import QgsProcessingProvider
from qgis.PyQt.QtGui import QIcon
from lftools.processing_provider.Cart_inom2utm imp... | 0.589835 | 0.223801 |
import os
import pathlib
import pty
import subprocess
from typing import Optional, Tuple
import algosdk.account
import algosdk.future.transaction
import algosdk.mnemonic
from algosdk.v2client.algod import AlgodClient
import algodao.helpers
def _cli_passphrase_for_account(address: str) -> str:
"""Return passphra... | tests/helpers.py | import os
import pathlib
import pty
import subprocess
from typing import Optional, Tuple
import algosdk.account
import algosdk.future.transaction
import algosdk.mnemonic
from algosdk.v2client.algod import AlgodClient
import algodao.helpers
def _cli_passphrase_for_account(address: str) -> str:
"""Return passphra... | 0.774498 | 0.148294 |
import os
import unittest
from copy import deepcopy
from tempfile import mkdtemp
import os.path
from text_recognition.utils.exporter import Exporter
from text_recognition.utils.evaluator import Evaluator, RunnerType
from text_recognition.utils.get_config import get_config
from text_recognition.utils.common import down... | misc/pytorch_toolkit/text_recognition/tests/test_export.py | import os
import unittest
from copy import deepcopy
from tempfile import mkdtemp
import os.path
from text_recognition.utils.exporter import Exporter
from text_recognition.utils.evaluator import Evaluator, RunnerType
from text_recognition.utils.get_config import get_config
from text_recognition.utils.common import down... | 0.460289 | 0.207455 |
import os
import cv2
import numpy as np
from PIL import Image
import torch
from facenet_pytorch import MTCNN
from .constants import *
class Cropper:
def __init__(self, device='cpu'):
self.DEVICE = torch.device(device)
self.MTCNN_MODEL = MTCNN(keep_all=False, device=self.DEVICE)
'''
... | cropimage/cropper.py | import os
import cv2
import numpy as np
from PIL import Image
import torch
from facenet_pytorch import MTCNN
from .constants import *
class Cropper:
def __init__(self, device='cpu'):
self.DEVICE = torch.device(device)
self.MTCNN_MODEL = MTCNN(keep_all=False, device=self.DEVICE)
'''
... | 0.459804 | 0.276697 |
import gym
import numpy as np
from garage.envs.step import Step
class PointEnv(gym.Env):
"""A simple 2D point environment.
Attributes:
observation_space (gym.spaces.Box): The observation space
action_space (gym.spaces.Box): The action space
Args:
goal (np.ndarray):... | src/garage/envs/point_env.py | import gym
import numpy as np
from garage.envs.step import Step
class PointEnv(gym.Env):
"""A simple 2D point environment.
Attributes:
observation_space (gym.spaces.Box): The observation space
action_space (gym.spaces.Box): The action space
Args:
goal (np.ndarray):... | 0.90215 | 0.703941 |
# pylint: disable=wrong-import-order
from ._util_enterprise import (is_enterprise_tier, get_client)
from ._enterprise import (app_get_enterprise, app_list_enterprise, app_create_enterprise,
app_update_enterprise, app_scale_enterprise, app_deploy_enterprise,
app_star... | src/spring-cloud/azext_spring_cloud/tier_routing_app.py |
# pylint: disable=wrong-import-order
from ._util_enterprise import (is_enterprise_tier, get_client)
from ._enterprise import (app_get_enterprise, app_list_enterprise, app_create_enterprise,
app_update_enterprise, app_scale_enterprise, app_deploy_enterprise,
app_star... | 0.32306 | 0.04982 |
import struct
import hid_constants
import usb_constants
class Field(object):
"""USB descriptor field information."""
def __init__(self, name, str_fmt, struct_fmt, required):
"""Define a new USB descriptor field.
Args:
name: Name of the field.
str_fmt: Python 'string' module format string fo... | tools/usb_gadget/usb_descriptors.py | import struct
import hid_constants
import usb_constants
class Field(object):
"""USB descriptor field information."""
def __init__(self, name, str_fmt, struct_fmt, required):
"""Define a new USB descriptor field.
Args:
name: Name of the field.
str_fmt: Python 'string' module format string fo... | 0.813275 | 0.331769 |
import ctypes
LONG = ctypes.c_long
DWORD = ctypes.c_ulong
ULONG_PTR = ctypes.POINTER(DWORD)
WORD = ctypes.c_ushort
class MOUSEINPUT(ctypes.Structure):
_fields_ = (('dx', LONG),
('dy', LONG),
('mouseData', DWORD),
('dwFlags', DWORD),
('time', DWORD),
... | input.py | import ctypes
LONG = ctypes.c_long
DWORD = ctypes.c_ulong
ULONG_PTR = ctypes.POINTER(DWORD)
WORD = ctypes.c_ushort
class MOUSEINPUT(ctypes.Structure):
_fields_ = (('dx', LONG),
('dy', LONG),
('mouseData', DWORD),
('dwFlags', DWORD),
('time', DWORD),
... | 0.271155 | 0.146911 |
from __future__ import print_function
import sys
import itertools
import pddl
import timers
from functools import reduce
def convert_rules(prog):
RULE_TYPES = {
"join": JoinRule,
"product": ProductRule,
"project": ProjectRule,
}
result = []
for rule in prog.rules:
... | build_model.py |
from __future__ import print_function
import sys
import itertools
import pddl
import timers
from functools import reduce
def convert_rules(prog):
RULE_TYPES = {
"join": JoinRule,
"product": ProductRule,
"project": ProjectRule,
}
result = []
for rule in prog.rules:
... | 0.438304 | 0.290176 |
import time
from mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData
from mitmproxy.proxy.events import ConnectionClosed, DataReceived
from mitmproxy.proxy.layers import dns
from mitmproxy.dns import DNSFlow
from mitmproxy.test.tutils import tdnsreq, tdnsresp
from ..tutils import Placeholder... | test/mitmproxy/proxy/layers/test_dns.py | import time
from mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData
from mitmproxy.proxy.events import ConnectionClosed, DataReceived
from mitmproxy.proxy.layers import dns
from mitmproxy.dns import DNSFlow
from mitmproxy.test.tutils import tdnsreq, tdnsresp
from ..tutils import Placeholder... | 0.468547 | 0.525308 |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import merge_dicts
class MallTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:(?:www|sk)\.)?mall\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
_TESTS = [{
'url': 'https://www.mall.tv/18-miliard-pro-neziskovky-opravdu-... | youtube_dl/extractor/malltv.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import merge_dicts
class MallTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:(?:www|sk)\.)?mall\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
_TESTS = [{
'url': 'https://www.mall.tv/18-miliard-pro-neziskovky-opravdu-... | 0.40251 | 0.115511 |
from defoe import query_utils
from defoe.fmp.query_utils import segment_image
import yaml
import os
from collections import namedtuple, defaultdict
WordLocation = namedtuple('WordLocation',
("word "
"position "
"year "
"document "
... | defoe/fmp/queries/weighted_target_segmentation.py | from defoe import query_utils
from defoe.fmp.query_utils import segment_image
import yaml
import os
from collections import namedtuple, defaultdict
WordLocation = namedtuple('WordLocation',
("word "
"position "
"year "
"document "
... | 0.625781 | 0.222795 |
import pprint
import re # noqa: F401
import six
class V1FilesystemLayoutCreateRequest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | metal_python/models/v1_filesystem_layout_create_request.py | import pprint
import re # noqa: F401
import six
class V1FilesystemLayoutCreateRequest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | 0.718792 | 0.088781 |
import os
from functools import partial
import numpy as np
import nvidia.dali as dali
import nvidia.dali.ops as ops
import nvidia.dali.types as types
import test_utils
from nvidia.dali.pipeline import Pipeline
import gc
video_directory = '/tmp/labelled_videos/'
video_directory_multiple_resolutions = '/tmp/video_res... | dali/test/python/test_video_reader_resize.py |
import os
from functools import partial
import numpy as np
import nvidia.dali as dali
import nvidia.dali.ops as ops
import nvidia.dali.types as types
import test_utils
from nvidia.dali.pipeline import Pipeline
import gc
video_directory = '/tmp/labelled_videos/'
video_directory_multiple_resolutions = '/tmp/video_res... | 0.521715 | 0.231115 |
import multiprocessing as mp
import random
import sys
import time
from gevent import monkey as curious_george
curious_george.patch_all(thread=False, select=False)
import gevent
import marktime
from zaqarclient.transport import errors
from zaqar.bench import config
from zaqar.bench import helpers
CONF = config.conf
... | zaqar/bench/consumer.py |
import multiprocessing as mp
import random
import sys
import time
from gevent import monkey as curious_george
curious_george.patch_all(thread=False, select=False)
import gevent
import marktime
from zaqarclient.transport import errors
from zaqar.bench import config
from zaqar.bench import helpers
CONF = config.conf
... | 0.267791 | 0.117471 |
import json
import os
import random
import string
from pathlib import Path
from eth_typing import ChecksumAddress
from eth_utils import to_checksum_address
PATH_CONFIG = Path("/opt/synapse/config/synapse.yaml")
PATH_CONFIG_TEMPLATE = Path("/opt/synapse/config/synapse.template.yaml")
PATH_MACAROON_KEY = Path("/opt/syna... | e2e-environment/synapse/exec/render_config_template.py | import json
import os
import random
import string
from pathlib import Path
from eth_typing import ChecksumAddress
from eth_utils import to_checksum_address
PATH_CONFIG = Path("/opt/synapse/config/synapse.yaml")
PATH_CONFIG_TEMPLATE = Path("/opt/synapse/config/synapse.template.yaml")
PATH_MACAROON_KEY = Path("/opt/syna... | 0.453988 | 0.051942 |
from itertools import chain
import dash_html_components as html
from dash.development._py_components_generation import (
filter_props,
js_to_py_type,
parse_events,
reorder_props,
)
def ApiDoc(component_metadata, component_name=None):
component_props = component_metadata.get("props", {})
retur... | docs/components_page/api_doc.py | from itertools import chain
import dash_html_components as html
from dash.development._py_components_generation import (
filter_props,
js_to_py_type,
parse_events,
reorder_props,
)
def ApiDoc(component_metadata, component_name=None):
component_props = component_metadata.get("props", {})
retur... | 0.419053 | 0.122707 |
import sys
import os
from flask import Flask
from flask.ext.cache import Cache
app = Flask(__name__)
# Load configuration defaults
app.config.from_object("pegasus.service.defaults")
# Load user configuration
conf = os.path.expanduser("~/.pegasus/service.py")
if os.path.isfile(conf):
app.config.from_pyfile(conf)
... | pegasus/service/__init__.py | import sys
import os
from flask import Flask
from flask.ext.cache import Cache
app = Flask(__name__)
# Load configuration defaults
app.config.from_object("pegasus.service.defaults")
# Load user configuration
conf = os.path.expanduser("~/.pegasus/service.py")
if os.path.isfile(conf):
app.config.from_pyfile(conf)
... | 0.419172 | 0.040276 |
import unittest
from resync.url_authority import UrlAuthority
class TestUrlAuthority(unittest.TestCase):
def test01_strict_authority(self):
"""Default is server check only."""
uauth = UrlAuthority('http://example.org/sitemap.xml', True)
self.assertTrue(uauth.has_authority_over(
... | tests/test_url_authority.py | import unittest
from resync.url_authority import UrlAuthority
class TestUrlAuthority(unittest.TestCase):
def test01_strict_authority(self):
"""Default is server check only."""
uauth = UrlAuthority('http://example.org/sitemap.xml', True)
self.assertTrue(uauth.has_authority_over(
... | 0.611266 | 0.686055 |
from pyomo.environ import *
dependencies = 'switch_model.timescales', 'switch_model.balancing.load_zones',\
'switch_model.financials', 'switch_model.transmission.transport.build'
def define_components(mod):
"""
Adds components to a Pyomo abstract model object to describe the
dispatch of transmission ... | switch_model/transmission/transport/dispatch.py | from pyomo.environ import *
dependencies = 'switch_model.timescales', 'switch_model.balancing.load_zones',\
'switch_model.financials', 'switch_model.transmission.transport.build'
def define_components(mod):
"""
Adds components to a Pyomo abstract model object to describe the
dispatch of transmission ... | 0.760473 | 0.628493 |
import base64
import logging
import os
import socket
import threading
import time
from i2p.util import receive_line, pub_from_priv
import shared
class I2PController(threading.Thread):
def __init__(self, host='127.0.0.1', port=7656, dest_priv=b''):
super().__init__(name='I2P Controller')
self.hos... | minode/i2p/controller.py | import base64
import logging
import os
import socket
import threading
import time
from i2p.util import receive_line, pub_from_priv
import shared
class I2PController(threading.Thread):
def __init__(self, host='127.0.0.1', port=7656, dest_priv=b''):
super().__init__(name='I2P Controller')
self.hos... | 0.142202 | 0.06276 |
import concurrent.futures
class Executor:
"""Asynchronous bounded executor.
Used to process entries asynchronously in threads (or processes), then
pass the results back to the main thread.
This class is just a thin wrapper around the PoolExecutor classes from the
built-in concurrent.futures libr... | bounded_async_executor/executor.py | import concurrent.futures
class Executor:
"""Asynchronous bounded executor.
Used to process entries asynchronously in threads (or processes), then
pass the results back to the main thread.
This class is just a thin wrapper around the PoolExecutor classes from the
built-in concurrent.futures libr... | 0.781831 | 0.368292 |
# This script shows you how to export ppq internal graph to tensorRT
# ---------------------------------------------------------------
# For this inference test, all test data is randomly picked.
# If you want to use real data, just rewrite the defination of SAMPLES
import onnxruntime
import torch
from ppq import *
f... | ppq/samples/TensorRT/Example_PTQ.py |
# This script shows you how to export ppq internal graph to tensorRT
# ---------------------------------------------------------------
# For this inference test, all test data is randomly picked.
# If you want to use real data, just rewrite the defination of SAMPLES
import onnxruntime
import torch
from ppq import *
f... | 0.373419 | 0.32005 |
import json
import random
import time
from collections import OrderedDict
from urllib.parse import unquote, urlencode
import requests
from bs4 import BeautifulSoup
from requests.packages import urllib3
from config import _PROXIES_DIC, TIMEOUT
from database import DBSession, Saved
# 禁用安全请求警告
urllib3.disable_warnings... | check_init.py |
import json
import random
import time
from collections import OrderedDict
from urllib.parse import unquote, urlencode
import requests
from bs4 import BeautifulSoup
from requests.packages import urllib3
from config import _PROXIES_DIC, TIMEOUT
from database import DBSession, Saved
# 禁用安全请求警告
urllib3.disable_warnings... | 0.344664 | 0.087916 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, args):
super(Attention, self).__init__()
self.hidden_size = args.hidden_size
self.W=nn.Linear(self.hidden_size,self.hidden_size*2)
self.attention_wight=nn.Linear(self... | model/attention.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, args):
super(Attention, self).__init__()
self.hidden_size = args.hidden_size
self.W=nn.Linear(self.hidden_size,self.hidden_size*2)
self.attention_wight=nn.Linear(self... | 0.890437 | 0.296769 |
import os
import argparse
import logging
from tqdm import tqdm
from typing import Callable, Tuple
from PIL import Image
from functools import partial
import torch
import torch.nn.functional as F
from torch.optim import SGD
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import DataLoader
from torch... | train.py | import os
import argparse
import logging
from tqdm import tqdm
from typing import Callable, Tuple
from PIL import Image
from functools import partial
import torch
import torch.nn.functional as F
from torch.optim import SGD
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import DataLoader
from torch... | 0.947345 | 0.504578 |
import sys
import time
from Utils.log import Logger
from Utils.DriverWait import Wait_Find
from Utils.ScreenShot import Screenshot
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
send_time = time.str... | Utils/Login_User.py | import sys
import time
from Utils.log import Logger
from Utils.DriverWait import Wait_Find
from Utils.ScreenShot import Screenshot
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
send_time = time.str... | 0.069751 | 0.04952 |
from pypy.interpreter.mixedmodule import MixedModule
class PyPyModule(MixedModule):
interpleveldefs = {
'debug_repr': 'interp_extras.debug_repr',
'remove_invalidates': 'interp_extras.remove_invalidates',
'set_invalidation': 'interp_extras.set_invalidation',
}
appleveldefs = {}
cla... | pypy/module/micronumpy/__init__.py | from pypy.interpreter.mixedmodule import MixedModule
class PyPyModule(MixedModule):
interpleveldefs = {
'debug_repr': 'interp_extras.debug_repr',
'remove_invalidates': 'interp_extras.remove_invalidates',
'set_invalidation': 'interp_extras.set_invalidation',
}
appleveldefs = {}
cla... | 0.639849 | 0.230302 |
import re
from random import randint, choice
from ..config import dp, _
from ..lib import handlers
#REWRITE: use regular
@dp.message_handler(lambda msg: msg.text.lower().find("бот, сколько") != -1 and
msg.text.lower().find("?") != -1)
@handlers.check("__enable_response__")
async de... | bot/triggers/ban.py | import re
from random import randint, choice
from ..config import dp, _
from ..lib import handlers
#REWRITE: use regular
@dp.message_handler(lambda msg: msg.text.lower().find("бот, сколько") != -1 and
msg.text.lower().find("?") != -1)
@handlers.check("__enable_response__")
async de... | 0.159512 | 0.08163 |
import PIL.Image as Image
from PIL import ImageChops
import os
import re
from glob import glob
REQ_SIZE = (48, 48)
def getbbox(im, threshold):
'''like Image.getbbox(), but instead of cropping everything that is exactly 0,
crops everything with the alpha channel below @threshold'''
a = im.split()[-1]
... | geocamUtil/icons/rotate.py |
import PIL.Image as Image
from PIL import ImageChops
import os
import re
from glob import glob
REQ_SIZE = (48, 48)
def getbbox(im, threshold):
'''like Image.getbbox(), but instead of cropping everything that is exactly 0,
crops everything with the alpha channel below @threshold'''
a = im.split()[-1]
... | 0.577972 | 0.324837 |
from __future__ import print_function, unicode_literals
import json
import os
from contextlib import contextmanager
from ..constants import ROOT
@contextmanager
def chdir(d, cwd=None):
origin = cwd or os.getcwd()
os.chdir(d)
try:
yield
finally:
os.chdir(origin)
def get_version_fil... | tasks/utils/common.py | from __future__ import print_function, unicode_literals
import json
import os
from contextlib import contextmanager
from ..constants import ROOT
@contextmanager
def chdir(d, cwd=None):
origin = cwd or os.getcwd()
os.chdir(d)
try:
yield
finally:
os.chdir(origin)
def get_version_fil... | 0.407923 | 0.112016 |
import numpy as np
import pandas as pd
import csv
import seaborn as sns
import sys
import matplotlib.pyplot as plt
from collections import OrderedDict
from argparse import ArgumentParser
import pathlib
import math
import copy
def main():
args = get_args()
sns.set(style='white',)
palette=sns.color_palette('... | test/figures/read_mapping/accuracy-ont-blend/accuracy_dist.py | import numpy as np
import pandas as pd
import csv
import seaborn as sns
import sys
import matplotlib.pyplot as plt
from collections import OrderedDict
from argparse import ArgumentParser
import pathlib
import math
import copy
def main():
args = get_args()
sns.set(style='white',)
palette=sns.color_palette('... | 0.328853 | 0.204084 |
import datetime
from importlib import reload
import json
from unittest import mock
from django.conf import settings
from django.test.testcases import SimpleTestCase
import responses
from mtp_common.auth import api_client, urljoin
from mtp_common.auth.exceptions import Unauthorized
from mtp_common.auth.test_utils impo... | tests/test_api_client.py | import datetime
from importlib import reload
import json
from unittest import mock
from django.conf import settings
from django.test.testcases import SimpleTestCase
import responses
from mtp_common.auth import api_client, urljoin
from mtp_common.auth.exceptions import Unauthorized
from mtp_common.auth.test_utils impo... | 0.569494 | 0.298901 |
from django.urls import reverse
from rest_framework.status import (
HTTP_200_OK,
HTTP_201_CREATED,
)
from rest_framework.test import APITestCase
from rest_api.tests.main import (
create_authors_articles,
USERNAME,
PASSWORD,
)
class TestIntegration(APITestCase):
"""
Integration test for au... | rest_api/tests/test_end_to_end.py | from django.urls import reverse
from rest_framework.status import (
HTTP_200_OK,
HTTP_201_CREATED,
)
from rest_framework.test import APITestCase
from rest_api.tests.main import (
create_authors_articles,
USERNAME,
PASSWORD,
)
class TestIntegration(APITestCase):
"""
Integration test for au... | 0.509032 | 0.169063 |
import pickle
import operator
import numpy as np
import preprocessing as pp
global char_n_grams_index, word_n_grams_index, truth_top_hashtags, truth_top_hi_tokens, truth_top_en_tokens, truth_top_rest_tokens
# Add features derived from emoticons.
def addemoticonfeatures(feature_vector, emoticons):
feature_vector.appe... | data/raw/SarcasmDetection_CodeMixed/Classification_system/build_feature_vector.py |
import pickle
import operator
import numpy as np
import preprocessing as pp
global char_n_grams_index, word_n_grams_index, truth_top_hashtags, truth_top_hi_tokens, truth_top_en_tokens, truth_top_rest_tokens
# Add features derived from emoticons.
def addemoticonfeatures(feature_vector, emoticons):
feature_vector.appe... | 0.266548 | 0.161485 |
# shell script to check if nova API DB migrations finished after X attempts.
# Default max is 60 iterations with 10s (default) timeout in between.
from __future__ import print_function
import logging
import os
import re
import sys
import time
from keystoneauth1.identity import v3
from keystoneauth1 import session
f... | container_config_scripts/nova_wait_for_placement_service.py |
# shell script to check if nova API DB migrations finished after X attempts.
# Default max is 60 iterations with 10s (default) timeout in between.
from __future__ import print_function
import logging
import os
import re
import sys
import time
from keystoneauth1.identity import v3
from keystoneauth1 import session
f... | 0.297572 | 0.07836 |
from os import environ
from pathlib import Path
from typing import List
from colorama import Fore, Style
from superai.data_program.hatchery.utils import (
build_path,
create_agent_run_command,
execute_verbose,
get_binaries,
init_build_path,
)
from superai.log import logger
from superai.utils impor... | superai/data_program/hatchery/hatchery.py | from os import environ
from pathlib import Path
from typing import List
from colorama import Fore, Style
from superai.data_program.hatchery.utils import (
build_path,
create_agent_run_command,
execute_verbose,
get_binaries,
init_build_path,
)
from superai.log import logger
from superai.utils impor... | 0.705886 | 0.143998 |
"""A trainer object that can train models with a single output."""
from keras import backend as K
from absl import logging
from third_party.tf_models import orbit
import tensorflow as tf
from keras.utils.vis_utils import plot_model
class IdentityMetric(tf.keras.metrics.Metric):
"""Keras metric to report value at any... | mint/ctl/single_task_trainer.py | """A trainer object that can train models with a single output."""
from keras import backend as K
from absl import logging
from third_party.tf_models import orbit
import tensorflow as tf
from keras.utils.vis_utils import plot_model
class IdentityMetric(tf.keras.metrics.Metric):
"""Keras metric to report value at any... | 0.97338 | 0.657621 |
import os.path
import json
import re
import numpy as np
from nltk import word_tokenize
from .audio_tools import Sound
def _path(relpath):
"""
Returns an absolute path for the given path (which is relative to the root directory ml_subtitle_align)
"""
parent = os.path.join(os.path.dirname(__file__), "..")
return os... | preprocessing/subtitle.py | import os.path
import json
import re
import numpy as np
from nltk import word_tokenize
from .audio_tools import Sound
def _path(relpath):
"""
Returns an absolute path for the given path (which is relative to the root directory ml_subtitle_align)
"""
parent = os.path.join(os.path.dirname(__file__), "..")
return os... | 0.31732 | 0.317109 |
import logging, datetime
from pprint import pprint
from diana.utils.guid import GUIDMint
def test_guid_genders():
M = GUIDMint()
expected = {
'ID': 'WHLOKMAGICLQGYKC3ZQLLMFKMOX3ZAP2',
'Name': ['WAGENAAR', 'HERIBERTO', 'L'],
'BirthDate': datetime.date(1999, 10, 8),
'TimeOffset'... | tests/diana-tests/utils/guidmint_test.py | import logging, datetime
from pprint import pprint
from diana.utils.guid import GUIDMint
def test_guid_genders():
M = GUIDMint()
expected = {
'ID': 'WHLOKMAGICLQGYKC3ZQLLMFKMOX3ZAP2',
'Name': ['WAGENAAR', 'HERIBERTO', 'L'],
'BirthDate': datetime.date(1999, 10, 8),
'TimeOffset'... | 0.577972 | 0.566438 |
import copy
import numpy as np
import numexpr as ne
from ..field import Field, field_dot, field_kron
_U_matrix = 1 / np.sqrt(2) * np.array([
[1, 0, 0, 1],
[1, 0, 0, -1],
[0, 1, 1, 0],
[0, 1j, -1j, 0]])
# TODO Should add a pilot Gaussian beam with each Wavefront
class Wavefront(object):
'''A physical wavefront ... | hcipy/optics/wavefront.py | import copy
import numpy as np
import numexpr as ne
from ..field import Field, field_dot, field_kron
_U_matrix = 1 / np.sqrt(2) * np.array([
[1, 0, 0, 1],
[1, 0, 0, -1],
[0, 1, 1, 0],
[0, 1j, -1j, 0]])
# TODO Should add a pilot Gaussian beam with each Wavefront
class Wavefront(object):
'''A physical wavefront ... | 0.54819 | 0.650828 |
import pytest
from django.apps import apps
from awx.main.migrations import _rbac as rbac
from awx.main.models import (
UnifiedJobTemplate,
InventorySource, Inventory,
JobTemplate, Project,
Organization,
User
)
@pytest.mark.django_db
def test_implied_organization_subquery_inventory():
orgs = ... | awx/main/tests/functional/test_rbac_migration.py | import pytest
from django.apps import apps
from awx.main.migrations import _rbac as rbac
from awx.main.models import (
UnifiedJobTemplate,
InventorySource, Inventory,
JobTemplate, Project,
Organization,
User
)
@pytest.mark.django_db
def test_implied_organization_subquery_inventory():
orgs = ... | 0.345657 | 0.193452 |
import json
import os
import random
from typing import Any, DefaultDict, Dict, Generator, List
import jax.numpy as jnp
import numpy as np
import scipy.io
from jaxtalk.utils import Logger, create_vocabulary
class BasicDataProvider:
"""A data provider for that provides in form of image captions pairs"""
def ... | jaxtalk/data.py | import json
import os
import random
from typing import Any, DefaultDict, Dict, Generator, List
import jax.numpy as jnp
import numpy as np
import scipy.io
from jaxtalk.utils import Logger, create_vocabulary
class BasicDataProvider:
"""A data provider for that provides in form of image captions pairs"""
def ... | 0.664105 | 0.352257 |
print('=' * 50)
print('Seja bem-vindo ao nosso atendimento online!')
print('=' * 50)
def atend():
cpf = input('\nInforme seu CPF para continuar com o atendimento: \n')
confirma_cpf = input('Confirme seu CPF: \n')
if cpf != confirma_cpf:
print('\nConfirmação de CPF inválida, tente de novo.')
... | Atendimendo (chat)/atendimento.py | print('=' * 50)
print('Seja bem-vindo ao nosso atendimento online!')
print('=' * 50)
def atend():
cpf = input('\nInforme seu CPF para continuar com o atendimento: \n')
confirma_cpf = input('Confirme seu CPF: \n')
if cpf != confirma_cpf:
print('\nConfirmação de CPF inválida, tente de novo.')
... | 0.171477 | 0.254632 |
import networkn
class ndexGraphBuilder:
def __init__(self):
self.ndexGraph = networkn.NdexGraph()
self.nodeIdCounter = 0
self.sidTable = {} # external id to nodeIt mapping table
self.edgeIdCounter = 0
def addNamespaces(self, namespaces):
self.ndexGraph.set_namespace(n... | ndex/ndexGraphBuilder.py | import networkn
class ndexGraphBuilder:
def __init__(self):
self.ndexGraph = networkn.NdexGraph()
self.nodeIdCounter = 0
self.sidTable = {} # external id to nodeIt mapping table
self.edgeIdCounter = 0
def addNamespaces(self, namespaces):
self.ndexGraph.set_namespace(n... | 0.45641 | 0.147218 |
import logging # noqa
import mock
from rally.common import logging as rally_logging
from tests.unit import test
class SetUpLogTestCase(test.TestCase):
@mock.patch("rally.common.logging.CONF")
@mock.patch("rally.common.logging.handlers")
@mock.patch("rally.common.logging.oslogging")
def test_setu... | tests/unit/common/test_logging.py |
import logging # noqa
import mock
from rally.common import logging as rally_logging
from tests.unit import test
class SetUpLogTestCase(test.TestCase):
@mock.patch("rally.common.logging.CONF")
@mock.patch("rally.common.logging.handlers")
@mock.patch("rally.common.logging.oslogging")
def test_setu... | 0.603465 | 0.328853 |
import numpy as np
import queue
import copy
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='/Library/Fonts/Songti.ttc')
# 输入参数
total_time = int(input("输入模拟时间 (小时): "))
IAT_rate = int(input("输入顾客到达速率 (/小时): "))
ST_rate = int(input("输入服务器服务速率 (/小时): "))
que... | class/Project1/codes/m:m:1:n.py | import numpy as np
import queue
import copy
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='/Library/Fonts/Songti.ttc')
# 输入参数
total_time = int(input("输入模拟时间 (小时): "))
IAT_rate = int(input("输入顾客到达速率 (/小时): "))
ST_rate = int(input("输入服务器服务速率 (/小时): "))
que... | 0.112356 | 0.194139 |
import random
from random import shuffle
import numpy as np
from datetime import datetime
from typing import Any, List, Tuple
import time
import queue
import threading
import logging
from PIL import Image
import itertools
import re
import os
import glob
import shutil
import sys
import copy
import h5py
import torch
imp... | train/v3/run.py | import random
from random import shuffle
import numpy as np
from datetime import datetime
from typing import Any, List, Tuple
import time
import queue
import threading
import logging
from PIL import Image
import itertools
import re
import os
import glob
import shutil
import sys
import copy
import h5py
import torch
imp... | 0.748352 | 0.208179 |
import random
import operator
import csv
import matplotlib.pyplot
import matplotlib.animation
import agentframework
# This imports a csv file and reads it into an environmnet list in 2D.
environment = []
with open('in.txt', newline='') as f:
dataset = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
for row in dat... | model.py | import random
import operator
import csv
import matplotlib.pyplot
import matplotlib.animation
import agentframework
# This imports a csv file and reads it into an environmnet list in 2D.
environment = []
with open('in.txt', newline='') as f:
dataset = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
for row in dat... | 0.330363 | 0.413181 |
import os
from collections import Counter
import json
from flask import current_app as capp
from flask import request
from functools import wraps
from psqlgraph import Node
import sqlalchemy
from threading import Thread
import simplejson
import yaml
import datamodelutils.models as models
from peregrine.errors import ... | peregrine/resources/submission/util.py | import os
from collections import Counter
import json
from flask import current_app as capp
from flask import request
from functools import wraps
from psqlgraph import Node
import sqlalchemy
from threading import Thread
import simplejson
import yaml
import datamodelutils.models as models
from peregrine.errors import ... | 0.7011 | 0.368832 |
import numpy as np
import os
import random
import scipy.misc
import string
import tempfile
from PIL import Image
class TempFile:
def __init__(self, img=None):
self.path = self.create_unique_name('.png')
if isinstance(img, Image.Image):
img.save(self.path, format='png')
elif isi... | tests/imgs.py | import numpy as np
import os
import random
import scipy.misc
import string
import tempfile
from PIL import Image
class TempFile:
def __init__(self, img=None):
self.path = self.create_unique_name('.png')
if isinstance(img, Image.Image):
img.save(self.path, format='png')
elif isi... | 0.488771 | 0.177882 |
from unittest import TestCase
from random import choice
from drawer import AdviceBuilder, weave_clazz, prelude
from functools import partial
from domain_model import CustomerServiceWorkflow, SpecialistWorkflow, construct_universe, Clock, Troupe
from domain_model import set_skip_log, action_log, generate_XES
from pydyso... | experiment_tests/fuzzing_experiments.py | from unittest import TestCase
from random import choice
from drawer import AdviceBuilder, weave_clazz, prelude
from functools import partial
from domain_model import CustomerServiceWorkflow, SpecialistWorkflow, construct_universe, Clock, Troupe
from domain_model import set_skip_log, action_log, generate_XES
from pydyso... | 0.502197 | 0.311767 |
import h5py
import pandas
from optparse import OptionParser
import scipy as sp
import os
import pdb
import subprocess, sys, os
import limix.io.plink as PLINK
class LIMIX_converter(object):
'''
A class to help with file conversion in LIMIX
'''
__slots__=["options","args","data", "result","infostring","... | src/interfaces/python/limix/io/conversion.py | import h5py
import pandas
from optparse import OptionParser
import scipy as sp
import os
import pdb
import subprocess, sys, os
import limix.io.plink as PLINK
class LIMIX_converter(object):
'''
A class to help with file conversion in LIMIX
'''
__slots__=["options","args","data", "result","infostring","... | 0.127395 | 0.118462 |
import torch
from torch.utils.data import Dataset
from torchvision.transforms import transforms
import numpy as np
from PIL import Image
import os
def get_training_set(train_dir, single_channel, train_list=None):
if train_list is None:
patches_dir = train_dir + 'patches/'
assert os.path.exists(p... | CS-CO/cluster_sample/dataset.py | import torch
from torch.utils.data import Dataset
from torchvision.transforms import transforms
import numpy as np
from PIL import Image
import os
def get_training_set(train_dir, single_channel, train_list=None):
if train_list is None:
patches_dir = train_dir + 'patches/'
assert os.path.exists(p... | 0.643665 | 0.347482 |
import logging
from io import BytesIO
from openpyxl import load_workbook
from constance import config
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.vi... | seahub/api2/endpoints/admin/users_batch.py |
import logging
from io import BytesIO
from openpyxl import load_workbook
from constance import config
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.vi... | 0.319015 | 0.05211 |
''' Script to do very basic conversion of TRAC to reST format '''
import sys
import re
rst_section_levels = ['*', '=', '-', '~', '^']
heading_re = re.compile('^(=+) +([^=]+) +(=+)')
enumerate_re = re.compile(r'^ +(\d+\)) +(.*)')
link_re = re.compile(r'\[+ *(http://[\w.\-~/]+) +(.+?) *\]+')
italic_re = re.compile(r"''... | tools/trac2rst.py | ''' Script to do very basic conversion of TRAC to reST format '''
import sys
import re
rst_section_levels = ['*', '=', '-', '~', '^']
heading_re = re.compile('^(=+) +([^=]+) +(=+)')
enumerate_re = re.compile(r'^ +(\d+\)) +(.*)')
link_re = re.compile(r'\[+ *(http://[\w.\-~/]+) +(.+?) *\]+')
italic_re = re.compile(r"''... | 0.411347 | 0.256052 |
import math
import os
from pathlib import Path
import sys
import textwrap
from xml.etree import ElementTree as ET
tracks = ['rainbow', 'desert']
src_dir = sys.argv[1]
build_dir = sys.argv[2]
def parse_points(points_str):
return [[int(x) for x in p.split(',')] for p in points_str.split(' ')]
def get_template_pr... | extract_track_info.py |
import math
import os
from pathlib import Path
import sys
import textwrap
from xml.etree import ElementTree as ET
tracks = ['rainbow', 'desert']
src_dir = sys.argv[1]
build_dir = sys.argv[2]
def parse_points(points_str):
return [[int(x) for x in p.split(',')] for p in points_str.split(' ')]
def get_template_pr... | 0.300643 | 0.16175 |
import unittest
import api_example_base as aeb
from document_helper import DocumentHelper
import aspose.words as aw
class ExControlChar(aeb.ApiExampleBase):
def test_carriage_return(self) :
#ExStart
#ExFor:ControlChar
#ExFor:ControlChar.CR
#ExFor:Node.get_text
... | Examples/ApiExamples/ex_control_char.py | import unittest
import api_example_base as aeb
from document_helper import DocumentHelper
import aspose.words as aw
class ExControlChar(aeb.ApiExampleBase):
def test_carriage_return(self) :
#ExStart
#ExFor:ControlChar
#ExFor:ControlChar.CR
#ExFor:Node.get_text
... | 0.637708 | 0.349255 |