code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import traceback
import requests
import json
from datetime import datetime
from dust import Datatypes, ValueTypes, Operation, MetaProps, FieldProps
from dust.entity import Store, Entity, _entity_map, get_unit_deps_tuple
from dust.events import get_event, EventType
from dust.messages import register_listener, unregiste... | dust/slack.py | import traceback
import requests
import json
from datetime import datetime
from dust import Datatypes, ValueTypes, Operation, MetaProps, FieldProps
from dust.entity import Store, Entity, _entity_map, get_unit_deps_tuple
from dust.events import get_event, EventType
from dust.messages import register_listener, unregiste... | 0.343232 | 0.088741 |
import re
from regparser import utils
from regparser.citations import internal_citations, Label
from regparser.grammar.unified import marker_subpart_title
from regparser.search import find_offsets, find_start, segments
from regparser.tree import struct
from regparser.tree.appendix.carving import find_appendix_start
fr... | regparser/tree/reg_text.py | import re
from regparser import utils
from regparser.citations import internal_citations, Label
from regparser.grammar.unified import marker_subpart_title
from regparser.search import find_offsets, find_start, segments
from regparser.tree import struct
from regparser.tree.appendix.carving import find_appendix_start
fr... | 0.639849 | 0.324209 |
import os
import re
import yaml
import cerberus
import logging
from watsor.config.schema import schema
_LOGGER = logging.getLogger(__name__)
_ENV_pattern = re.compile('.*?\${(\w+)}.*?')
SECRETS_YAML = "secrets.yaml"
__SECRET_CACHE = {}
def _load_yaml(filename: str, loader: yaml.Loader = yaml.SafeLoader):
_LOG... | watsor/config/loader.py | import os
import re
import yaml
import cerberus
import logging
from watsor.config.schema import schema
_LOGGER = logging.getLogger(__name__)
_ENV_pattern = re.compile('.*?\${(\w+)}.*?')
SECRETS_YAML = "secrets.yaml"
__SECRET_CACHE = {}
def _load_yaml(filename: str, loader: yaml.Loader = yaml.SafeLoader):
_LOG... | 0.579519 | 0.294101 |
def get_appliance_nat_config(
self,
ne_id: str,
cached: bool,
) -> dict:
"""Get Edge Connect appliance NAT configuration
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - nat
- GET
- /nat/{neId}?cached={cac... | pyedgeconnect/orch/_nat.py |
def get_appliance_nat_config(
self,
ne_id: str,
cached: bool,
) -> dict:
"""Get Edge Connect appliance NAT configuration
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - nat
- GET
- /nat/{neId}?cached={cac... | 0.88602 | 0.257269 |
from MoinMoin import user, wikiutil
from MoinMoin.events import EventResult
class Result(EventResult):
""" A base class for results of notification handlers"""
pass
class Failure(Result):
""" Used to report a failure in sending notifications """
def __init__(self, reason, recipients = None):
... | Documentation/ManualSource/wikicmd/MoinMoin/events/notification.py | from MoinMoin import user, wikiutil
from MoinMoin.events import EventResult
class Result(EventResult):
""" A base class for results of notification handlers"""
pass
class Failure(Result):
""" Used to report a failure in sending notifications """
def __init__(self, reason, recipients = None):
... | 0.651798 | 0.134122 |
import json
from kazoo.client import KazooClient
from .base import WatchableBase, WatcherBase
class ZooKeeper(WatchableBase):
'''A zookeeper client wrapper. Improves usability especially for watcher callbacks.'''
def __init__(self, *hosts):
self._client = KazooClient(','.join(hosts), read_only=True)
... | smartclient/backends/zookeeper.py | import json
from kazoo.client import KazooClient
from .base import WatchableBase, WatcherBase
class ZooKeeper(WatchableBase):
'''A zookeeper client wrapper. Improves usability especially for watcher callbacks.'''
def __init__(self, *hosts):
self._client = KazooClient(','.join(hosts), read_only=True)
... | 0.406391 | 0.107813 |
import numpy as np
import matplotlib.pyplot as plt
import h5py
import matplotlib as mpl
import os
import sys
from datetime import datetime
plt.close('all')
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['font.size'] = 12
mpl.rcParams['axes.linewidth'] = 1
mpl.rcParams['xtick.major.width'] = 1
mpl.rcParams['ytick.major... | freqent/tests/brownianParticle/plots/make_eprSmoothingPlot.py | import numpy as np
import matplotlib.pyplot as plt
import h5py
import matplotlib as mpl
import os
import sys
from datetime import datetime
plt.close('all')
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['font.size'] = 12
mpl.rcParams['axes.linewidth'] = 1
mpl.rcParams['xtick.major.width'] = 1
mpl.rcParams['ytick.major... | 0.302494 | 0.436802 |
import decision_tree as dt
import naive_bayes as nb
import support_vector_machine as svm
import pandas as pd
import numpy as np
from pymed import PubMed
def drop_data(dataframe):
dataframe = dataframe.iloc[0:0]
return dataframe
def define_query(classification, data_type):
query = 0
if classification... | vigor/health_query.py | import decision_tree as dt
import naive_bayes as nb
import support_vector_machine as svm
import pandas as pd
import numpy as np
from pymed import PubMed
def drop_data(dataframe):
dataframe = dataframe.iloc[0:0]
return dataframe
def define_query(classification, data_type):
query = 0
if classification... | 0.522446 | 0.466238 |
import json,io,os,sys
from log import get_logger
'''
将对口相声按8:1:1切成train,dev.test
'''
this_dir = os.path.split(os.path.realpath(__file__))[0]
base_dir = os.path.join(os.path.dirname(this_dir))
data_dir = os.path.join(base_dir,'data_resource')
export_dir = os.path.join(data_dir,'cleanExportData')
result_dir = os.path.jo... | src/split_train_dev_test.py | import json,io,os,sys
from log import get_logger
'''
将对口相声按8:1:1切成train,dev.test
'''
this_dir = os.path.split(os.path.realpath(__file__))[0]
base_dir = os.path.join(os.path.dirname(this_dir))
data_dir = os.path.join(base_dir,'data_resource')
export_dir = os.path.join(data_dir,'cleanExportData')
result_dir = os.path.jo... | 0.063027 | 0.0704 |
from __future__ import division, print_function, absolute_import
import cv2
import os
import numpy as np
import time
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dir',type = str, default = '/home/xcy/append/dataset/VOT/vot2016/road', help = 'Path to vot tracking sequence')
args = parser.pa... | vot_inference.py | from __future__ import division, print_function, absolute_import
import cv2
import os
import numpy as np
import time
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dir',type = str, default = '/home/xcy/append/dataset/VOT/vot2016/road', help = 'Path to vot tracking sequence')
args = parser.pa... | 0.351645 | 0.116563 |
class ALFError(Exception):
"""A base class for ALF-related errors
Attributes
----------
explanation : str
An optional, verbose but general explanation of the error class. All errors will display
the same explanation.
"""
explanation = ''
def __init__(self, *args, terse=Fal... | one/alf/exceptions.py | class ALFError(Exception):
"""A base class for ALF-related errors
Attributes
----------
explanation : str
An optional, verbose but general explanation of the error class. All errors will display
the same explanation.
"""
explanation = ''
def __init__(self, *args, terse=Fal... | 0.892709 | 0.201931 |
import scrapy
import re
import urllib.parse
from datetime import datetime
from city_scrapers.spider import Spider
class Det_schoolsSpider(Spider):
name = 'det_schools'
long_name = 'Detroit Board of Education'
allowed_domains = ['detroitk12.org']
start_urls = ['http://detroitk12.org/board/meetings/']
... | city_scrapers/spiders/det_schools.py | import scrapy
import re
import urllib.parse
from datetime import datetime
from city_scrapers.spider import Spider
class Det_schoolsSpider(Spider):
name = 'det_schools'
long_name = 'Detroit Board of Education'
allowed_domains = ['detroitk12.org']
start_urls = ['http://detroitk12.org/board/meetings/']
... | 0.562177 | 0.316184 |
from django.shortcuts import render,redirect
from django.db.models import Count,Q
from .models import Exam,Question,Result,MyAdmin
from django.contrib import messages
from django.core import serializers
import json
import datetime,time
import pytz
from plyer import notification
from functools import reduce
# auth
from ... | nteacher/views.py | from django.shortcuts import render,redirect
from django.db.models import Count,Q
from .models import Exam,Question,Result,MyAdmin
from django.contrib import messages
from django.core import serializers
import json
import datetime,time
import pytz
from plyer import notification
from functools import reduce
# auth
from ... | 0.149687 | 0.208924 |
import zlx.record
import zlx.bin
import zlx.io
import zlx.wire
import zlx.int
MZ_MAGIC = 0x5A4D
PE_MAGIC = 0x4550
MACHINE_I386 = 0x014C
MACHINE_IA64 = 0x0200
MACHINE_AMD64 = 0x8664
# header flags
FH_RELOCS_STRIPPED = 0x0001
FH_EXECUTABLE_IMAGE = 0x0002
FH_LINE_NUMS_STRIPPED = 0x0004
FH_LOCAL_SYMS_STRIPPED = 0x0008
F... | zlx/pe.py | import zlx.record
import zlx.bin
import zlx.io
import zlx.wire
import zlx.int
MZ_MAGIC = 0x5A4D
PE_MAGIC = 0x4550
MACHINE_I386 = 0x014C
MACHINE_IA64 = 0x0200
MACHINE_AMD64 = 0x8664
# header flags
FH_RELOCS_STRIPPED = 0x0001
FH_EXECUTABLE_IMAGE = 0x0002
FH_LINE_NUMS_STRIPPED = 0x0004
FH_LOCAL_SYMS_STRIPPED = 0x0008
F... | 0.276202 | 0.118615 |
import re
from collections import OrderedDict
from rest_framework import renderers
from xml.sax.saxutils import escape
class KeyStringBaseRenderer(renderers.BaseRenderer):
def process_key(self, key):
raise NotImplementedError('process_key() must be implemented.')
def process_value(self, value):
... | apps/Localizr/renderers.py | import re
from collections import OrderedDict
from rest_framework import renderers
from xml.sax.saxutils import escape
class KeyStringBaseRenderer(renderers.BaseRenderer):
def process_key(self, key):
raise NotImplementedError('process_key() must be implemented.')
def process_value(self, value):
... | 0.45423 | 0.154567 |
import pytest
import responses
from prometheus_client import generate_latest, CollectorRegistry
from azure_costs_exporter.reserved_vm_collector import AzureReservedVMCollector
@pytest.fixture()
def enable_login():
responses.add(
method='POST',
url='https://login.microsoftonline.com/tenant_id/oau... | tests/test_reserved_vm_collector.py | import pytest
import responses
from prometheus_client import generate_latest, CollectorRegistry
from azure_costs_exporter.reserved_vm_collector import AzureReservedVMCollector
@pytest.fixture()
def enable_login():
responses.add(
method='POST',
url='https://login.microsoftonline.com/tenant_id/oau... | 0.51879 | 0.347523 |
import collections.abc
import enum
import functools
import itertools
import re
import typing
from collections import defaultdict
import sqlalchemy as sa
import typesystem
from sqlalchemy import orm as orm
from sqlalchemy.ext.associationproxy import AssociationProxy
from ..executor import async_
class SQLALchemyMap... | cognito_emulator/utils/typesystem.py |
import collections.abc
import enum
import functools
import itertools
import re
import typing
from collections import defaultdict
import sqlalchemy as sa
import typesystem
from sqlalchemy import orm as orm
from sqlalchemy.ext.associationproxy import AssociationProxy
from ..executor import async_
class SQLALchemyMap... | 0.484868 | 0.149531 |
model = {
u' de': 0,
u' în': 1,
u'de ': 2,
u' a ': 3,
u'ul ': 4,
u' co': 5,
u'în ': 6,
u're ': 7,
u'e d': 8,
u'ea ': 9,
u' di': 10,
u' pr': 11,
u'le ': 12,
u'şi ': 13,
u'are': 14,
u'at ': 15,
u'con': 16,
u'ui ': 17,
u' şi': 18,
u'i d': 19,
u'ii ': 20,
u' cu': 21,
u'e a': 22,
u'lui': 23,
u'ern':... | env/lib/python2.7/site-packages/guess_language/data/models/ro.py | model = {
u' de': 0,
u' în': 1,
u'de ': 2,
u' a ': 3,
u'ul ': 4,
u' co': 5,
u'în ': 6,
u're ': 7,
u'e d': 8,
u'ea ': 9,
u' di': 10,
u' pr': 11,
u'le ': 12,
u'şi ': 13,
u'are': 14,
u'at ': 15,
u'con': 16,
u'ui ': 17,
u' şi': 18,
u'i d': 19,
u'ii ': 20,
u' cu': 21,
u'e a': 22,
u'lui': 23,
u'ern':... | 0.288669 | 0.068975 |
import torch
import pandas as pd
import numpy as np
from typing import List, Union
from .layers import BatchNorm1d, Linear, Dense0d
from ._conversions import dataframe_to_tensor, classes_to_tensor
from ._conversions import floats_to_tensor, tensor_to_classes
from ._conversions import tensor_to_probabilities
from ._neur... | pygmalion/neural_networks/_dense_classifier.py | import torch
import pandas as pd
import numpy as np
from typing import List, Union
from .layers import BatchNorm1d, Linear, Dense0d
from ._conversions import dataframe_to_tensor, classes_to_tensor
from ._conversions import floats_to_tensor, tensor_to_classes
from ._conversions import tensor_to_probabilities
from ._neur... | 0.948179 | 0.461927 |
from typing import (
Any,
Awaitable,
)
from web3._utils.admin import (
add_peer,
addPeer,
datadir,
node_info,
nodeInfo,
peers,
start_rpc,
start_ws,
startRPC,
startWS,
stop_rpc,
stop_ws,
stopRPC,
stopWS,
)
from web3._utils.miner import (
make_dag,
... | web3/geth.py | from typing import (
Any,
Awaitable,
)
from web3._utils.admin import (
add_peer,
addPeer,
datadir,
node_info,
nodeInfo,
peers,
start_rpc,
start_ws,
startRPC,
startWS,
stop_rpc,
stop_ws,
stopRPC,
stopWS,
)
from web3._utils.miner import (
make_dag,
... | 0.498047 | 0.100392 |
import numpy as np
from keras.utils import Sequence
import xarray as xr
class DataGenerator(Sequence):
def __init__(self, partition='train', batch_size=32, n_channels=3, t_stride=10, shuffle=True, seed=1):
self.partition = partition
self.batch_size = batch_size
self.n_channels = n_channels... | data_generator.py | import numpy as np
from keras.utils import Sequence
import xarray as xr
class DataGenerator(Sequence):
def __init__(self, partition='train', batch_size=32, n_channels=3, t_stride=10, shuffle=True, seed=1):
self.partition = partition
self.batch_size = batch_size
self.n_channels = n_channels... | 0.805403 | 0.50354 |
import sys
from pathlib import Path
project_dir = Path(__file__).resolve().parents[2]
helper_folder = str(project_dir.parent / 'Utils')
sys.path.insert(0, helper_folder)
# print(helper_folder)
import notifications as n
from dotenv import find_dotenv, load_dotenv
import os
import pandas as pd
import logging
logger = lo... | price_tracker/src/features/monitor_price_changes.py | import sys
from pathlib import Path
project_dir = Path(__file__).resolve().parents[2]
helper_folder = str(project_dir.parent / 'Utils')
sys.path.insert(0, helper_folder)
# print(helper_folder)
import notifications as n
from dotenv import find_dotenv, load_dotenv
import os
import pandas as pd
import logging
logger = lo... | 0.054406 | 0.111531 |
import logging
from math import log, isnan
import os
import tempfile
from . import core
import basico
import petab_select
def copasi_aic():
"""Calculates the AIC based on the last parameter estimation run
SSR = weighted sum of squares
N = number of data points
K = number of parameters be... | basico/petab/select.py | import logging
from math import log, isnan
import os
import tempfile
from . import core
import basico
import petab_select
def copasi_aic():
"""Calculates the AIC based on the last parameter estimation run
SSR = weighted sum of squares
N = number of data points
K = number of parameters be... | 0.656878 | 0.410343 |
import logging.config
import os
import sys
from flask import Flask
from patch_tracking.api.issue import issue
from patch_tracking.api.tracking import tracking
from patch_tracking.database import db
from patch_tracking.task import task
logging.config.fileConfig('logging.conf', disable_existing_loggers=False)
app = Fla... | patch_tracking/app.py | import logging.config
import os
import sys
from flask import Flask
from patch_tracking.api.issue import issue
from patch_tracking.api.tracking import tracking
from patch_tracking.database import db
from patch_tracking.task import task
logging.config.fileConfig('logging.conf', disable_existing_loggers=False)
app = Fla... | 0.142232 | 0.050261 |
"true" '''\'
exec "$(dirname "$(readlink -f "$0")")"/../.venv/bin/python "$0" "$@"
'''
__doc__ = """
Based on https://github.com/Kozea/CairoSVG/issues/200#issuecomment-709015462
"""
import sys
import os
import cairocffi
import click
from cairosvg.parser import Tree
from cairosvg.surface import PDFSurface
VERSION = ... | src/svg2pdf.py | "true" '''\'
exec "$(dirname "$(readlink -f "$0")")"/../.venv/bin/python "$0" "$@"
'''
__doc__ = """
Based on https://github.com/Kozea/CairoSVG/issues/200#issuecomment-709015462
"""
import sys
import os
import cairocffi
import click
from cairosvg.parser import Tree
from cairosvg.surface import PDFSurface
VERSION = ... | 0.319865 | 0.121764 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class DnCNN(nn.Module):
def __init__(self, channels, num_of_layers=17, **kwargs):
super(DnCNN, self).__init__()
kernel_size = 3
padding = 1
features = 64
layers = []
layers.append(nn.Conv2d(in_channe... | models/arch/dncnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class DnCNN(nn.Module):
def __init__(self, channels, num_of_layers=17, **kwargs):
super(DnCNN, self).__init__()
kernel_size = 3
padding = 1
features = 64
layers = []
layers.append(nn.Conv2d(in_channe... | 0.964631 | 0.396039 |
import copy
from core.call import Call
from core.callhistory import CallHistory
from core.suit import *
class CallExplorer(object):
def possible_calls_over(self, history):
if history.is_complete():
return
yield Call('P')
last_non_pass = history.last_non_pass()
calle... | src/core/callexplorer.py |
import copy
from core.call import Call
from core.callhistory import CallHistory
from core.suit import *
class CallExplorer(object):
def possible_calls_over(self, history):
if history.is_complete():
return
yield Call('P')
last_non_pass = history.last_non_pass()
calle... | 0.367497 | 0.149469 |
import warnings
from collections import OrderedDict
from itertools import product, chain, takewhile, count
import re
import numpy as np
from ._common import ASTProcessor, is_, StandardOps, VectorsAsLists, id_generator
def translate(node, component=None, multistage=True, assign_to=None,
multistage_subexp... | skompiler/fromskast/excel.py | import warnings
from collections import OrderedDict
from itertools import product, chain, takewhile, count
import re
import numpy as np
from ._common import ASTProcessor, is_, StandardOps, VectorsAsLists, id_generator
def translate(node, component=None, multistage=True, assign_to=None,
multistage_subexp... | 0.623262 | 0.494812 |
from copy import deepcopy
from typing import Dict
# Yaml loaders and dumpers
from ruamel.yaml.main import round_trip_load as yaml_load, round_trip_dump as yaml_dump
# Yaml commentary
from ruamel.yaml.comments import CommentedMap as OrderedDict, CommentedSeq as OrderedList
# For manual creation of tokens
from ruame... | services/yml_client.py | from copy import deepcopy
from typing import Dict
# Yaml loaders and dumpers
from ruamel.yaml.main import round_trip_load as yaml_load, round_trip_dump as yaml_dump
# Yaml commentary
from ruamel.yaml.comments import CommentedMap as OrderedDict, CommentedSeq as OrderedList
# For manual creation of tokens
from ruame... | 0.36727 | 0.187635 |
# Import all dependencies:
from sqlite3 import connect
# Connect to the database:
def get_connection(location):
"""
Obtains a handle to the database
:return: A tuple representing the database connection & cursor.
"""
conn = connect(location)
cursor = conn.cursor()
# Create the database:
... | fortune_lite/__init__.py | # Import all dependencies:
from sqlite3 import connect
# Connect to the database:
def get_connection(location):
"""
Obtains a handle to the database
:return: A tuple representing the database connection & cursor.
"""
conn = connect(location)
cursor = conn.cursor()
# Create the database:
... | 0.670932 | 0.330093 |
import matplotlib.pyplot as plt
import numpy as np
from sklearn.manifold import TSNE
import seaborn as sns
import pandas as pd
def plot_metric(metric_dict, label, averaged_plot=True, n=8):
global_steps = list(metric_dict.keys())
metric = list(metric_dict.values())
if not averaged_plot:
plt.plot(g... | SemiSupervisedLearning/visualisations.py | import matplotlib.pyplot as plt
import numpy as np
from sklearn.manifold import TSNE
import seaborn as sns
import pandas as pd
def plot_metric(metric_dict, label, averaged_plot=True, n=8):
global_steps = list(metric_dict.keys())
metric = list(metric_dict.values())
if not averaged_plot:
plt.plot(g... | 0.682045 | 0.715244 |
from ai_ct_scans import phase_correlation
from skimage import draw
import pytest
import numpy as np
import mock
@pytest.fixture()
def circle():
circle = np.zeros([100, 100], dtype=float)
rows, cols = draw.circle(50, 50, 25)
circle[rows, cols] = 1
return circle
@pytest.fixture()
def shift_2d():
r... | tests/test_phase_correlation.py | from ai_ct_scans import phase_correlation
from skimage import draw
import pytest
import numpy as np
import mock
@pytest.fixture()
def circle():
circle = np.zeros([100, 100], dtype=float)
rows, cols = draw.circle(50, 50, 25)
circle[rows, cols] = 1
return circle
@pytest.fixture()
def shift_2d():
r... | 0.788705 | 0.586908 |
from hangmanDisplay import Hangman #Inputs a very long varible.
while True:
fstWrd = () #First word. These all open strings so that they can all be given letters.
secdWrd = () #second word
thrdWrd = () #third word, etc
forthWrd = () #Needs to be placed in the while loop so that it doesn't go onto the... | final hangman.py | from hangmanDisplay import Hangman #Inputs a very long varible.
while True:
fstWrd = () #First word. These all open strings so that they can all be given letters.
secdWrd = () #second word
thrdWrd = () #third word, etc
forthWrd = () #Needs to be placed in the while loop so that it doesn't go onto the... | 0.109176 | 0.344388 |
from __future__ import absolute_import, annotations
from unittest import TestCase
from unittest.mock import Mock
from test.unit.wenet.interface.mock.client import MockOauth2Client
from test.unit.wenet.interface.mock.response import MockResponse
from wenet.interface.exceptions import NotFound, CreationError, Authentic... | test/unit/wenet/interface/test_service_api.py | from __future__ import absolute_import, annotations
from unittest import TestCase
from unittest.mock import Mock
from test.unit.wenet.interface.mock.client import MockOauth2Client
from test.unit.wenet.interface.mock.response import MockResponse
from wenet.interface.exceptions import NotFound, CreationError, Authentic... | 0.689933 | 0.149469 |
import json
import os
mpi_typenames = [
'MPI_Aint',
'MPI_Comm',
'MPI_Comm_copy_attr_function',
'MPI_Comm_delete_attr_function',
#'MPI_Comm_errhandler_function',
'MPI_Datarep_conversion_function',
'MPI_Datarep_extent_function',
'MPI_Datatype',
'MPI_Errhandler',
'MPI_File',
#... | readspec.py | import json
import os
mpi_typenames = [
'MPI_Aint',
'MPI_Comm',
'MPI_Comm_copy_attr_function',
'MPI_Comm_delete_attr_function',
#'MPI_Comm_errhandler_function',
'MPI_Datarep_conversion_function',
'MPI_Datarep_extent_function',
'MPI_Datatype',
'MPI_Errhandler',
'MPI_File',
#... | 0.251188 | 0.081191 |
from datetime import timedelta
import pytest
from django.utils import timezone
from jcasts.podcasts import scheduler
from jcasts.podcasts.factories import PodcastFactory, SubscriptionFactory
from jcasts.podcasts.models import Podcast
class TestEmptyQueue:
def test_empty_queue(self, db, mock_feed_queue):
... | jcasts/podcasts/tests/test_scheduler.py | from datetime import timedelta
import pytest
from django.utils import timezone
from jcasts.podcasts import scheduler
from jcasts.podcasts.factories import PodcastFactory, SubscriptionFactory
from jcasts.podcasts.models import Podcast
class TestEmptyQueue:
def test_empty_queue(self, db, mock_feed_queue):
... | 0.614972 | 0.361221 |
import vtk
import os.path
import numpy as np
import nibabel as nib
from six import iteritems
from vtk.util import numpy_support as ns
from nibabel.streamlines.tck import TckFile as tck
def read_vtk(filename):
if filename.endswith('xml') or filename.endswith('vtp'):
polydata_reader = vtk.vtkXMLPolyDataRead... | Tractography/functions/input_output.py | import vtk
import os.path
import numpy as np
import nibabel as nib
from six import iteritems
from vtk.util import numpy_support as ns
from nibabel.streamlines.tck import TckFile as tck
def read_vtk(filename):
if filename.endswith('xml') or filename.endswith('vtp'):
polydata_reader = vtk.vtkXMLPolyDataRead... | 0.361503 | 0.192596 |
import cv2
import numpy as np
import dlib
from math import hypot
# Loading Camera and Nose image and Creating mask
cap = cv2.VideoCapture(0)
nose_image = cv2.imread("bunny.png")
_, frame = cap.read()
rows, cols, _ = frame.shape
nose_mask = np.zeros((rows, cols), np.uint8)
# Loading Face detector
detector = dlib.get_f... | Snapchat_Filters/Bunny_Nose/Bunny_Nose_Filter.py | import cv2
import numpy as np
import dlib
from math import hypot
# Loading Camera and Nose image and Creating mask
cap = cv2.VideoCapture(0)
nose_image = cv2.imread("bunny.png")
_, frame = cap.read()
rows, cols, _ = frame.shape
nose_mask = np.zeros((rows, cols), np.uint8)
# Loading Face detector
detector = dlib.get_f... | 0.441432 | 0.44348 |
import pandas as pd
import numpy as np
import scipy as sp
import random
from scipy.spatial.distance import mahalanobis
class TrainOutlier:
percentilek = None
valuecountsdict = None
colsum = None
median = None
invcovmx = None
cols = None
threshold = None
datetimecols = None
... | categoricaloutlier/AnomalyTrainer.py | import pandas as pd
import numpy as np
import scipy as sp
import random
from scipy.spatial.distance import mahalanobis
class TrainOutlier:
percentilek = None
valuecountsdict = None
colsum = None
median = None
invcovmx = None
cols = None
threshold = None
datetimecols = None
... | 0.79736 | 0.71484 |
from __future__ import division
import simcx
import numpy as np
import pyglet
__docformat__ = 'restructuredtext'
__author__ = '<NAME>'
class CA(simcx.Simulator):
"""Wolfram's elementary cellular automaton."""
def __init__(self, rule=30, width=50):
super(CA, self).__init__()
self.size = wid... | examples/ca.py | from __future__ import division
import simcx
import numpy as np
import pyglet
__docformat__ = 'restructuredtext'
__author__ = '<NAME>'
class CA(simcx.Simulator):
"""Wolfram's elementary cellular automaton."""
def __init__(self, rule=30, width=50):
super(CA, self).__init__()
self.size = wid... | 0.732974 | 0.360517 |
class Graph:
def __init__(self, name='<NAME> graf',
names_of_x=['A', 'B', 'C'],
values=[17, 21, 35],
xspace=5, yspace=2, size=15):
self.names_of_x, self.values, self.xspace = names_of_x, values, xspace
self.size = size
self.table = list(... | Domain/Graph.py | class Graph:
def __init__(self, name='<NAME> graf',
names_of_x=['A', 'B', 'C'],
values=[17, 21, 35],
xspace=5, yspace=2, size=15):
self.names_of_x, self.values, self.xspace = names_of_x, values, xspace
self.size = size
self.table = list(... | 0.30819 | 0.413832 |
import urwid as uw
import time
import datetime
from operator import itemgetter
from decimal import Decimal
__version__ = '1.1.1'
class FancyProgressBar(uw.ProgressBar):
"""ProgressBar with extended inline text"""
def __init__(self, normal, complete, done=100, satt=None,
units='KB'):
... | urwid_timed_progress/__init__.py |
import urwid as uw
import time
import datetime
from operator import itemgetter
from decimal import Decimal
__version__ = '1.1.1'
class FancyProgressBar(uw.ProgressBar):
"""ProgressBar with extended inline text"""
def __init__(self, normal, complete, done=100, satt=None,
units='KB'):
... | 0.853882 | 0.486941 |
import tensorflow as tf
from object_detection.models import faster_rcnn_inception_resnet_v2_feature_extractor as frcnn_inc_res
class FasterRcnnInceptionResnetV2FeatureExtractorTest(tf.test.TestCase):
def _build_feature_extractor(self, first_stage_features_stride):
return frcnn_inc_res.FasterRCNNInceptionResne... | object_detection/models/faster_rcnn_inception_resnet_v2_feature_extractor_test.py | import tensorflow as tf
from object_detection.models import faster_rcnn_inception_resnet_v2_feature_extractor as frcnn_inc_res
class FasterRcnnInceptionResnetV2FeatureExtractorTest(tf.test.TestCase):
def _build_feature_extractor(self, first_stage_features_stride):
return frcnn_inc_res.FasterRCNNInceptionResne... | 0.800653 | 0.506591 |
import torch
import torch.nn.functional as F
import time
import os
import cv2
import numpy as np
from sklearn.neighbors import KDTree
from random import sample
from lib.utils import save_session, AverageMeter
from lib.ransac_voting_gpu_layer.ransac_voting_gpu import ransac_voting_layer_v3
from lib.ransac_voting_gpu_lay... | trainers/coretrainer.py | import torch
import torch.nn.functional as F
import time
import os
import cv2
import numpy as np
from sklearn.neighbors import KDTree
from random import sample
from lib.utils import save_session, AverageMeter
from lib.ransac_voting_gpu_layer.ransac_voting_gpu import ransac_voting_layer_v3
from lib.ransac_voting_gpu_lay... | 0.681939 | 0.244273 |
import datetime
import ftplib
import json
import logging
import os
import re
import sys
from googleads import adwords
import click
import yaml
class _DateType(click.ParamType):
"""Initialise a custom click type to be used to validate a date provided at command line input."""
name = "Date (YYYY-MM-DD)"
... | adwordsreportdownloader/__init__.py | import datetime
import ftplib
import json
import logging
import os
import re
import sys
from googleads import adwords
import click
import yaml
class _DateType(click.ParamType):
"""Initialise a custom click type to be used to validate a date provided at command line input."""
name = "Date (YYYY-MM-DD)"
... | 0.501465 | 0.266086 |
import math
from src.functions.mainmenu import clear_console, print_header
def is_greater(thing, item):
""" Pick which item is higher ranking
Prompt the user to choose which thing is better, or ranked higher
Args:
thing The item being added to the list
item The item in the list b... | src/functions/additem.py | import math
from src.functions.mainmenu import clear_console, print_header
def is_greater(thing, item):
""" Pick which item is higher ranking
Prompt the user to choose which thing is better, or ranked higher
Args:
thing The item being added to the list
item The item in the list b... | 0.661814 | 0.516108 |
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
__all__ = ['EmbeddingWithWeights', 'EmbeddingSim', 'get_custom_objects']
def get_custom_objects():
return {
'EmbeddingWithWeights': EmbeddingWithWeights,
... | src/dnn/embeddings.py | import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
__all__ = ['EmbeddingWithWeights', 'EmbeddingSim', 'get_custom_objects']
def get_custom_objects():
return {
'EmbeddingWithWeights': EmbeddingWithWeights,
... | 0.923975 | 0.409782 |
import contextlib
import os
import pathlib
import platform
import subprocess
import tempfile
from unittest import TestCase
if platform.system() == "Windows":
import _winapi
exeext = ".exe"
else:
exeext = ""
repository_root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
user_scripts_di... | tests/test_x_blender.py | import contextlib
import os
import pathlib
import platform
import subprocess
import tempfile
from unittest import TestCase
if platform.system() == "Windows":
import _winapi
exeext = ".exe"
else:
exeext = ""
repository_root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
user_scripts_di... | 0.198608 | 0.091748 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import time
import os
import cv2
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge
from scipy.misc import imsave
import numpy as np
from sk... | lightct/tomo_scan.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import time
import os
import cv2
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge
from scipy.misc import imsave
import numpy as np
from sk... | 0.527317 | 0.196383 |
import logging
from typing import List
from opyoid.bindings import Binding, BindingToProviderAdapter, ClassBindingToProviderAdapter, \
InstanceBindingToProviderAdapter, MultiBindingToProviderAdapter, ProviderBindingToProviderAdapter, \
SelfBindingToProviderAdapter
from opyoid.bindings.registered_binding import... | opyoid/providers/providers_factories/from_registered_binding_provider_factory.py | import logging
from typing import List
from opyoid.bindings import Binding, BindingToProviderAdapter, ClassBindingToProviderAdapter, \
InstanceBindingToProviderAdapter, MultiBindingToProviderAdapter, ProviderBindingToProviderAdapter, \
SelfBindingToProviderAdapter
from opyoid.bindings.registered_binding import... | 0.84869 | 0.176281 |
from __future__ import print_function, division, absolute_import, unicode_literals
import unittest
from ufo2ft.fontInfoData import (
getAttrWithFallback,
normalizeStringForPostscript)
class GetAttrWithFallbackTest(unittest.TestCase):
def test_family_and_style_names(self):
info = TestInfoObject()
... | tests/fontInfoData_test.py | from __future__ import print_function, division, absolute_import, unicode_literals
import unittest
from ufo2ft.fontInfoData import (
getAttrWithFallback,
normalizeStringForPostscript)
class GetAttrWithFallbackTest(unittest.TestCase):
def test_family_and_style_names(self):
info = TestInfoObject()
... | 0.596198 | 0.239727 |
from flask import Flask
from flask_admin import Admin, AdminIndexView
from flask_admin.base import MenuLink
from flask_sqlalchemy import SQLAlchemy
from flask_admin.contrib.sqla import ModelView
db = SQLAlchemy()
admin = Admin(template_mode='bootstrap3', index_view=AdminIndexView(
menu_icon_type='glyph', menu_ico... | AD07-flask-admin-custom-navbar-demo/app.py | from flask import Flask
from flask_admin import Admin, AdminIndexView
from flask_admin.base import MenuLink
from flask_sqlalchemy import SQLAlchemy
from flask_admin.contrib.sqla import ModelView
db = SQLAlchemy()
admin = Admin(template_mode='bootstrap3', index_view=AdminIndexView(
menu_icon_type='glyph', menu_ico... | 0.448426 | 0.049681 |
# encoding: utf-8
from __future__ import print_function
import os
import socket
from pocketsphinx import LiveSpeech, get_model_path
from __playwave import playwave
from __baidu_speech_recognise import get_baidu_asr
sys_model_path = get_model_path()
voice_path = os.path.join(os.getcwd(), 'voice')
usr_model_path = os... | speech/livespeech_recognise.py |
# encoding: utf-8
from __future__ import print_function
import os
import socket
from pocketsphinx import LiveSpeech, get_model_path
from __playwave import playwave
from __baidu_speech_recognise import get_baidu_asr
sys_model_path = get_model_path()
voice_path = os.path.join(os.getcwd(), 'voice')
usr_model_path = os... | 0.232659 | 0.080141 |
from pulumi import Config, get_project, get_stack
from pulumi_policy import (
EnforcementLevel,
PolicyCustomTimeouts,
PolicyPack,
PolicyResourceOptions,
ResourceValidationPolicy,
StackValidationPolicy,
)
def create_urn(type_: str, name: str) -> str:
return f"urn:pulumi:{get_stack()}::{ge... | tests/integration/resource_options/policy-pack-python/__main__.py |
from pulumi import Config, get_project, get_stack
from pulumi_policy import (
EnforcementLevel,
PolicyCustomTimeouts,
PolicyPack,
PolicyResourceOptions,
ResourceValidationPolicy,
StackValidationPolicy,
)
def create_urn(type_: str, name: str) -> str:
return f"urn:pulumi:{get_stack()}::{ge... | 0.66628 | 0.285552 |
import tensorflow as tf
from tensorflow.keras import layers
from ...base.track_layers import CustomLayers
from ...base.xformer_layers.pairwise_op import PairwiseOp
from ...base.xformer_layers.masking import Neg1MaskedEmbedding, MaskedGlobalAvgPooling2D
from ..graph_xformer_model_base import GraphTransformerBase
from .... | lib/models/zinc_full/dc.py | import tensorflow as tf
from tensorflow.keras import layers
from ...base.track_layers import CustomLayers
from ...base.xformer_layers.pairwise_op import PairwiseOp
from ...base.xformer_layers.masking import Neg1MaskedEmbedding, MaskedGlobalAvgPooling2D
from ..graph_xformer_model_base import GraphTransformerBase
from .... | 0.661486 | 0.160135 |
from fractions import Fraction as Q
import unittest
from quest.assembler import assemble
from quest.process import Process
from quest.register import Register
from quest.stdio import StandardStream
STDIN = StandardStream.STDIN.value
STDOUT = StandardStream.STDOUT.value
STDERR = StandardStream.STDERR.value
ECHO_SOURC... | test/process_test.py | from fractions import Fraction as Q
import unittest
from quest.assembler import assemble
from quest.process import Process
from quest.register import Register
from quest.stdio import StandardStream
STDIN = StandardStream.STDIN.value
STDOUT = StandardStream.STDOUT.value
STDERR = StandardStream.STDERR.value
ECHO_SOURC... | 0.462959 | 0.132767 |
from tastypie.exceptions import ImmediateHttpResponse
from tastypie import fields
from tastypie.http import HttpNotFound
from cached import SimpleResource
from lib.bango.constants import SBI_ALREADY_ACCEPTED
from lib.bango.errors import BangoFormError
from lib.bango.forms import SBIForm
class SBIAgreement(object):
... | lib/bango/resources/sbi.py | from tastypie.exceptions import ImmediateHttpResponse
from tastypie import fields
from tastypie.http import HttpNotFound
from cached import SimpleResource
from lib.bango.constants import SBI_ALREADY_ACCEPTED
from lib.bango.errors import BangoFormError
from lib.bango.forms import SBIForm
class SBIAgreement(object):
... | 0.564579 | 0.107954 |
import json
from typing import Any
import geopandas as gpd
import pandas as pd
def _fill_unknown_countyname(gdf):
# these small areas are islands and so fall outside the routing key boundaries!
c = "countyname"
gdf.loc["077149001/077149002", c] = "CO. KERRY"
gdf.loc["057133003", c] = "CO. WEXFORD"
... | link-small-areas-to-routing-keys/tasks.py | import json
from typing import Any
import geopandas as gpd
import pandas as pd
def _fill_unknown_countyname(gdf):
# these small areas are islands and so fall outside the routing key boundaries!
c = "countyname"
gdf.loc["077149001/077149002", c] = "CO. KERRY"
gdf.loc["057133003", c] = "CO. WEXFORD"
... | 0.591723 | 0.246295 |
from financialdatapy.date import validate_date
import pandas as pd
import re
from typing import Optional
from financialdatapy.stocklist import KorStockList
from financialdatapy.exception import CountryCodeValidationFailed
from financialdatapy.market import Market
class Stock:
"""A class representing a stock or a ... | financialdatapy/stock.py | from financialdatapy.date import validate_date
import pandas as pd
import re
from typing import Optional
from financialdatapy.stocklist import KorStockList
from financialdatapy.exception import CountryCodeValidationFailed
from financialdatapy.market import Market
class Stock:
"""A class representing a stock or a ... | 0.940742 | 0.567817 |
from flask import abort, render_template, session, request, redirect, url_for, jsonify, send_file
from werkzeug.utils import secure_filename
from pathlib import Path
from .app import app
from .model import User, FileSharing
from .database import session as db
from . import users
import functools
import os
import rando... | src/hub/hub/__init__.py | from flask import abort, render_template, session, request, redirect, url_for, jsonify, send_file
from werkzeug.utils import secure_filename
from pathlib import Path
from .app import app
from .model import User, FileSharing
from .database import session as db
from . import users
import functools
import os
import rando... | 0.171616 | 0.067424 |
from __init__ import *
# no functions
# classes
class DtoErrorDetails(object):
""" DtoErrorDetails() """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DtoErrorDetails()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
ItemCodes=property(lambda self: object(),lamb... | release/stubs.min/Wms/RemotingObjects/Purchase.py | from __init__ import *
# no functions
# classes
class DtoErrorDetails(object):
""" DtoErrorDetails() """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DtoErrorDetails()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
ItemCodes=property(lambda self: object(),lamb... | 0.617859 | 0.110832 |
import display_page
import movie
cars = movie.Movie("Cars",
"Story about live cars",
"2006",
" Pixar Animation Studios",
"Walt Disney Pictures",
" <NAME>",
" Golden Globe Award for Best Animated ... | website.py | import display_page
import movie
cars = movie.Movie("Cars",
"Story about live cars",
"2006",
" Pixar Animation Studios",
"Walt Disney Pictures",
" <NAME>",
" Golden Globe Award for Best Animated ... | 0.539226 | 0.295224 |
import re
from typing import (
Callable,
Dict,
Generic,
Match,
Optional,
Pattern,
Tuple,
Type,
Union,
)
from .typevars import T, U, V, W # pylint: disable=unused-import
__all__ = (
"Converter",
"Filter",
"Transform",
"Equiv",
"OneOf",
"Regex",
"Range",
... | limier/converters.py | import re
from typing import (
Callable,
Dict,
Generic,
Match,
Optional,
Pattern,
Tuple,
Type,
Union,
)
from .typevars import T, U, V, W # pylint: disable=unused-import
__all__ = (
"Converter",
"Filter",
"Transform",
"Equiv",
"OneOf",
"Regex",
"Range",
... | 0.915283 | 0.519704 |
from django.test import TestCase
from tests.lib import TagTestManager
from tests.tagulousTestsApp3 import models as test_models
class CapitalisedModelTest(TagTestManager, TestCase):
"""
Test model with capitalised table name
"""
manage_models = [test_models.CapitalisedTest]
def setUpExtra(self)... | tests/test_models_capitalised.py | from django.test import TestCase
from tests.lib import TagTestManager
from tests.tagulousTestsApp3 import models as test_models
class CapitalisedModelTest(TagTestManager, TestCase):
"""
Test model with capitalised table name
"""
manage_models = [test_models.CapitalisedTest]
def setUpExtra(self)... | 0.728845 | 0.51946 |
import random
import numpy as np
from sklearn import metrics
import pandas as pd
import matplotlib.pyplot as plt
class kmeans_input_weight:
def __check_params(self, data, k, weights, max_iter, tol):
if k <= 0 or k > data.shape[0]:
raise ValueError("k must be > 0 and <= {}, got {}"... | chinese/clustering/WKmeans/kmeans_input/kmeans_input_weight_class.py | import random
import numpy as np
from sklearn import metrics
import pandas as pd
import matplotlib.pyplot as plt
class kmeans_input_weight:
def __check_params(self, data, k, weights, max_iter, tol):
if k <= 0 or k > data.shape[0]:
raise ValueError("k must be > 0 and <= {}, got {}"... | 0.577495 | 0.392744 |
import os
import sys
from typing import Tuple
sys.path.append(".")
sys.path.append("../../.")
from torch.utils.data import DataLoader
import wandb
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.loggers import WandbLogger
from src.d... | src/train/train.py | import os
import sys
from typing import Tuple
sys.path.append(".")
sys.path.append("../../.")
from torch.utils.data import DataLoader
import wandb
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.loggers import WandbLogger
from src.d... | 0.397354 | 0.228156 |
import logging, asyncio
from datetime import datetime
from tbot import config, db
from tbot.twitch_bot.bot_base import bot
from tbot.twitch_bot import commands, tasks, functions, filters
bot.channels = {}
@bot.on('AFTER_CONNECTED')
async def join(**kwargs):
bot.channels = await get_channels()
# From what I ca... | tbot/twitch_bot/bot_main.py | import logging, asyncio
from datetime import datetime
from tbot import config, db
from tbot.twitch_bot.bot_base import bot
from tbot.twitch_bot import commands, tasks, functions, filters
bot.channels = {}
@bot.on('AFTER_CONNECTED')
async def join(**kwargs):
bot.channels = await get_channels()
# From what I ca... | 0.263694 | 0.081923 |
from enum import Enum
from six import with_metaclass
from azure.core import CaseInsensitiveEnumMeta
class BillingFrequency(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The billing frequency.
"""
MONTH = "Month"
QUARTER = "Quarter"
YEAR = "Year"
class BudgetOperatorType(with_metaclass... | sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py |
from enum import Enum
from six import with_metaclass
from azure.core import CaseInsensitiveEnumMeta
class BillingFrequency(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""The billing frequency.
"""
MONTH = "Month"
QUARTER = "Quarter"
YEAR = "Year"
class BudgetOperatorType(with_metaclass... | 0.647018 | 0.217254 |
NUM_GA_ARGS = 12
NUM_MOL_ARGS = 7
def read_ga_input(ga_input_file):
"""Read an input file for genetic algorithm.
Parameters
----------
ga_input_file : str
The full path to the ga input file.
Raises
------
FileNotFoundError
The given ga_input_file does not exist.
Value... | kaplan/ga_input.py | NUM_GA_ARGS = 12
NUM_MOL_ARGS = 7
def read_ga_input(ga_input_file):
"""Read an input file for genetic algorithm.
Parameters
----------
ga_input_file : str
The full path to the ga input file.
Raises
------
FileNotFoundError
The given ga_input_file does not exist.
Value... | 0.79657 | 0.664255 |
from .exporter import Exporter
import ezdxf
from ezdxf.tools import standards as std
import entity
import config as cfg
class DxfExporter(Exporter):
def __init__(self):
super().__init__()
self.dwg = ezdxf.new(dxfversion='AC1015')
ezdxf.setup_linetypes(self.dwg)
self.msp = self.dwg... | exporter/dxfexporter.py | from .exporter import Exporter
import ezdxf
from ezdxf.tools import standards as std
import entity
import config as cfg
class DxfExporter(Exporter):
def __init__(self):
super().__init__()
self.dwg = ezdxf.new(dxfversion='AC1015')
ezdxf.setup_linetypes(self.dwg)
self.msp = self.dwg... | 0.363534 | 0.145449 |
from itertools import chain
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
from typing import Iterable, List, Any, Optional, Tuple
from common.consts import JOBS_CONTROLLER_QUEUE, JOBS_WORKER_QUEUE
from common.elasticsearch import create_index, delete_doc_operations, \
index_doc_o... | services/workers/src/workers/jobs/search.py |
from itertools import chain
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
from typing import Iterable, List, Any, Optional, Tuple
from common.consts import JOBS_CONTROLLER_QUEUE, JOBS_WORKER_QUEUE
from common.elasticsearch import create_index, delete_doc_operations, \
index_doc_o... | 0.627951 | 0.118003 |
import matplotlib.pyplot as plt
import seaborn as sns
import argparse
import json
def load_from_json(file_name):
with open(file_name, 'r') as out_file:
return json.load(out_file)
def plot_curves(json_logs, exp_ids, mode, factor):
""" Plots perplexity/ BLEU curves of multiple experiments for compariso... | utils/curve_plotter.py | import matplotlib.pyplot as plt
import seaborn as sns
import argparse
import json
def load_from_json(file_name):
with open(file_name, 'r') as out_file:
return json.load(out_file)
def plot_curves(json_logs, exp_ids, mode, factor):
""" Plots perplexity/ BLEU curves of multiple experiments for compariso... | 0.693473 | 0.388792 |
from __future__ import print_function
import codecs
import os
import os.path
import sys
def main():
# Get a list of all the releases, in order.
# These are held in a file, releases.txt where
# each line includes RELEASEDIR:Release Name.
releases = []
with codecs.open("releases.txt", "r", "utf8") ... | generate_indexes.py | from __future__ import print_function
import codecs
import os
import os.path
import sys
def main():
# Get a list of all the releases, in order.
# These are held in a file, releases.txt where
# each line includes RELEASEDIR:Release Name.
releases = []
with codecs.open("releases.txt", "r", "utf8") ... | 0.225929 | 0.191895 |
import re
import json
import logging
from optparse import OptionParser
import time
import csv
import ecxclient.sdk.client as client
logger = logging.getLogger('logger')
logger.setLevel(logging.INFO)
parser = OptionParser()
parser.add_option("--user", dest="username", help="ECX Username")
parser.add_option("--pass", ... | samples/joblogwithregex.py |
import re
import json
import logging
from optparse import OptionParser
import time
import csv
import ecxclient.sdk.client as client
logger = logging.getLogger('logger')
logger.setLevel(logging.INFO)
parser = OptionParser()
parser.add_option("--user", dest="username", help="ECX Username")
parser.add_option("--pass", ... | 0.205217 | 0.057599 |
import decisiontree_regressor
import randomforest_regressor
import pandas as pd
import numpy as np
import copy
class RegressionEngine():
def __init__(self, names=[], regressor='DecisionTree', split='ResourceNames'):
self.fault_tolerance_rate = []
self.fault_tolerance_rate_dict = dict()
for name in names:
se... | osgparse/regression_engine/regression_engine.py | import decisiontree_regressor
import randomforest_regressor
import pandas as pd
import numpy as np
import copy
class RegressionEngine():
def __init__(self, names=[], regressor='DecisionTree', split='ResourceNames'):
self.fault_tolerance_rate = []
self.fault_tolerance_rate_dict = dict()
for name in names:
se... | 0.078857 | 0.304875 |
import rospy
import tf
from time import sleep
from drawnow import drawnow
from matplotlib import pyplot as plt
from Config.colorbar import *
from Node import DataSaver, Painter
from Node.Painter import colormap
from Sensors.simulation.lib import device
from Utils import timeit, root_path
from Utils.Alert import PLAY... | signal/scripts/heatmap_test.py |
import rospy
import tf
from time import sleep
from drawnow import drawnow
from matplotlib import pyplot as plt
from Config.colorbar import *
from Node import DataSaver, Painter
from Node.Painter import colormap
from Sensors.simulation.lib import device
from Utils import timeit, root_path
from Utils.Alert import PLAY... | 0.2359 | 0.231462 |
from rackattack.tcp import heartbeat
from rackattack.common import baseipcserver
from rackattack.physical import network
from rackattack.common.hoststatemachine import STATE_DESTROYED
import logging
class IPCServer(baseipcserver.BaseIPCServer):
def __init__(self, publicNATIP, osmosisServerIP, dnsmasq, allocations... | rackattack/physical/ipcserver.py | from rackattack.tcp import heartbeat
from rackattack.common import baseipcserver
from rackattack.physical import network
from rackattack.common.hoststatemachine import STATE_DESTROYED
import logging
class IPCServer(baseipcserver.BaseIPCServer):
def __init__(self, publicNATIP, osmosisServerIP, dnsmasq, allocations... | 0.583085 | 0.10786 |
from playsound import playsound
from time import sleep
import re
import random
import os
def get_content(path):
pattern = r'=(.*)\n'
files = ["english.txt", 'mylanguage.txt', 'syllable.txt']
data = {}
for filename in files:
with open(path+filename, 'r', encoding='utf_16_le') as f:
... | RE/gina.py | from playsound import playsound
from time import sleep
import re
import random
import os
def get_content(path):
pattern = r'=(.*)\n'
files = ["english.txt", 'mylanguage.txt', 'syllable.txt']
data = {}
for filename in files:
with open(path+filename, 'r', encoding='utf_16_le') as f:
... | 0.118985 | 0.182225 |
import os
from typing import Optional
import numpy as np
import pytorch_lightning as pl
import torch
import torchvision.transforms as T
from torch.utils.data import DataLoader, TensorDataset
from torchvision import datasets
from torchvision.datasets.utils import download_and_extract_archive
from . import utils
cla... | lightning/data/cifar.py | import os
from typing import Optional
import numpy as np
import pytorch_lightning as pl
import torch
import torchvision.transforms as T
from torch.utils.data import DataLoader, TensorDataset
from torchvision import datasets
from torchvision.datasets.utils import download_and_extract_archive
from . import utils
cla... | 0.868332 | 0.554712 |
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_param_ArmISA', [dirname(__file__)])
except ImportError:
import _... | build/ARM/python/m5/internal/param_ArmISA.py |
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_param_ArmISA', [dirname(__file__)])
except ImportError:
import _... | 0.111931 | 0.079246 |
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import csv
import math
import openpyxl
#sandbox
url_map = 'https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/map'
url_info = 'https://sandbox-api.coinmarketcap.com/v1/cryptocur... | CMC_coin_info_fetch.py |
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import csv
import math
import openpyxl
#sandbox
url_map = 'https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/map'
url_info = 'https://sandbox-api.coinmarketcap.com/v1/cryptocur... | 0.060121 | 0.140248 |
from __future__ import print_function
# the following is a hack to get the baseclient to import whether we're in a
# package or not. This makes pep8 unhappy hence the annotations.
try:
# baseclient and this client are in a package
from .baseclient import BaseClient as _BaseClient # @UnusedImport
except Import... | lib/installed_clients/FunctionalProfileUtilClient.py |
from __future__ import print_function
# the following is a hack to get the baseclient to import whether we're in a
# package or not. This makes pep8 unhappy hence the annotations.
try:
# baseclient and this client are in a package
from .baseclient import BaseClient as _BaseClient # @UnusedImport
except Import... | 0.763219 | 0.130812 |
from dataclasses import Field
from typing import Any, Optional, Dict, List
from .constraints import Unique
import sqlite3 as sql
type_table: Dict[Optional[type], str] = {None: "NULL", int: "INTEGER", float: "REAL",
str: "TEXT", bytes: "BLOB"}
type_table.update({Unique[key]: f"... | datalite/commons.py | from dataclasses import Field
from typing import Any, Optional, Dict, List
from .constraints import Unique
import sqlite3 as sql
type_table: Dict[Optional[type], str] = {None: "NULL", int: "INTEGER", float: "REAL",
str: "TEXT", bytes: "BLOB"}
type_table.update({Unique[key]: f"... | 0.909929 | 0.357231 |
import logging
import os
import Queue
import signal
import sys
import time
import threading
from logging.handlers import RotatingFileHandler
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db.models.loading import get_apps
from djutils.queue import autod... | djutils/management/commands/queue_consumer.py |
import logging
import os
import Queue
import signal
import sys
import time
import threading
from logging.handlers import RotatingFileHandler
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db.models.loading import get_apps
from djutils.queue import autod... | 0.450843 | 0.057388 |
def load_file(filename: str) -> list:
"""Load the list of crab positions from filename
:param filename: Location of the input file
:return: List of display entries
"""
entries = list()
with open(filename) as f:
for line in f:
entries.append(
(line.split('|'... | 2021/problem08.py |
def load_file(filename: str) -> list:
"""Load the list of crab positions from filename
:param filename: Location of the input file
:return: List of display entries
"""
entries = list()
with open(filename) as f:
for line in f:
entries.append(
(line.split('|'... | 0.510008 | 0.522629 |
import sys
import click
from io import StringIO, BytesIO
from .determinator import TbxDocument
from lxml import etree
import rdflib
import logging
import os
XML_LANG = "{http://www.w3.org/XML/1998/namespace}lang"
@click.command()
@click.option(
"--input", default="data/example.tbx", prompt="input file", help="T... | determinator/convert2skos.py | import sys
import click
from io import StringIO, BytesIO
from .determinator import TbxDocument
from lxml import etree
import rdflib
import logging
import os
XML_LANG = "{http://www.w3.org/XML/1998/namespace}lang"
@click.command()
@click.option(
"--input", default="data/example.tbx", prompt="input file", help="T... | 0.598195 | 0.161883 |
from base.base_train import BaseTrain
from tqdm import tqdm
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
from time import sleep
# tf.enable_eager_execution()
import time
class GANTrainer(BaseTrain):
def __init__(self, sess, model, data, config, logger):
super(GANTr... | scripts/gan_trainer.py | from base.base_train import BaseTrain
from tqdm import tqdm
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
from time import sleep
# tf.enable_eager_execution()
import time
class GANTrainer(BaseTrain):
def __init__(self, sess, model, data, config, logger):
super(GANTr... | 0.878692 | 0.286494 |
try:
import pyscca
from argparse import ArgumentParser
import pandas as pd
from colorama import init, Fore, Back, Style
except ImportError:
print("\nImport Error Triggered, check dependencies, install from requirements.txt. Exiting")
exit()
import pyfiglet
import ntpath
import os
from pathlib im... | predfetch.py | try:
import pyscca
from argparse import ArgumentParser
import pandas as pd
from colorama import init, Fore, Back, Style
except ImportError:
print("\nImport Error Triggered, check dependencies, install from requirements.txt. Exiting")
exit()
import pyfiglet
import ntpath
import os
from pathlib im... | 0.143908 | 0.20199 |
from __future__ import annotations
import yaml
from .base_config import (
DEFAULT_CLITIC_MARKERS,
DEFAULT_COMPOUND_MARKERS,
DEFAULT_PUNCTUATION,
BaseConfig,
ConfigError,
)
__all__ = ["G2PConfig", "g2p_yaml_to_config", "load_basic_g2p_config"]
class G2PConfig(BaseConfig):
"""
Configurati... | montreal_forced_aligner/config/g2p_config.py | from __future__ import annotations
import yaml
from .base_config import (
DEFAULT_CLITIC_MARKERS,
DEFAULT_COMPOUND_MARKERS,
DEFAULT_PUNCTUATION,
BaseConfig,
ConfigError,
)
__all__ = ["G2PConfig", "g2p_yaml_to_config", "load_basic_g2p_config"]
class G2PConfig(BaseConfig):
"""
Configurati... | 0.706089 | 0.104386 |
from functools import partial
import warnings
import optax
import jax.numpy as jnp
from jax import jit, value_and_grad
import chex
import typing_extensions
from typing import Any, NamedTuple
from jsl.experimental.seql.agents.agent_utils import Memory
from jsl.experimental.seql.agents.base import Agent
Params = Any... | jsl/experimental/seql/agents/sgd_agent.py | from functools import partial
import warnings
import optax
import jax.numpy as jnp
from jax import jit, value_and_grad
import chex
import typing_extensions
from typing import Any, NamedTuple
from jsl.experimental.seql.agents.agent_utils import Memory
from jsl.experimental.seql.agents.base import Agent
Params = Any... | 0.856197 | 0.333368 |
from collections import defaultdict
import os
# external libs
import cv2
import numpy as np
# internal libs
from Show_Images_Differences.add_text_to_image.add_text_to_image import add_text_to_image, is_bigger_than
from Show_Images_Differences.compute_image_differences import compute_image_differences
from Show_Images... | Show_Images_Differences/modes/save.py | from collections import defaultdict
import os
# external libs
import cv2
import numpy as np
# internal libs
from Show_Images_Differences.add_text_to_image.add_text_to_image import add_text_to_image, is_bigger_than
from Show_Images_Differences.compute_image_differences import compute_image_differences
from Show_Images... | 0.608361 | 0.289748 |
from numpy import (
argsort, array, float_, inexact, issubdtype, __version__ as __np_version__
)
from numpy.core.multiarray import normalize_axis_index
from numpy.lib import NumpyVersion
__all__ = [
'moveaxis', 'preprocess', 'preprocess_pair', 'preprocess_npair'
]
if NumpyVersion(__np_version__) >= '1.11.0'... | src/skg/util.py | from numpy import (
argsort, array, float_, inexact, issubdtype, __version__ as __np_version__
)
from numpy.core.multiarray import normalize_axis_index
from numpy.lib import NumpyVersion
__all__ = [
'moveaxis', 'preprocess', 'preprocess_pair', 'preprocess_npair'
]
if NumpyVersion(__np_version__) >= '1.11.0'... | 0.9481 | 0.656108 |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = <KEY>
# SECURITY WARNING: don't run wi... | flisol_connect/settings.py | import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = <KEY>
# SECURITY WARNING: don't run wi... | 0.327776 | 0.053379 |
import collections
import threading
import time
from functools import wraps
from typing import List
from koapy.utils.logging.Logging import Logging
class RateLimiter:
def check_sleep_seconds(self, *args, **kwargs):
return 0
def add_call_history(self, *args, **kwargs):
pass
def sleep_if... | koapy/utils/rate_limiting/RateLimiter.py | import collections
import threading
import time
from functools import wraps
from typing import List
from koapy.utils.logging.Logging import Logging
class RateLimiter:
def check_sleep_seconds(self, *args, **kwargs):
return 0
def add_call_history(self, *args, **kwargs):
pass
def sleep_if... | 0.694303 | 0.104477 |
import os
from django.shortcuts import render
import spacy
import torch
from .utils import classifier as cl
import pandas as pd
# CONSTANTS
FOLDER = os.path.dirname(os.path.abspath(__file__))
MODEL_PATH = os.path.join(FOLDER, 'Ressources/Model/model.pt')
COLLECTED_DATA_PATH = os.path.join(FOLDER, 'Ressources/DataSet/C... | GBV/TextClassification/views.py | import os
from django.shortcuts import render
import spacy
import torch
from .utils import classifier as cl
import pandas as pd
# CONSTANTS
FOLDER = os.path.dirname(os.path.abspath(__file__))
MODEL_PATH = os.path.join(FOLDER, 'Ressources/Model/model.pt')
COLLECTED_DATA_PATH = os.path.join(FOLDER, 'Ressources/DataSet/C... | 0.482673 | 0.17692 |
from pandas_datareader import data as pdr
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
def calculate_protfolio(list_of_ticks, img_name, type):
#Select stocks, start year and end year, stock number has no known limit
## Insert Parmater
start_year = '2009-1-1'
end_year = '202... | Include/advisor.py | from pandas_datareader import data as pdr
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
def calculate_protfolio(list_of_ticks, img_name, type):
#Select stocks, start year and end year, stock number has no known limit
## Insert Parmater
start_year = '2009-1-1'
end_year = '202... | 0.586878 | 0.701295 |
import os
import sys
import jinja2
import re
import json
import traceback
from dpath import util as dpath_util
from jinja2.exceptions import UndefinedError, FilterArgumentError, TemplateSyntaxError
from jsonschema import validate, ValidationError, draft4_format_checker
from json.decoder import JSONDecodeError
from e2j2... | e2j2/templates.py | import os
import sys
import jinja2
import re
import json
import traceback
from dpath import util as dpath_util
from jinja2.exceptions import UndefinedError, FilterArgumentError, TemplateSyntaxError
from jsonschema import validate, ValidationError, draft4_format_checker
from json.decoder import JSONDecodeError
from e2j2... | 0.210848 | 0.09118 |
import numpy as np
from warnings import warn
def _check(scores, true_labels):
"""Raise exceptions or warnings for wrong or questionable inputs."""
if scores.ndim != 1 or true_labels.ndim !=1:
raise ValueError("Scores and labels must be one dimensional arrays")
if scores.size != true_labels.siz... | pySUMMA/utilities/roc.py | import numpy as np
from warnings import warn
def _check(scores, true_labels):
"""Raise exceptions or warnings for wrong or questionable inputs."""
if scores.ndim != 1 or true_labels.ndim !=1:
raise ValueError("Scores and labels must be one dimensional arrays")
if scores.size != true_labels.siz... | 0.796055 | 0.502136 |
# NetworkX performs network analytics (computes scc)
import heapq
import json
import time
from functools import partial
from math import log
from multiprocessing import Pool
import networkx as nx
from tqdm import tqdm
class CollectiveInfluencer(object):
'''
for CI
'''
def __init__(self, num_ci_thre... | chicken-ribs/CI.py | # NetworkX performs network analytics (computes scc)
import heapq
import json
import time
from functools import partial
from math import log
from multiprocessing import Pool
import networkx as nx
from tqdm import tqdm
class CollectiveInfluencer(object):
'''
for CI
'''
def __init__(self, num_ci_thre... | 0.444565 | 0.227394 |
import numpy as np
from . import tools
class IntervalTestData(object):
functions = [tools.f]
first_derivs = [tools.fd]
domains = [(1,2),(0,2),(-1,0),(-.2*np.pi,.2*np.e),(-1,1)]
integrals = [
[ 0.032346217980525, 0.030893429600387, -0.014887469493652,
-0.033389463703032, -0.016340257... | tests/data.py | import numpy as np
from . import tools
class IntervalTestData(object):
functions = [tools.f]
first_derivs = [tools.fd]
domains = [(1,2),(0,2),(-1,0),(-.2*np.pi,.2*np.e),(-1,1)]
integrals = [
[ 0.032346217980525, 0.030893429600387, -0.014887469493652,
-0.033389463703032, -0.016340257... | 0.269806 | 0.458834 |