code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from pprint import pformat
from six import iteritems
import re
class V1beta1CustomResourceDefinitionSpec(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... | kubernetes/client/models/v1beta1_custom_resource_definition_spec.py | from pprint import pformat
from six import iteritems
import re
class V1beta1CustomResourceDefinitionSpec(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... | 0.756897 | 0.132066 |
import os
import time
import hashlib
import codecs
from unittest import TestCase
from cryptodetector import Options, CryptoDetector, MethodFactory
class TestCryptoDetector(TestCase):
"""Unit Tests
"""
KNOWN_TEST_SHA1 = "370aef2687f5d68f3696b0190d459600a22dccf7"
def method(self, method_id):
fo... | tests/test_all.py | import os
import time
import hashlib
import codecs
from unittest import TestCase
from cryptodetector import Options, CryptoDetector, MethodFactory
class TestCryptoDetector(TestCase):
"""Unit Tests
"""
KNOWN_TEST_SHA1 = "370aef2687f5d68f3696b0190d459600a22dccf7"
def method(self, method_id):
fo... | 0.412175 | 0.340746 |
import errno
import json
import logging
import os
import sys
from pathlib import Path
from typing import Optional
LOGGER = logging.getLogger("napari.monitor")
# If False monitor is disabled even if we meet all other requirements.
ENABLE_MONITOR = True
def _load_config(path: str) -> dict:
"""Load the JSON format... | napari/components/experimental/monitor/_monitor.py | import errno
import json
import logging
import os
import sys
from pathlib import Path
from typing import Optional
LOGGER = logging.getLogger("napari.monitor")
# If False monitor is disabled even if we meet all other requirements.
ENABLE_MONITOR = True
def _load_config(path: str) -> dict:
"""Load the JSON format... | 0.757615 | 0.236032 |
from functools import cached_property
from lss.drums import MiDIDrums
from lss.utils import Color
class Pad:
"""
Represents one of 81 pads.
Pad is defined by (x, y) pair which strictly corresponds with note
assigned to the pad.
Note map:
91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 || 99
====... | lss/pad.py | from functools import cached_property
from lss.drums import MiDIDrums
from lss.utils import Color
class Pad:
"""
Represents one of 81 pads.
Pad is defined by (x, y) pair which strictly corresponds with note
assigned to the pad.
Note map:
91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 || 99
====... | 0.822332 | 0.357904 |
import re
birth_year = 'byr'
issue_year = 'iyr'
expiration_year = 'eyr'
height = 'hgt'
hair_color = 'hcl'
eye_color = 'ecl'
passport_id = 'pid'
country_id = 'cid'
def is_valid_passport_part1(passport: dict):
mandatory_passport_fields = [birth_year, issue_year, expiration_year, height, hair_color, eye_color, pass... | 2020/day4/day4.py | import re
birth_year = 'byr'
issue_year = 'iyr'
expiration_year = 'eyr'
height = 'hgt'
hair_color = 'hcl'
eye_color = 'ecl'
passport_id = 'pid'
country_id = 'cid'
def is_valid_passport_part1(passport: dict):
mandatory_passport_fields = [birth_year, issue_year, expiration_year, height, hair_color, eye_color, pass... | 0.353317 | 0.105257 |
from . import core
from .. import mongo, logger, celery
from flask import (
render_template, redirect, url_for, jsonify, request, Response
)
from flask_login import login_required, current_user
from flask import current_app as app
from .forms import AccountSettingsForm, ChangePasswordForm
from ..utils.helpers impor... | app/core/generic.py | from . import core
from .. import mongo, logger, celery
from flask import (
render_template, redirect, url_for, jsonify, request, Response
)
from flask_login import login_required, current_user
from flask import current_app as app
from .forms import AccountSettingsForm, ChangePasswordForm
from ..utils.helpers impor... | 0.455441 | 0.049889 |
from unittest.mock import patch
from homeassistant.components.siren import ATTR_DURATION, DOMAIN as SIREN_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
)
from .test_gateway import (
DECONZ_WEB_REQUEST,
... | tests/components/deconz/test_siren.py |
from unittest.mock import patch
from homeassistant.components.siren import ATTR_DURATION, DOMAIN as SIREN_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
)
from .test_gateway import (
DECONZ_WEB_REQUEST,
... | 0.713531 | 0.510069 |
__author__ = "<NAME>"
__copyright__ = "Copyright (c) 2016 Black Radley Limited."
import helpers_list
import helpers_geo
ceremonial_counties_of_england = helpers_list.get_ceremonial_counties_of_england()
ceremonial_counties_of_england = ['Bristol', 'Cornwall', 'Devon', 'Dorset', 'Gloucestershire', 'Somerset', 'Wiltsh... | data/src/3_geocode_museums_from_wikipedia.py |
__author__ = "<NAME>"
__copyright__ = "Copyright (c) 2016 Black Radley Limited."
import helpers_list
import helpers_geo
ceremonial_counties_of_england = helpers_list.get_ceremonial_counties_of_england()
ceremonial_counties_of_england = ['Bristol', 'Cornwall', 'Devon', 'Dorset', 'Gloucestershire', 'Somerset', 'Wiltsh... | 0.256832 | 0.138695 |
from xstac import xarray_to_stac, fix_attrs
import xarray as xr
import numpy as np
import pandas as pd
import pytest
import pystac
data = np.empty((40, 584, 284), dtype="float32")
x = xr.DataArray(
np.arange(-5802250.0, -5519250 + 1000, 1000),
name="x",
dims="x",
attrs={
"units": "m",
... | test_xstac.py | from xstac import xarray_to_stac, fix_attrs
import xarray as xr
import numpy as np
import pandas as pd
import pytest
import pystac
data = np.empty((40, 584, 284), dtype="float32")
x = xr.DataArray(
np.arange(-5802250.0, -5519250 + 1000, 1000),
name="x",
dims="x",
attrs={
"units": "m",
... | 0.566019 | 0.519217 |
"""Analysis plugin to look up files in VirusTotal and tag events."""
from __future__ import unicode_literals
from plaso.analysis import interface
from plaso.analysis import logger
from plaso.analysis import manager
from plaso.lib import errors
class VirusTotalAnalyzer(interface.HTTPHashAnalyzer):
"""Class that an... | plaso/analysis/virustotal.py | """Analysis plugin to look up files in VirusTotal and tag events."""
from __future__ import unicode_literals
from plaso.analysis import interface
from plaso.analysis import logger
from plaso.analysis import manager
from plaso.lib import errors
class VirusTotalAnalyzer(interface.HTTPHashAnalyzer):
"""Class that an... | 0.847779 | 0.31932 |
# here put the import lib
from . import STensor
import spartan as st
class Graph:
def __init__(self, graph_tensor: STensor, weighted: bool = False,
bipartite: bool = False, modet=None):
'''Construct a graph from sparse tensor.
If the sparse tensor has more than 2 modes, then it is... | spartan/tensor/graph.py | # here put the import lib
from . import STensor
import spartan as st
class Graph:
def __init__(self, graph_tensor: STensor, weighted: bool = False,
bipartite: bool = False, modet=None):
'''Construct a graph from sparse tensor.
If the sparse tensor has more than 2 modes, then it is... | 0.816662 | 0.446977 |
# pyre-unsafe
import logging
from typing import Optional, Sequence, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from kats.consts import TimeSeriesChangePoint, TimeSeriesData
from kats.detectors.detector import Detector
from scipy.stats import chi2
from sklearn.covariance impor... | kats/detectors/hourly_ratio_detection.py |
# pyre-unsafe
import logging
from typing import Optional, Sequence, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from kats.consts import TimeSeriesChangePoint, TimeSeriesData
from kats.detectors.detector import Detector
from scipy.stats import chi2
from sklearn.covariance impor... | 0.959059 | 0.680288 |
import pytest
from align.circuit.core import NTerminalDevice, Circuit, SubCircuit, Model
def test_n_terminal_device():
inst = NTerminalDevice('X1')
assert inst.name == 'X1'
with pytest.raises(AssertionError):
inst = NTerminalDevice('X2', 'net1')
@pytest.fixture
def TwoTerminalDevice():
return... | tests/circuit/test_core.py | import pytest
from align.circuit.core import NTerminalDevice, Circuit, SubCircuit, Model
def test_n_terminal_device():
inst = NTerminalDevice('X1')
assert inst.name == 'X1'
with pytest.raises(AssertionError):
inst = NTerminalDevice('X2', 'net1')
@pytest.fixture
def TwoTerminalDevice():
return... | 0.642096 | 0.667053 |
import json
from kafka import KafkaConsumer, KafkaProducer
from kafka.structs import TopicPartition
from tethys.core.transports.connectors.connector_base import (
ConnectorBase,
ConnectionBase,
)
class KafkaConnection(ConnectionBase):
def __init__(
self,
channel_id: str,
group_i... | tethys/core/transports/connectors/connector_kafka.py |
import json
from kafka import KafkaConsumer, KafkaProducer
from kafka.structs import TopicPartition
from tethys.core.transports.connectors.connector_base import (
ConnectorBase,
ConnectionBase,
)
class KafkaConnection(ConnectionBase):
def __init__(
self,
channel_id: str,
group_i... | 0.651466 | 0.076857 |
import pygame as pyg
from pygame.locals import *
import random, time
from spritesheet.Sprites import *
clock = pyg.time.Clock()
FPS = 60
pyg.init()
screen = pyg.display.set_mode([800, 600], RESIZABLE)
mouse = pyg.transform.scale(pyg.image.load('./res/mouse/mouse_0.png'), (16, 16))
seletor = pyg.transfo... | testsmap.py | import pygame as pyg
from pygame.locals import *
import random, time
from spritesheet.Sprites import *
clock = pyg.time.Clock()
FPS = 60
pyg.init()
screen = pyg.display.set_mode([800, 600], RESIZABLE)
mouse = pyg.transform.scale(pyg.image.load('./res/mouse/mouse_0.png'), (16, 16))
seletor = pyg.transfo... | 0.088224 | 0.167253 |
from __future__ import division, print_function, unicode_literals
import distro
import itertools
import logging
from rpaths import Path
import subprocess
import time
from reprozip.common import Package
from reprozip.utils import iteritems, listvalues
logger = logging.getLogger('reprozip')
magic_dirs = ('/dev', '/... | reprozip/reprozip/tracer/linux_pkgs.py | from __future__ import division, print_function, unicode_literals
import distro
import itertools
import logging
from rpaths import Path
import subprocess
import time
from reprozip.common import Package
from reprozip.utils import iteritems, listvalues
logger = logging.getLogger('reprozip')
magic_dirs = ('/dev', '/... | 0.482185 | 0.112016 |
from model.rbm import RBM
import tensorflow as tf
import copy
from functools import partial
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class RBMRealPos(RBM):
"""
This class is used to define a restricted Boltzmann machine with real and
positive wavefunction ... | model/rbm/realpos/rbm_realpos.py | from model.rbm import RBM
import tensorflow as tf
import copy
from functools import partial
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class RBMRealPos(RBM):
"""
This class is used to define a restricted Boltzmann machine with real and
positive wavefunction ... | 0.814717 | 0.738315 |
import math
import random
import time
import pybullet as p
import pybullet_data as pd
random.seed(10)
from blind_walking.envs.env_modifiers.env_modifier import EnvModifier
textureId = -1
useProgrammatic = 0
useTerrainFromPNG = 1
useDeepLocoCSV = 2
updateHeightfield = False
heightfieldSource = useProgrammatic
numH... | blind_walking/envs/env_modifiers/heightfield.py | import math
import random
import time
import pybullet as p
import pybullet_data as pd
random.seed(10)
from blind_walking.envs.env_modifiers.env_modifier import EnvModifier
textureId = -1
useProgrammatic = 0
useTerrainFromPNG = 1
useDeepLocoCSV = 2
updateHeightfield = False
heightfieldSource = useProgrammatic
numH... | 0.23546 | 0.265273 |
from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path, re_path
from django.conf import settings
from rest_framework import routers, permissions
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_fr... | tbot/rest_api/urls.py | from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path, re_path
from django.conf import settings
from rest_framework import routers, permissions
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_fr... | 0.337859 | 0.066873 |
import torch
from . import scatter_add, scatter_max
def scatter_logsumexp(src, index, dim=-1, out=None, dim_size=None,
fill_value=None, eps=1e-12):
r"""Fills :attr:`out` with the log of summed exponentials of all values
from the :attr:`src` tensor at the indices specified in the :attr:`... | torch_scatter/logsumexp.py | import torch
from . import scatter_add, scatter_max
def scatter_logsumexp(src, index, dim=-1, out=None, dim_size=None,
fill_value=None, eps=1e-12):
r"""Fills :attr:`out` with the log of summed exponentials of all values
from the :attr:`src` tensor at the indices specified in the :attr:`... | 0.917094 | 0.588209 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from spl_sirna.sirna_util import get_seq_motif, idx_to_seq
USE_CUDA = torch.cuda.is_available()
# DEVICE = torch.device('cuda' if USE_CUDA else 'cpu')
class Word2vecModel(nn.Module):
def __init__(self, vocab_size, embed_size):
... | RSC/model_util.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from spl_sirna.sirna_util import get_seq_motif, idx_to_seq
USE_CUDA = torch.cuda.is_available()
# DEVICE = torch.device('cuda' if USE_CUDA else 'cpu')
class Word2vecModel(nn.Module):
def __init__(self, vocab_size, embed_size):
... | 0.862612 | 0.35883 |
#string类(不可变对象, 接近内置)
string = str('...') #string = '...'
string.isalnum()
string.isalpha()
string.isdigit()
string.islower()
string.isupper()
string.isspace()
string.isidentifier() #Python标识符
string.startswith('...') #以子串开头
string.endswith('...') #以子串结尾
string.find('...') #查找子串最低下标(-1)
string.rfind('...') #查找子串最高... | KnowledgeSet/B_Other/Python/_note_.py/_class_.py | #string类(不可变对象, 接近内置)
string = str('...') #string = '...'
string.isalnum()
string.isalpha()
string.isdigit()
string.islower()
string.isupper()
string.isspace()
string.isidentifier() #Python标识符
string.startswith('...') #以子串开头
string.endswith('...') #以子串结尾
string.find('...') #查找子串最低下标(-1)
string.rfind('...') #查找子串最高... | 0.091118 | 0.355859 |
# Kludge to import logger from a relative path
from sys import path, stderr
path.append('../logger')
from logger import Logger
OBJS = [
{
"name": "red-ball",
"radius": 0.25,
"restitution": 0.85,
"color": [1, 0, 0, 1],
"pos": [-1, 4, 0],
"rot": [0, 0, 0, 1],
"... | examples/falling_sphere.py | # Kludge to import logger from a relative path
from sys import path, stderr
path.append('../logger')
from logger import Logger
OBJS = [
{
"name": "red-ball",
"radius": 0.25,
"restitution": 0.85,
"color": [1, 0, 0, 1],
"pos": [-1, 4, 0],
"rot": [0, 0, 0, 1],
"... | 0.404743 | 0.450239 |
# Lint as: python3
# pylint:disable=line-too-long
r"""Beam job to map to tf.Examples of embeddings.
This file has two modes:
1) Map from tf.Examples of audio to tf.Examples of embeddings.
2) Map from TFDS dataseet to tf.Examples of embeddings.
"""
# pylint:enable=line-too-long
from typing import Any, Dict
from abs... | non_semantic_speech_benchmark/data_prep/audio_to_embeddings_beam_main.py |
# Lint as: python3
# pylint:disable=line-too-long
r"""Beam job to map to tf.Examples of embeddings.
This file has two modes:
1) Map from tf.Examples of audio to tf.Examples of embeddings.
2) Map from TFDS dataseet to tf.Examples of embeddings.
"""
# pylint:enable=line-too-long
from typing import Any, Dict
from abs... | 0.844697 | 0.255919 |
import torch
import torch.nn as nn
import torch.nn.init
import sys
import numpy as np
import torchvision.models as models
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from torch.nn.utils.rnn import pad_packed_sequence
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.c... | model.py | import torch
import torch.nn as nn
import torch.nn.init
import sys
import numpy as np
import torchvision.models as models
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from torch.nn.utils.rnn import pad_packed_sequence
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.c... | 0.851799 | 0.3805 |
import os
import threading
import subprocess
import pkg_resources
METEOR_JAR = pkg_resources.resource_filename('nmtpytorch',
'lib/meteor-1.5.jar')
class Meteor(object):
def __init__(self, language, norm=False):
self.meteor_cmd = ['java', '-jar', '-Xmx2G', MET... | nmtpytorch/cocoeval/meteor/meteor.py |
import os
import threading
import subprocess
import pkg_resources
METEOR_JAR = pkg_resources.resource_filename('nmtpytorch',
'lib/meteor-1.5.jar')
class Meteor(object):
def __init__(self, language, norm=False):
self.meteor_cmd = ['java', '-jar', '-Xmx2G', MET... | 0.377885 | 0.115586 |
import optparse
import os
import sys
import time
import threading
import BaseHTTPServer
from server.http_handler import XwalkHttpHandlerWrapper
from net.port_server import PortServer
from base.log import InitLogging
from base.log import VLOG
from base.bind import Bind
def main(argv):
''' main entrance of xwalkdriver... | xwalkdriver.py | import optparse
import os
import sys
import time
import threading
import BaseHTTPServer
from server.http_handler import XwalkHttpHandlerWrapper
from net.port_server import PortServer
from base.log import InitLogging
from base.log import VLOG
from base.bind import Bind
def main(argv):
''' main entrance of xwalkdriver... | 0.157947 | 0.041793 |
from __future__ import annotations
import platform
from typing import TYPE_CHECKING
import psutil
from pincer import command
if TYPE_CHECKING:
from pincer.objects import Embed
from mcoding_bot.bot import Bot
def _percent_info_unit_ram(used, total):
mb: int = 1024 ** 2
return (
100 * (used /... | mcoding_bot/cogs/dev.py | from __future__ import annotations
import platform
from typing import TYPE_CHECKING
import psutil
from pincer import command
if TYPE_CHECKING:
from pincer.objects import Embed
from mcoding_bot.bot import Bot
def _percent_info_unit_ram(used, total):
mb: int = 1024 ** 2
return (
100 * (used /... | 0.875867 | 0.209955 |
import json
import sys
from pathlib import Path
from typing import Optional, Awaitable
from os import path as P
import tornado.websocket
from tornado.log import app_log
from tornado.web import Finish, HTTPError, StaticFileHandler
class RestResult(object):
def __init__(self, code, body):
self.code = cod... | experiment-visualization/experiment_visualization/handlers.py | import json
import sys
from pathlib import Path
from typing import Optional, Awaitable
from os import path as P
import tornado.websocket
from tornado.log import app_log
from tornado.web import Finish, HTTPError, StaticFileHandler
class RestResult(object):
def __init__(self, code, body):
self.code = cod... | 0.419648 | 0.100172 |
import argparse
import logging
import numpy as np
import tensorflow as tf
from features import extract_features_shapenet, generate_views
from inference import shapenet_inference
from utilities import print_and_log, get_log_files, gaussian_log_density
from data import get_data
"""
parse_command_line: command line par... | src/train_view_reconstruction.py | import argparse
import logging
import numpy as np
import tensorflow as tf
from features import extract_features_shapenet, generate_views
from inference import shapenet_inference
from utilities import print_and_log, get_log_files, gaussian_log_density
from data import get_data
"""
parse_command_line: command line par... | 0.837421 | 0.236252 |
from PIL import Image
from difflib import SequenceMatcher
import hashlib, os, imagehash, argparse
# Setup arguments
parser = argparse.ArgumentParser(description="Image deduplicator")
parser.add_argument('-m', '--mode', help="Deduplicator operation mode (rename, move, organize, similar, all)", required=True)
parser.add... | deduper.py | from PIL import Image
from difflib import SequenceMatcher
import hashlib, os, imagehash, argparse
# Setup arguments
parser = argparse.ArgumentParser(description="Image deduplicator")
parser.add_argument('-m', '--mode', help="Deduplicator operation mode (rename, move, organize, similar, all)", required=True)
parser.add... | 0.272218 | 0.099733 |
from functools import reduce
from operator import mul
from typing import Union, Callable
import torch
from torch import nn
from continual_learning.solvers.base import Solver
class MultiHeadsSolver(Solver):
def __init__(self, input_dim: Union[int, tuple], topology: Callable[[int, int], nn.Module] = None):
... | continual_learning/solvers/multi_task.py | from functools import reduce
from operator import mul
from typing import Union, Callable
import torch
from torch import nn
from continual_learning.solvers.base import Solver
class MultiHeadsSolver(Solver):
def __init__(self, input_dim: Union[int, tuple], topology: Callable[[int, int], nn.Module] = None):
... | 0.911309 | 0.218982 |
from common import *
from apps.nem.helpers import *
from apps.nem.multisig import *
from apps.nem.multisig.serialize import *
from apps.nem.namespace import *
from apps.nem.namespace.serialize import *
from trezor.messages.NEMSignTx import NEMSignTx
from trezor.messages.NEMAggregateModification import NEMAggregateMod... | core/tests/test_apps.nem.multisig.py | from common import *
from apps.nem.helpers import *
from apps.nem.multisig import *
from apps.nem.multisig.serialize import *
from apps.nem.namespace import *
from apps.nem.namespace.serialize import *
from trezor.messages.NEMSignTx import NEMSignTx
from trezor.messages.NEMAggregateModification import NEMAggregateMod... | 0.555918 | 0.186706 |
import pytest # pylint: disable=unused-import
from datetime import date, timedelta
from structure.organization import Team # pylint: disable=unused-import
from structure.measurements import OTMeasurement
class TestOvertimeMeasurement:
TEAM = None
def test_common_overtime(self):
# Positive overtime
... | tmv/test/test_measurements.py | import pytest # pylint: disable=unused-import
from datetime import date, timedelta
from structure.organization import Team # pylint: disable=unused-import
from structure.measurements import OTMeasurement
class TestOvertimeMeasurement:
TEAM = None
def test_common_overtime(self):
# Positive overtime
... | 0.596668 | 0.387806 |
# In[1]:
'''
Author: Sameer
Date: 09/11/2018
Read Me:
1 - This code is for building a Gaussian Kernel (RBF) Support Vector Machine (SVM) and the optimization
problem (Quadratic Programming) is solved using python cvxopt optimization toolbox.
Polynomial Kernel SVM can also be build using this code.
2 - Input Sample... | SVM.py |
# In[1]:
'''
Author: Sameer
Date: 09/11/2018
Read Me:
1 - This code is for building a Gaussian Kernel (RBF) Support Vector Machine (SVM) and the optimization
problem (Quadratic Programming) is solved using python cvxopt optimization toolbox.
Polynomial Kernel SVM can also be build using this code.
2 - Input Sample... | 0.801625 | 0.822795 |
from rllab.misc.instrument import VariantGenerator
from rllab import config
from rllab_maml.baselines.linear_feature_baseline import LinearFeatureBaseline
from rllab_maml.baselines.gaussian_mlp_baseline import GaussianMLPBaseline
from sandbox.ours.envs.normalized_env import normalize
from sandbox.ours.envs.base import ... | experiments/run_scripts/gpu-mb-mpo-train.py | from rllab.misc.instrument import VariantGenerator
from rllab import config
from rllab_maml.baselines.linear_feature_baseline import LinearFeatureBaseline
from rllab_maml.baselines.gaussian_mlp_baseline import GaussianMLPBaseline
from sandbox.ours.envs.normalized_env import normalize
from sandbox.ours.envs.base import ... | 0.478041 | 0.212355 |
import datetime
import time
class EarthquakeUSGS:
"""
@brief Class that holds earthquake data records.
Class that hold earthquake data, for use with USGIS retrieved quake data.
BRIDGES uses scripts to
continually monitor USGIS site (tweets) and retrieve the latest
quake data for use in stude... | bridges/data_src_dependent/earthquake_usgs.py | import datetime
import time
class EarthquakeUSGS:
"""
@brief Class that holds earthquake data records.
Class that hold earthquake data, for use with USGIS retrieved quake data.
BRIDGES uses scripts to
continually monitor USGIS site (tweets) and retrieve the latest
quake data for use in stude... | 0.9024 | 0.476092 |
import yfinance as yf
import matplotlib.pyplot as plt
import collections
import pandas as pd
import numpy as np
import cvxpy as cp
import efficient_frontier
import param_estimator
import backtest
import objective_functions
def port_opt(stock_picks, weight_constraints, control, trade_horizon, cardinality, target_retu... | business_logic/portfolio_opt_front_end.py | import yfinance as yf
import matplotlib.pyplot as plt
import collections
import pandas as pd
import numpy as np
import cvxpy as cp
import efficient_frontier
import param_estimator
import backtest
import objective_functions
def port_opt(stock_picks, weight_constraints, control, trade_horizon, cardinality, target_retu... | 0.465387 | 0.425486 |
import os
import time
import queue
import demomgr.constants as CNST
from demomgr.filterlogic import process_filterstring, FILTERFLAGS
from demomgr.helpers import readdemoheader
from demomgr.threads.read_folder import ThreadReadFolder
from demomgr.threads._threadsig import THREADSIG
from demomgr.threads._base import _S... | demomgr/threads/filter.py | import os
import time
import queue
import demomgr.constants as CNST
from demomgr.filterlogic import process_filterstring, FILTERFLAGS
from demomgr.helpers import readdemoheader
from demomgr.threads.read_folder import ThreadReadFolder
from demomgr.threads._threadsig import THREADSIG
from demomgr.threads._base import _S... | 0.183594 | 0.10393 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas
from pandas.api.types import (is_scalar, is_list_like, is_bool)
from pandas.core.dtypes.common import is_integer
from pandas.core.indexing import IndexingError
import numpy as np
import ray
from ... | modin/pandas/indexing.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas
from pandas.api.types import (is_scalar, is_list_like, is_bool)
from pandas.core.dtypes.common import is_integer
from pandas.core.indexing import IndexingError
import numpy as np
import ray
from ... | 0.744378 | 0.319871 |
import urlparse
import logging
from django.views.generic import FormView, TemplateView
from django.contrib import auth
from django.contrib.auth import REDIRECT_FIELD_NAME, login
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponseGone
from django.utils.decorators import method_decor... | teamsurmandl/views.py | import urlparse
import logging
from django.views.generic import FormView, TemplateView
from django.contrib import auth
from django.contrib.auth import REDIRECT_FIELD_NAME, login
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect, HttpResponseGone
from django.utils.decorators import method_decor... | 0.493653 | 0.05151 |
import json
import os
import ipaddress
from platform import system
def clear():
if system() == "Windows":
os.system("cls")
else:
os.system("clear")
def get_settings():
with open("data/settings.json", "r", encoding="utf-8") as file:
return json.load(file)
def g... | Dscanner/data/functions.py | import json
import os
import ipaddress
from platform import system
def clear():
if system() == "Windows":
os.system("cls")
else:
os.system("clear")
def get_settings():
with open("data/settings.json", "r", encoding="utf-8") as file:
return json.load(file)
def g... | 0.110904 | 0.090053 |
import torch
import torch.nn as nn
import skimage
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
def conv_block(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, padding=1),
nn.BatchNorm2d(num_features=out_channels),
... | nets/zoo/brrnet_BE.py | import torch
import torch.nn as nn
import skimage
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
def conv_block(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, padding=1),
nn.BatchNorm2d(num_features=out_channels),
... | 0.939165 | 0.395981 |
import io
import requests
from bs4 import BeautifulSoup
from collections import OrderedDict
from requests_toolbelt.multipart.encoder import MultipartEncoder
from watchdogs.utils import Cast
from watchdogs.base.models import AllArgs, Common
from watchdogs.web.models import Response, WebFile
from watchdogs.web.models.R... | watchdogs/web/services/RequestResponseService.py |
import io
import requests
from bs4 import BeautifulSoup
from collections import OrderedDict
from requests_toolbelt.multipart.encoder import MultipartEncoder
from watchdogs.utils import Cast
from watchdogs.base.models import AllArgs, Common
from watchdogs.web.models import Response, WebFile
from watchdogs.web.models.R... | 0.371707 | 0.065785 |
def get_target_area(raw):
target_area = {}
raw = raw.replace("target area: x=", "").split(", y=")
target_area["x"] = [int(x) for x in raw[0].split("..")]
target_area["y"] = [int(x) for x in raw[1].split("..")]
return target_area
class Probe():
def __init__(self, x, y, target_area):
sel... | day17/puzzle.py | def get_target_area(raw):
target_area = {}
raw = raw.replace("target area: x=", "").split(", y=")
target_area["x"] = [int(x) for x in raw[0].split("..")]
target_area["y"] = [int(x) for x in raw[1].split("..")]
return target_area
class Probe():
def __init__(self, x, y, target_area):
sel... | 0.322419 | 0.430506 |
from tkinter import *
root= Tk()
root.title("Calculator")
result=0
f_num=0
Operator=""
def click(number):
current=e.get()
e.delete(0, END)
e.insert(0, str(current)+str(number))
def clear():
e.delete(0, END)
def first_num():
first_num=e.get()
global f_num
f_num=int(first_num)
e.delete... | Python Library/Simple Calculator GUI/calculator adv.py | from tkinter import *
root= Tk()
root.title("Calculator")
result=0
f_num=0
Operator=""
def click(number):
current=e.get()
e.delete(0, END)
e.insert(0, str(current)+str(number))
def clear():
e.delete(0, END)
def first_num():
first_num=e.get()
global f_num
f_num=int(first_num)
e.delete... | 0.28897 | 0.262548 |
import pickle
import time
from .transaction import Transaction
from blockchain.crypto_tools import hash, sign, generateKeys, b58encode, b58decode, text2PublicKey, verify
import pickle
from pathlib import Path
class Block():
def __init__(self, id = 0, ts = time.time(), coinbase:Transaction=Transaction(),transacti... | src/blockchain/data/block.py | import pickle
import time
from .transaction import Transaction
from blockchain.crypto_tools import hash, sign, generateKeys, b58encode, b58decode, text2PublicKey, verify
import pickle
from pathlib import Path
class Block():
def __init__(self, id = 0, ts = time.time(), coinbase:Transaction=Transaction(),transacti... | 0.511473 | 0.205336 |
import os
import subprocess
import sys
from importlib import import_module
from tensorflow.keras import models
import numpy as np
from snntoolbox.bin.utils import initialize_simulator
from snntoolbox.bin.utils import run_pipeline
from snntoolbox.conversion.utils import normalize_parameters
from snntoolbox.datasets.ut... | tests/core/test_models.py | import os
import subprocess
import sys
from importlib import import_module
from tensorflow.keras import models
import numpy as np
from snntoolbox.bin.utils import initialize_simulator
from snntoolbox.bin.utils import run_pipeline
from snntoolbox.conversion.utils import normalize_parameters
from snntoolbox.datasets.ut... | 0.496338 | 0.279208 |
import cv2
import mediapipe as mp
import math
from imutils.video import VideoStream
from imutils.video import FileVideoStream
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter
import collections
class PoseEstimator:
def __init__(self, window_size=8, smoothing_function=N... | code/pose_estimator.py | import cv2
import mediapipe as mp
import math
from imutils.video import VideoStream
from imutils.video import FileVideoStream
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter
import collections
class PoseEstimator:
def __init__(self, window_size=8, smoothing_function=N... | 0.466603 | 0.269596 |
import logging
from datetime import datetime
from datetime import timezone
from typing import cast
from typing import Dict
from typing import List
from typing import Optional
import aiohttp
from .credential_store import CredentialStore
from .exceptions import RenaultException
from .kamereon import enums
from .kamereo... | src/renault_api/renault_vehicle.py | import logging
from datetime import datetime
from datetime import timezone
from typing import cast
from typing import Dict
from typing import List
from typing import Optional
import aiohttp
from .credential_store import CredentialStore
from .exceptions import RenaultException
from .kamereon import enums
from .kamereo... | 0.827932 | 0.091463 |
from System.IO import *
from System.Drawing import *
from System.Runtime.Remoting import *
from System.Threading import *
from System.Windows.Forms import *
from System.Xml.Serialization import *
from System import *
from System.Collections.Generic import Dictionary
from DAQ.Environment import *
from DAQ import *
from... | SympatheticScripts/SPImagingFromMOT.py | from System.IO import *
from System.Drawing import *
from System.Runtime.Remoting import *
from System.Threading import *
from System.Windows.Forms import *
from System.Xml.Serialization import *
from System import *
from System.Collections.Generic import Dictionary
from DAQ.Environment import *
from DAQ import *
from... | 0.101567 | 0.128197 |
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import numpy as np
from typing import Tuple
from privacy_evaluator.datasets.dataset import Dataset
class CIFAR10(Dataset):
"""CIFAR10 dataset class."""
TRAIN_SET_SIZE = 50000
TEST... | privacy_evaluator/datasets/cifar10.py | import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import numpy as np
from typing import Tuple
from privacy_evaluator.datasets.dataset import Dataset
class CIFAR10(Dataset):
"""CIFAR10 dataset class."""
TRAIN_SET_SIZE = 50000
TEST... | 0.955079 | 0.784897 |
import datetime
from slack import WebClient
from slack.errors import SlackApiError
import ssl
import bench_cli.configuration as configuration
# ----------------------------------------------------------------------------------------------------------------------------------
# ----------------------------------------... | bench_cli/reporting.py |
import datetime
from slack import WebClient
from slack.errors import SlackApiError
import ssl
import bench_cli.configuration as configuration
# ----------------------------------------------------------------------------------------------------------------------------------
# ----------------------------------------... | 0.229363 | 0.131396 |
import torch
from torch import nn
import torch.nn.functional as F
from hparams import hparams as hp
class MocoLoss(nn.Module):
def __init__(self):
super(MocoLoss, self).__init__()
moco_model_path = hp.moco_model_path
print("Loading MOCO model from path: {}".format(moco_model_path))
... | criteria/moco_loss.py | import torch
from torch import nn
import torch.nn.functional as F
from hparams import hparams as hp
class MocoLoss(nn.Module):
def __init__(self):
super(MocoLoss, self).__init__()
moco_model_path = hp.moco_model_path
print("Loading MOCO model from path: {}".format(moco_model_path))
... | 0.920317 | 0.349477 |
import io
import json
import os
from json import load, dump, JSONDecodeError
from ctpbee.center import PositionModel
from ctpbee.constant import TradeData, PositionData, Direction, Offset, Exchange
class SinglePositionModel:
def __init__(self, local_symbol):
self.local_symbol = local_symbol
# ... | ctpbee/data_handle/level_position.py | import io
import json
import os
from json import load, dump, JSONDecodeError
from ctpbee.center import PositionModel
from ctpbee.constant import TradeData, PositionData, Direction, Offset, Exchange
class SinglePositionModel:
def __init__(self, local_symbol):
self.local_symbol = local_symbol
# ... | 0.430387 | 0.257342 |
from ..mapping import MappedArray, AccessType
from ..indexing import is_fullslice, split_operation, slicer_sub2ind, invert_slice
from .. import volutils
from ..readers import reader_classes
from .metadata import ome_zooms, parse_unit
from nitorch.spatial import affine_default
from nitorch.core import pyutils, dtypes
fr... | nitorch/io/tiff/array.py | from ..mapping import MappedArray, AccessType
from ..indexing import is_fullslice, split_operation, slicer_sub2ind, invert_slice
from .. import volutils
from ..readers import reader_classes
from .metadata import ome_zooms, parse_unit
from nitorch.spatial import affine_default
from nitorch.core import pyutils, dtypes
fr... | 0.752104 | 0.567637 |
from marinetrafficapi.models import Model
from marinetrafficapi.fields import NumberField, TextField, RealNumberField
class PredictiveArrivals(Model):
"""Receive a prediction of the vessels
likely to arrive to a specific port."""
mmsi = NumberField(index='MMSI',
desc="Maritime Mobi... | marinetrafficapi/voyage_info/VI05_predictive_arrivals/models.py | from marinetrafficapi.models import Model
from marinetrafficapi.fields import NumberField, TextField, RealNumberField
class PredictiveArrivals(Model):
"""Receive a prediction of the vessels
likely to arrive to a specific port."""
mmsi = NumberField(index='MMSI',
desc="Maritime Mobi... | 0.765155 | 0.438364 |
from fcn.config import cfg
from gt_synthesize_layer.minibatch import get_minibatch
import numpy as np
import cv2
from utils.blob import pad_im
import os
import cPickle
import scipy.io
class GtSynthesizeLayer(object):
"""FCN data layer used for training."""
def __init__(self, roidb, roidb_val, num_classes, ext... | lib/gt_synthesize_layer/layer.py | from fcn.config import cfg
from gt_synthesize_layer.minibatch import get_minibatch
import numpy as np
import cv2
from utils.blob import pad_im
import os
import cPickle
import scipy.io
class GtSynthesizeLayer(object):
"""FCN data layer used for training."""
def __init__(self, roidb, roidb_val, num_classes, ext... | 0.691602 | 0.185523 |
from typing import Set
import argparse
import os
import json
import glob
from utils.utils import load_images_map
def is_trajectory_valid(trajectory, images_map):
"""Check that a trajectory has associated images.
"""
# TODO: add min count instead?
for frame_index, bbs in enumerate(trajectory["bbs"], st... | facerec/merge_shards.py | from typing import Set
import argparse
import os
import json
import glob
from utils.utils import load_images_map
def is_trajectory_valid(trajectory, images_map):
"""Check that a trajectory has associated images.
"""
# TODO: add min count instead?
for frame_index, bbs in enumerate(trajectory["bbs"], st... | 0.492188 | 0.409929 |
import pyrosim.pyrosim as pyrosim
import random
def Create_World():
x,y,z = 1,1,1
pyrosim.Start_SDF("world.sdf")
pyrosim.Send_Cube(name="Box", pos=[2,2,0.5] , size=[x,y,z])
pyrosim.End()
def Generate_Body():
# x,y,z = 1,1,1
# pyrosim.Start_URDF("body.urdf")
# pyrosim.Send_Cube(name="Torso... | generate.py | import pyrosim.pyrosim as pyrosim
import random
def Create_World():
x,y,z = 1,1,1
pyrosim.Start_SDF("world.sdf")
pyrosim.Send_Cube(name="Box", pos=[2,2,0.5] , size=[x,y,z])
pyrosim.End()
def Generate_Body():
# x,y,z = 1,1,1
# pyrosim.Start_URDF("body.urdf")
# pyrosim.Send_Cube(name="Torso... | 0.406037 | 0.424352 |
class MemObject:
'''memcached 关系对象
'''
def __init__(self,name,mc):
'''
@param name: str 对象的名称
@param _lock: int 对象锁 为1时表示对象被锁定无法进行修改
'''
self._client = mc
self._name = name
self._lock = 0
def produceKey(self,keyname):
'''重新生成... | firefly/dbentrust/memobject.py | class MemObject:
'''memcached 关系对象
'''
def __init__(self,name,mc):
'''
@param name: str 对象的名称
@param _lock: int 对象锁 为1时表示对象被锁定无法进行修改
'''
self._client = mc
self._name = name
self._lock = 0
def produceKey(self,keyname):
'''重新生成... | 0.320183 | 0.14919 |
from __future__ import annotations
import traceback
from datetime import datetime
from typing import TYPE_CHECKING, List
from fabric_mb.message_bus.messages.lease_reservation_avro import LeaseReservationAvro
from fabric_mb.message_bus.messages.result_delegation_avro import ResultDelegationAvro
from fabric_mb.message_... | fabric_cf/actor/core/manage/client_actor_management_object_helper.py | from __future__ import annotations
import traceback
from datetime import datetime
from typing import TYPE_CHECKING, List
from fabric_mb.message_bus.messages.lease_reservation_avro import LeaseReservationAvro
from fabric_mb.message_bus.messages.result_delegation_avro import ResultDelegationAvro
from fabric_mb.message_... | 0.740644 | 0.054199 |
import unittest
from extensions.middle.GroupNorm import GroupNormToMVN
from mo.front.common.partial_infer.utils import float_array, int64_array
from mo.utils.ir_engine.compare_graphs import compare_graphs
from mo.utils.unittest.graph import build_graph, result, build_graph_with_edge_attrs, connect, \
regular_op_wi... | model-optimizer/extensions/middle/GroupNorm_test.py | import unittest
from extensions.middle.GroupNorm import GroupNormToMVN
from mo.front.common.partial_infer.utils import float_array, int64_array
from mo.utils.ir_engine.compare_graphs import compare_graphs
from mo.utils.unittest.graph import build_graph, result, build_graph_with_edge_attrs, connect, \
regular_op_wi... | 0.634543 | 0.493042 |
class MovieData():
""" This class handle movie's data information """
def __init__(self):
self.get_movie_data()
def get_movie_data(self):
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
return (["2h 34 min", VALID_RATINGS[3], "Crime, Drama","1994",
"Pulp... | movie-trailler/movie_data.py | class MovieData():
""" This class handle movie's data information """
def __init__(self):
self.get_movie_data()
def get_movie_data(self):
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
return (["2h 34 min", VALID_RATINGS[3], "Crime, Drama","1994",
"Pulp... | 0.507324 | 0.542924 |
import logging
import struct
import shutil
from pathlib import Path
from typing import Iterable, List
import requests
from dacite import from_dict
from nozomi.data import Post
from nozomi.exceptions import InvalidTagFormat, InvalidUrlFormat
from nozomi.helpers import sanitize_tag, create_tag_filepath, create_post_fi... | nozomi/api.py |
import logging
import struct
import shutil
from pathlib import Path
from typing import Iterable, List
import requests
from dacite import from_dict
from nozomi.data import Post
from nozomi.exceptions import InvalidTagFormat, InvalidUrlFormat
from nozomi.helpers import sanitize_tag, create_tag_filepath, create_post_fi... | 0.708818 | 0.226228 |
import os
import sys
import time
import math
import torch
import copy
import torch.nn as nn
import torch.nn.init as init
class MovingMaximum(object):
def __init__(self):
self.data = [] # data[i] is the maximum val in data[0:i+1]
self.max = 0.0
def push(self, current_data):
if len(self... | cifar10/utils.py | import os
import sys
import time
import math
import torch
import copy
import torch.nn as nn
import torch.nn.init as init
class MovingMaximum(object):
def __init__(self):
self.data = [] # data[i] is the maximum val in data[0:i+1]
self.max = 0.0
def push(self, current_data):
if len(self... | 0.440951 | 0.237101 |
import pyparsing as pp
from functools import lru_cache
def paren_exp(keyword, contents):
return pp.Keyword(keyword)('op') + pp.Suppress('(') + contents + pp.Suppress(')')
def cfg_exp():
option = pp.Word(pp.alphanums + '_')('option')
exp = pp.Forward()
assign = (option + pp.Suppress("=") + pp.QuotedS... | rustcfg/__init__.py |
import pyparsing as pp
from functools import lru_cache
def paren_exp(keyword, contents):
return pp.Keyword(keyword)('op') + pp.Suppress('(') + contents + pp.Suppress(')')
def cfg_exp():
option = pp.Word(pp.alphanums + '_')('option')
exp = pp.Forward()
assign = (option + pp.Suppress("=") + pp.QuotedS... | 0.646014 | 0.239416 |
# type annotations
from __future__ import annotations
from typing import Optional
# standard libs
import logging
from threading import Thread
from queue import Queue, Empty
# internal libs
from .database.message import Message, publish
# initialize module level logger
log = logging.getLogger(__name__)
# shared pa... | streamkit/publisher.py | # type annotations
from __future__ import annotations
from typing import Optional
# standard libs
import logging
from threading import Thread
from queue import Queue, Empty
# internal libs
from .database.message import Message, publish
# initialize module level logger
log = logging.getLogger(__name__)
# shared pa... | 0.942823 | 0.158858 |
from inspect import signature, Parameter
import numpy as np
from scipy.stats import rankdata
from sklearn.utils.validation import check_array, _is_arraylike
from ...base import (
MultiAnnotatorPoolQueryStrategy,
SingleAnnotatorPoolQueryStrategy,
)
from ...utils import (
rand_argmax,
check_type,
MI... | skactiveml/pool/multiannotator/_wrapper.py | from inspect import signature, Parameter
import numpy as np
from scipy.stats import rankdata
from sklearn.utils.validation import check_array, _is_arraylike
from ...base import (
MultiAnnotatorPoolQueryStrategy,
SingleAnnotatorPoolQueryStrategy,
)
from ...utils import (
rand_argmax,
check_type,
MI... | 0.946578 | 0.631651 |
import pytest
from homeassistant.components.binary_sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.modbus.const import (
CALL_TYPE_COIL,
CALL_TYPE_DISCRETE,
CONF_BINARY_SENSORS,
CONF_INPUT_TYPE,
CONF_INPUTS,
)
from homeassistant.const import (
CONF_ADDRESS,
CONF_DEVICE_C... | tests/components/modbus/test_modbus_binary_sensor.py | import pytest
from homeassistant.components.binary_sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.modbus.const import (
CALL_TYPE_COIL,
CALL_TYPE_DISCRETE,
CONF_BINARY_SENSORS,
CONF_INPUT_TYPE,
CONF_INPUTS,
)
from homeassistant.const import (
CONF_ADDRESS,
CONF_DEVICE_C... | 0.507812 | 0.332635 |
import os
#os.add_dll_directory(os.path.join(os.environ['CUDA_PATH'], 'bin'))
import dlib
import cv2
import numpy as np
from .IDetect import IDetect
from .core import Core
class FaceDetectCV2(Core, IDetect):
def __init__(self, source, method):
super().__init__(source = source)
self... | PROJECT_0000/faceLib/faceDetectCV2.py | import os
#os.add_dll_directory(os.path.join(os.environ['CUDA_PATH'], 'bin'))
import dlib
import cv2
import numpy as np
from .IDetect import IDetect
from .core import Core
class FaceDetectCV2(Core, IDetect):
def __init__(self, source, method):
super().__init__(source = source)
self... | 0.206574 | 0.087136 |
from inspect import isclass
from enum import Enum
from sqlalchemy import types
from pulsar.api import ImproperlyConfigured
class ScalarCoercible(object):
def _coerce(self, value):
raise NotImplementedError
def coercion_listener(self, target, value, oldvalue, initiator):
return self._coerce(... | odm/types/choice.py | from inspect import isclass
from enum import Enum
from sqlalchemy import types
from pulsar.api import ImproperlyConfigured
class ScalarCoercible(object):
def _coerce(self, value):
raise NotImplementedError
def coercion_listener(self, target, value, oldvalue, initiator):
return self._coerce(... | 0.848596 | 0.162945 |
from datetime import datetime
from datetime import timedelta
from datetime import tzinfo
from typing import Optional
from typing import TypeVar
from typing import overload
import pendulum
from pendulum.helpers import local_time
from pendulum.helpers import timestamp
from pendulum.utils._compat import _HAS_... | buildroot-external/rootfs-overlay/usr/lib/python3.8/site-packages/pendulum/tz/timezone.py | from datetime import datetime
from datetime import timedelta
from datetime import tzinfo
from typing import Optional
from typing import TypeVar
from typing import overload
import pendulum
from pendulum.helpers import local_time
from pendulum.helpers import timestamp
from pendulum.utils._compat import _HAS_... | 0.860589 | 0.139162 |
from directx.types import *
from directx.d3d import *
#********************************************************************
# Typedefs and constants
#********************************************************************
try:
#SDK April 2006 - you can change the
#.dll to a another one if you know what you are... | directx/d3dx.py | from directx.types import *
from directx.d3d import *
#********************************************************************
# Typedefs and constants
#********************************************************************
try:
#SDK April 2006 - you can change the
#.dll to a another one if you know what you are... | 0.169612 | 0.202818 |
import sys
import argparse
from pathlib import Path
import time
import pyperclip
from collections import defaultdict
from math import prod
def out(str):
print(str)
pyperclip.copy(str)
def read_positions(filename):
p = {}
with open(filename) as fin:
items = fin.readline().split(" ")
p[... | day21.py | import sys
import argparse
from pathlib import Path
import time
import pyperclip
from collections import defaultdict
from math import prod
def out(str):
print(str)
pyperclip.copy(str)
def read_positions(filename):
p = {}
with open(filename) as fin:
items = fin.readline().split(" ")
p[... | 0.158044 | 0.349449 |
import math
import torch.nn.functional as F
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch
import numpy as np
from torch.utils import data
from torchvision import transforms as T
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://dow... | model_agecomparison.py | import math
import torch.nn.functional as F
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch
import numpy as np
from torch.utils import data
from torchvision import transforms as T
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://dow... | 0.873916 | 0.582907 |
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | rero_grpc/text_to_speech_pb2.py | """Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | 0.257859 | 0.067332 |
import unittest
import tempfile
import shutil
import os
import io
from format_templates.format_templates import replace_iter, find_iters, render
class TestFormatting(unittest.TestCase):
def setUp(self):
self.data = {
"name": "World",
"numbers": xrange(1,5),
"nested": {... | tests/__init__.py | import unittest
import tempfile
import shutil
import os
import io
from format_templates.format_templates import replace_iter, find_iters, render
class TestFormatting(unittest.TestCase):
def setUp(self):
self.data = {
"name": "World",
"numbers": xrange(1,5),
"nested": {... | 0.315736 | 0.414543 |
import io
from setuptools import setup, find_packages
def readme():
with io.open('README.md', encoding='utf-8') as f:
return f.read()
def requirements(filename):
reqs = list()
with io.open(filename, encoding='utf-8') as f:
for line in f.readlines():
reqs.append(line.strip())... | {{cookiecutter.repo_name}}/setup.py |
import io
from setuptools import setup, find_packages
def readme():
with io.open('README.md', encoding='utf-8') as f:
return f.read()
def requirements(filename):
reqs = list()
with io.open(filename, encoding='utf-8') as f:
for line in f.readlines():
reqs.append(line.strip())... | 0.414069 | 0.147432 |
from conans import DEFAULT_REVISION_V1
from conans.model.ref import PackageReference
class CommonService(object):
def _get_latest_pref(self, pref):
ref = self._get_latest_ref(pref.ref)
pref = PackageReference(ref, pref.id)
tmp = self._server_store.get_last_package_revision(pref)
i... | conans/server/service/common/common.py | from conans import DEFAULT_REVISION_V1
from conans.model.ref import PackageReference
class CommonService(object):
def _get_latest_pref(self, pref):
ref = self._get_latest_ref(pref.ref)
pref = PackageReference(ref, pref.id)
tmp = self._server_store.get_last_package_revision(pref)
i... | 0.376967 | 0.115511 |
from __future__ import absolute_import, with_statement
import os
import logging
import functools
import hashlib
from assetman.tools import get_shard_from_list, _utf8
from assetman.manifest import Manifest
class AssetManager(object):
"""AssetManager attempts to provide easy-to-use asset management and
compila... | assetman/managers.py | from __future__ import absolute_import, with_statement
import os
import logging
import functools
import hashlib
from assetman.tools import get_shard_from_list, _utf8
from assetman.manifest import Manifest
class AssetManager(object):
"""AssetManager attempts to provide easy-to-use asset management and
compila... | 0.814607 | 0.194062 |
import numpy as np
import abc
def action(f):
def wrapper(*args):
result = f(*args)
world = args[0]
world.check_n_satisfied()
if result is None:
done = False
reward = 0
stats = world.stats
if world.interface.time_out:
... | vat/envs/base_world.py | import numpy as np
import abc
def action(f):
def wrapper(*args):
result = f(*args)
world = args[0]
world.check_n_satisfied()
if result is None:
done = False
reward = 0
stats = world.stats
if world.interface.time_out:
... | 0.64232 | 0.310028 |
import json
from urllib.parse import quote_plus as url_encode
import csv
from elsapy.elsclient import ElsClient
con_file = open("config.json")
config = json.load(con_file)
con_file.close()
## Initialize client
client = ElsClient(config['apikey']['mark'])
codes = ['ALL','ABS','AF-ID','AFFIL','AFFILCITY','AFFILCOUNTRY'... | findResultsCount.py | import json
from urllib.parse import quote_plus as url_encode
import csv
from elsapy.elsclient import ElsClient
con_file = open("config.json")
config = json.load(con_file)
con_file.close()
## Initialize client
client = ElsClient(config['apikey']['mark'])
codes = ['ALL','ABS','AF-ID','AFFIL','AFFILCITY','AFFILCOUNTRY'... | 0.138404 | 0.053403 |
import requests
import datetime as dt
bcb_urls = {
'IPCA-Serviços': 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.10844/dados?formato=json',
'IPCA-Bens não-duráveis': 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.10841/dados?formato=json',
'IPCA-Bens semi-duráveis': 'https://api.bcb.gov.br/dados/serie/bc... | inflationtools/main.py | import requests
import datetime as dt
bcb_urls = {
'IPCA-Serviços': 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.10844/dados?formato=json',
'IPCA-Bens não-duráveis': 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.10841/dados?formato=json',
'IPCA-Bens semi-duráveis': 'https://api.bcb.gov.br/dados/serie/bc... | 0.671255 | 0.533762 |
from trac.config import IntOption
from trac.core import Component, implements
from trac.env import ISystemInfoProvider
from trac.util import get_pkginfo
from tracspamfilter.api import IFilterStrategy, N_
from spambayes.hammie import Hammie
from spambayes.storage import SQLClassifier
class BayesianFilterS... | files/spam-filter/tracspamfilter/filters/bayes.py |
from trac.config import IntOption
from trac.core import Component, implements
from trac.env import ISystemInfoProvider
from trac.util import get_pkginfo
from tracspamfilter.api import IFilterStrategy, N_
from spambayes.hammie import Hammie
from spambayes.storage import SQLClassifier
class BayesianFilterS... | 0.378229 | 0.13852 |
import pygame
import logging
import copy
import time
import sys
from board import SudokuBoard
from tile import TileText
DEFAULT_BG_COL = (255, 255, 255)
MAX_BACKUP_LENGTH = 100
class Button(object):
DEFAULT_COL = (0, 0, 0)
DEFAULT_TEXTCOL = (0, 0, 0)
def __init__(self, text):
self.text = text
... | src/main.py | import pygame
import logging
import copy
import time
import sys
from board import SudokuBoard
from tile import TileText
DEFAULT_BG_COL = (255, 255, 255)
MAX_BACKUP_LENGTH = 100
class Button(object):
DEFAULT_COL = (0, 0, 0)
DEFAULT_TEXTCOL = (0, 0, 0)
def __init__(self, text):
self.text = text
... | 0.318273 | 0.170715 |
import logging
from pants.backend.python.goals.setup_py import SetupKwargs, SetupKwargsRequest
from pants.engine.fs import DigestContents, GlobMatchErrorBehavior, PathGlobs
from pants.engine.rules import Get, collect_rules, rule
from pants.engine.target import Target
from pants.engine.unions import UnionRule
logger =... | pants-plugins/grapl_setup_py/grapl_setupargs.py | import logging
from pants.backend.python.goals.setup_py import SetupKwargs, SetupKwargsRequest
from pants.engine.fs import DigestContents, GlobMatchErrorBehavior, PathGlobs
from pants.engine.rules import Get, collect_rules, rule
from pants.engine.target import Target
from pants.engine.unions import UnionRule
logger =... | 0.822296 | 0.265333 |
import copy
import sys
from geometry_msgs.msg import Pose, Point, Quaternion
import moveit_commander
import intera_interface
import rospy
from tf import TransformListener
from copy import deepcopy
from get_task_srv.srv import get_task
class Robot(object):
def __init__(self, limb='right', tip_name="right_gripper_... | docker/sawyer-robot/internal/temp/data_collection/run_toy_task.py |
import copy
import sys
from geometry_msgs.msg import Pose, Point, Quaternion
import moveit_commander
import intera_interface
import rospy
from tf import TransformListener
from copy import deepcopy
from get_task_srv.srv import get_task
class Robot(object):
def __init__(self, limb='right', tip_name="right_gripper_... | 0.38827 | 0.211824 |
"""Module to talk to EtherpadLite API."""
import json
import urllib
import urllib2
class APIClient:
"""Client to talk to EtherpadLite API."""
API_VERSION = "1.2.8"
CODE_OK = 0
CODE_INVALID_PARAMETERS = 1
CODE_INTERNAL_ERROR = 2
CODE_INVALID_FUNCTION = 3
CODE_INVALID_API_KEY = 4
TIMEOU... | src/py_etherpad/APIClient.py | """Module to talk to EtherpadLite API."""
import json
import urllib
import urllib2
class APIClient:
"""Client to talk to EtherpadLite API."""
API_VERSION = "1.2.8"
CODE_OK = 0
CODE_INVALID_PARAMETERS = 1
CODE_INTERNAL_ERROR = 2
CODE_INVALID_FUNCTION = 3
CODE_INVALID_API_KEY = 4
TIMEOU... | 0.630912 | 0.249853 |
from typing import Awaitable, Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from cripy import ConnectionType, SessionType
__all__ = ["Fetch"]
class Fetch:
"""
A domain for letting clients substitute browser's network layer with client code.
Domain Dependencies:
... | cripy/protocol/fetch.py | from typing import Awaitable, Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from cripy import ConnectionType, SessionType
__all__ = ["Fetch"]
class Fetch:
"""
A domain for letting clients substitute browser's network layer with client code.
Domain Dependencies:
... | 0.83762 | 0.255828 |
from functools import partial
from typing import NamedTuple
import jax
import jax.numpy as jnp
import jax.random as jrandom
from jax.scipy.special import logsumexp
from slzero.dataset import Batch, BatchStreamer
from slzero.decoding import viterbi
class Params(NamedTuple):
weight: jnp.ndarray
transitions: j... | slzero/crf/functions.py | from functools import partial
from typing import NamedTuple
import jax
import jax.numpy as jnp
import jax.random as jrandom
from jax.scipy.special import logsumexp
from slzero.dataset import Batch, BatchStreamer
from slzero.decoding import viterbi
class Params(NamedTuple):
weight: jnp.ndarray
transitions: j... | 0.915235 | 0.681528 |
import unittest
import os,sys
import pickle
from rdkit import rdBase
from rdkit import Chem
from rdkit.Chem import rdChemReactions, AllChem
from rdkit import Geometry
from rdkit import RDConfig
import itertools, time
test_data = [("good", '''$RXN
ISIS 052820091627
2 1
$MOL
-ISIS- 05280916272D
... | Code/GraphMol/ChemReactions/Wrap/testSanitize.py |
import unittest
import os,sys
import pickle
from rdkit import rdBase
from rdkit import Chem
from rdkit.Chem import rdChemReactions, AllChem
from rdkit import Geometry
from rdkit import RDConfig
import itertools, time
test_data = [("good", '''$RXN
ISIS 052820091627
2 1
$MOL
-ISIS- 05280916272D
... | 0.201853 | 0.169543 |
import argparse
import pandas as pd
from dpmModule.character.characterKernel import ItemedCharacter, JobGenerator
from dpmModule.character.characterTemplate import get_template_generator
from dpmModule.jobs import jobMap, weaponList
from dpmModule.kernel import core
from dpmModule.status.ability import Ability_grade
... | statistics/optimization_hint.py | import argparse
import pandas as pd
from dpmModule.character.characterKernel import ItemedCharacter, JobGenerator
from dpmModule.character.characterTemplate import get_template_generator
from dpmModule.jobs import jobMap, weaponList
from dpmModule.kernel import core
from dpmModule.status.ability import Ability_grade
... | 0.562657 | 0.129761 |
import os
def add_slash(m):
"""
Helper function that appends a / if one does not exist.
Prameters:
m: The string to append to.
"""
if m[-1] != "/":
return m + "/"
else:
return m
class Directory:
path_string = None
def __init__(self, in_string, ignore=False):
... | ProQuest2Bepress/paths.py | import os
def add_slash(m):
"""
Helper function that appends a / if one does not exist.
Prameters:
m: The string to append to.
"""
if m[-1] != "/":
return m + "/"
else:
return m
class Directory:
path_string = None
def __init__(self, in_string, ignore=False):
... | 0.40439 | 0.197232 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import threading
from tensorflow.python.framework import errors
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.profiler.internal import _pywrap_profiler
... | tensorflow/python/profiler/profiler_v2.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import threading
from tensorflow.python.framework import errors
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.profiler.internal import _pywrap_profiler
... | 0.874104 | 0.365457 |
from __future__ import absolute_import, unicode_literals
import logging
from rest_framework import viewsets, serializers, status
from rest_framework.response import Response
from django.contrib.sites.models import Site
from dbaas.middleware import UserMiddleware
from logical import models
from logical.forms import Da... | dbaas/api/database.py | from __future__ import absolute_import, unicode_literals
import logging
from rest_framework import viewsets, serializers, status
from rest_framework.response import Response
from django.contrib.sites.models import Site
from dbaas.middleware import UserMiddleware
from logical import models
from logical.forms import Da... | 0.637595 | 0.09122 |
import argparse
import logging
import logging.handlers
import time
import json
import paho.mqtt.client as mqtt
import eiscp
version="0.7"
parser = argparse.ArgumentParser(description='Bridge between onkyo-eiscp and MQTT')
parser.add_argument('--mqtt-host', default='localhost', help='MQTT server address. Defaults to ... | onkyo2mqtt.py |
import argparse
import logging
import logging.handlers
import time
import json
import paho.mqtt.client as mqtt
import eiscp
version="0.7"
parser = argparse.ArgumentParser(description='Bridge between onkyo-eiscp and MQTT')
parser.add_argument('--mqtt-host', default='localhost', help='MQTT server address. Defaults to ... | 0.163679 | 0.058319 |
from chainer import cuda
from chainer import functions
from chainer import gradient_check
import numpy
import pytest
from chainer_chemistry.config import MAX_ATOMIC_NUM
from chainer_chemistry.links.readout.general_readout import GeneralReadout
from chainer_chemistry.utils.permutation import permute_node
atom_size = 5... | tests/links_tests/readout_tests/test_general_readout.py | from chainer import cuda
from chainer import functions
from chainer import gradient_check
import numpy
import pytest
from chainer_chemistry.config import MAX_ATOMIC_NUM
from chainer_chemistry.links.readout.general_readout import GeneralReadout
from chainer_chemistry.utils.permutation import permute_node
atom_size = 5... | 0.457137 | 0.585931 |
import os
import json
from math import pow,log2,ceil
def ordering(wantedlist,inital_penalty = 0):
if wantedlist == []:
return "Cannot enchant: no enchantment given"
sortedlist, numlist = enchantment_split(wantedlist)
total_step = int(log2(len(sortedlist)))+1
penalty = inita... | ordering.py | import os
import json
from math import pow,log2,ceil
def ordering(wantedlist,inital_penalty = 0):
if wantedlist == []:
return "Cannot enchant: no enchantment given"
sortedlist, numlist = enchantment_split(wantedlist)
total_step = int(log2(len(sortedlist)))+1
penalty = inita... | 0.113113 | 0.229503 |
import concurrent.futures
import sys
import threading
from concurrent.futures import ThreadPoolExecutor
import tinify
import os
# tinify.key = "<KEY>"
total_pic_old_size = 0
total_pic_new_size = 0
total_pic_num = 0
# all thread pool tasks futures
futures = []
# tinypng API key cache file
API_KEY_CACHE_PATH = "key_c... | main.py | import concurrent.futures
import sys
import threading
from concurrent.futures import ThreadPoolExecutor
import tinify
import os
# tinify.key = "<KEY>"
total_pic_old_size = 0
total_pic_new_size = 0
total_pic_num = 0
# all thread pool tasks futures
futures = []
# tinypng API key cache file
API_KEY_CACHE_PATH = "key_c... | 0.197832 | 0.079496 |