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 .item import Value, Item, ANY, make_item ___all__ = [ "Items", "make_items", ] def _compute_size(items): size = 0 for item in items: if isinstance(item, Item): isize = item.size if isize is None: return None else: size +...
src/sequel/items.py
from .item import Value, Item, ANY, make_item ___all__ = [ "Items", "make_items", ] def _compute_size(items): size = 0 for item in items: if isinstance(item, Item): isize = item.size if isize is None: return None else: size +...
0.505371
0.222299
from collections import OrderedDict from ..mixins.ondemand import ext as _ext # ================== def timeouts(env, fmt): timeouts = env['timeouts'] connect_to = int(timeouts['connect']) read_to = int(timeouts['read']) total_to = int(timeouts['total']) if fmt == 'requests': return (con...
futoin/cid/util/configutil.py
from collections import OrderedDict from ..mixins.ondemand import ext as _ext # ================== def timeouts(env, fmt): timeouts = env['timeouts'] connect_to = int(timeouts['connect']) read_to = int(timeouts['read']) total_to = int(timeouts['total']) if fmt == 'requests': return (con...
0.460046
0.246389
import json from collections import OrderedDict import pprint s = r'{"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}' print(s) # {"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]} d = json.loads(s) pprint.pprint(d, width=40) # {'A': {'i': 1, 'j': 2...
notebook/json_example.py
import json from collections import OrderedDict import pprint s = r'{"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}' print(s) # {"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]} d = json.loads(s) pprint.pprint(d, width=40) # {'A': {'i': 1, 'j': 2...
0.058993
0.354754
import logging import os import re from google.appengine.ext import ndb from gae_libs import appengine_util from libs import test_name_util from libs import time_util from model.flake.flake import Flake from model.flake.flake import FlakeIssue from model.test_inventory import LuciTest from services import bigquery_h...
appengine/findit/services/disabled_tests/detect_disabled_tests.py
import logging import os import re from google.appengine.ext import ndb from gae_libs import appengine_util from libs import test_name_util from libs import time_util from model.flake.flake import Flake from model.flake.flake import FlakeIssue from model.test_inventory import LuciTest from services import bigquery_h...
0.63341
0.29724
from math import sin, cos, radians, degrees, acos from django.views import generic from django.shortcuts import render from django.utils import timezone from django.utils.decorators import method_decorator from ..models import Event, User, NotificationEvent, UserNotification from ..forms import EventForm from .deco...
core/views/map_view.py
from math import sin, cos, radians, degrees, acos from django.views import generic from django.shortcuts import render from django.utils import timezone from django.utils.decorators import method_decorator from ..models import Event, User, NotificationEvent, UserNotification from ..forms import EventForm from .deco...
0.527073
0.129485
from __future__ import absolute_import, division, print_function import sys import os import six import subprocess import json import pyuvdata from pyuvdata.data import DATA_PATH def test_get_gitinfo_file(): pyuvdata_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) git_file = os.path.join...
pyuvdata/tests/test_version.py
from __future__ import absolute_import, division, print_function import sys import os import six import subprocess import json import pyuvdata from pyuvdata.data import DATA_PATH def test_get_gitinfo_file(): pyuvdata_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) git_file = os.path.join...
0.377311
0.2083
from django.conf.urls import url from .api.address_book.groups import ( AdminAddressBookGroups, AdminAddressBookGroup ) from .api.group_libraries import AdminGroupLibraries, AdminGroupLibrary from .api.group_owned_libraries import ( AdminGroupOwnedLibraries, AdminGroupOwnedLibrary ) from .api.group_members im...
seahub/organizations/api_urls.py
from django.conf.urls import url from .api.address_book.groups import ( AdminAddressBookGroups, AdminAddressBookGroup ) from .api.group_libraries import AdminGroupLibraries, AdminGroupLibrary from .api.group_owned_libraries import ( AdminGroupOwnedLibraries, AdminGroupOwnedLibrary ) from .api.group_members im...
0.157234
0.041269
from ASRModel import ASRModel import os class HMM(ASRModel): # constructor def __init__(self, model_id: str): self.model_id = model_id @staticmethod def preprocess(audio_path): """ from an input path, load the single audio and return preprocessed audio which will be ...
HMM.py
from ASRModel import ASRModel import os class HMM(ASRModel): # constructor def __init__(self, model_id: str): self.model_id = model_id @staticmethod def preprocess(audio_path): """ from an input path, load the single audio and return preprocessed audio which will be ...
0.663887
0.449755
load("@io_bazel_rules_scala//scala:scala.bzl", upstream_scala_library = "scala_library", "scala_binary", "scala_test", "scala_repl") _plugins = ["@org_spire_math_kind_projector_2_11//jar:file"] def strict_scalacopts(): return [ "-Xfatal-warnings", "-Xfuture", "-Xlint", "-Xlint:unsound-match", ...
tools/scala.bzl
load("@io_bazel_rules_scala//scala:scala.bzl", upstream_scala_library = "scala_library", "scala_binary", "scala_test", "scala_repl") _plugins = ["@org_spire_math_kind_projector_2_11//jar:file"] def strict_scalacopts(): return [ "-Xfatal-warnings", "-Xfuture", "-Xlint", "-Xlint:unsound-match", ...
0.593256
0.235647
import cv2 as cv import numpy import hashlib import sys import os.path ColRange = 16 RowRange = 16 def hash(ID): hash_method = hashlib.sha256() hash_method.update(ID.encode('utf-8')) binary = [] temp = [] result = [] str = hash_method.hexdigest() for i in str: if i >= '0' and i <...
waterMark/image_watermark.py
import cv2 as cv import numpy import hashlib import sys import os.path ColRange = 16 RowRange = 16 def hash(ID): hash_method = hashlib.sha256() hash_method.update(ID.encode('utf-8')) binary = [] temp = [] result = [] str = hash_method.hexdigest() for i in str: if i >= '0' and i <...
0.151781
0.317638
from subprocess import Popen, PIPE, STDOUT import sys pomXml = """ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId...
mirror.py
from subprocess import Popen, PIPE, STDOUT import sys pomXml = """ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId...
0.2676
0.125039
import numpy as np import matplotlib.pyplot as plt class Environment(): def actions(self): raise NotImplementedError('Inheriting classes must override actions.') def step(self): raise NotImplementedError('Inheriting classes must override step') class BanditEnv(): def __init__(self, choic...
MultiarmedBandit/jupyterCode.py
import numpy as np import matplotlib.pyplot as plt class Environment(): def actions(self): raise NotImplementedError('Inheriting classes must override actions.') def step(self): raise NotImplementedError('Inheriting classes must override step') class BanditEnv(): def __init__(self, choic...
0.645567
0.461077
import argparse import numpy as np import pandas as pd import os import cv2 import tensorflow as tf from tensorflow.contrib.tensorboard.plugins.projector import \ visualize_embeddings, ProjectorConfig from os import path def build_args(parser): parser.add_argument( "--in-npy", type=str, ...
catalyst/contrib/scripts/project_embeddings.py
import argparse import numpy as np import pandas as pd import os import cv2 import tensorflow as tf from tensorflow.contrib.tensorboard.plugins.projector import \ visualize_embeddings, ProjectorConfig from os import path def build_args(parser): parser.add_argument( "--in-npy", type=str, ...
0.71413
0.251401
import pandas as pd import scanpy as sc import matplotlib.pyplot as plt import seaborn as sns import numpy as np import statsmodels.api as sm # Load count and alignment data and merge them into one annotated dataframe adata = sc.read_h5ad(r"E:\Dropbox\Dropbox\01_SST Project_daniel\033_PatchSeq CA3 SO\transcriptomics\P...
archive/transcriptomics_interneuron_markers_tony.py
import pandas as pd import scanpy as sc import matplotlib.pyplot as plt import seaborn as sns import numpy as np import statsmodels.api as sm # Load count and alignment data and merge them into one annotated dataframe adata = sc.read_h5ad(r"E:\Dropbox\Dropbox\01_SST Project_daniel\033_PatchSeq CA3 SO\transcriptomics\P...
0.622689
0.289775
import sys from B1B0_fuel import Fuel from B1B1_innergas import InnerGas from B1B2_clad import Clad #-------------------------------------------------------------------------------------------------- class FuelRod: #----------------------------------------------------------------------------------------...
B1B_fuelrod.py
import sys from B1B0_fuel import Fuel from B1B1_innergas import InnerGas from B1B2_clad import Clad #-------------------------------------------------------------------------------------------------- class FuelRod: #----------------------------------------------------------------------------------------...
0.125279
0.173148
from model.virtual_board import VirtualBoard from typing import Optional import numpy as np import chess import chess.svg import chess.pgn import chess.polyglot import chess.engine import time class Agent: """ Smart chess agent """ board: VirtualBoard = None __current_board_state: np.array = None __indexe...
src/model/agent.py
from model.virtual_board import VirtualBoard from typing import Optional import numpy as np import chess import chess.svg import chess.pgn import chess.polyglot import chess.engine import time class Agent: """ Smart chess agent """ board: VirtualBoard = None __current_board_state: np.array = None __indexe...
0.764188
0.204084
import datetime import mock from testify import TestCase, run, assert_equal, setup from testify.assertions import assert_in from tests.assertions import assert_raises from tron.config import config_utils, ConfigError, schema from tron.config.config_utils import build_list_of_type_validator, ConfigContext from tron.conf...
tests/config/config_utils_test.py
import datetime import mock from testify import TestCase, run, assert_equal, setup from testify.assertions import assert_in from tests.assertions import assert_raises from tron.config import config_utils, ConfigError, schema from tron.config.config_utils import build_list_of_type_validator, ConfigContext from tron.conf...
0.599954
0.507019
from google.protobuf import text_format from tensorflow.core.framework import op_def_pb2 from tensorflow.python.framework import op_def_registry from tensorflow.python.framework import ops from tensorflow.python.ops import op_def_library def reduce_join(inputs, reduction_indices, keep_dims=None, separator=None, ...
tensorflow/python/ops/gen_string_ops.py
from google.protobuf import text_format from tensorflow.core.framework import op_def_pb2 from tensorflow.python.framework import op_def_registry from tensorflow.python.framework import ops from tensorflow.python.ops import op_def_library def reduce_join(inputs, reduction_indices, keep_dims=None, separator=None, ...
0.888916
0.873593
import json import os from pattern import en as patten from stanza.server import CoreNLPClient from tqdm import tqdm # Map to pattern.en aliases # http://www.clips.ua.ac.be/pages/pattern-en#conjugation POS_TO_PATTERN = { 'vb': 'inf', # Infinitive 'vbp': '1sg', # non-3rd-person singular present ...
qa2sent.py
import json import os from pattern import en as patten from stanza.server import CoreNLPClient from tqdm import tqdm # Map to pattern.en aliases # http://www.clips.ua.ac.be/pages/pattern-en#conjugation POS_TO_PATTERN = { 'vb': 'inf', # Infinitive 'vbp': '1sg', # non-3rd-person singular present ...
0.554953
0.160167
import pprint import re import six class RenewalResourcesReq: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in...
huaweicloud-sdk-bss/huaweicloudsdkbss/v2/model/renewal_resources_req.py
import pprint import re import six class RenewalResourcesReq: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in...
0.547948
0.294478
from __future__ import absolute_import, division, print_function import mock try: import unittest2 as unittest except ImportError: import unittest import pkg_resources import begin class TestSubCommand(unittest.TestCase): def tearDown(self): for collector in begin.subcommands.COLLECTORS.values...
tests/test_subcommands.py
from __future__ import absolute_import, division, print_function import mock try: import unittest2 as unittest except ImportError: import unittest import pkg_resources import begin class TestSubCommand(unittest.TestCase): def tearDown(self): for collector in begin.subcommands.COLLECTORS.values...
0.506347
0.423637
import pytest from deeprelnn.factory import ClauseFactory, VariableFactory from deeprelnn.fol import Variable def test_variable_factory_initia_variables(): factory = VariableFactory([Variable("A"), Variable("B")]) assert factory.variables == set(["A", "B"]) factory = VariableFactory([Variable("A"), Vari...
deeprelnn/test/test_factory.py
import pytest from deeprelnn.factory import ClauseFactory, VariableFactory from deeprelnn.fol import Variable def test_variable_factory_initia_variables(): factory = VariableFactory([Variable("A"), Variable("B")]) assert factory.variables == set(["A", "B"]) factory = VariableFactory([Variable("A"), Vari...
0.674694
0.521167
__revision__="$Id: digest_md5.py 703 2010-04-03 17:45:43Z jajcus $" __docformat__="restructuredtext en" from binascii import b2a_hex import re import logging import hashlib from pyxmpp.sasl.core import ClientAuthenticator,ServerAuthenticator from pyxmpp.sasl.core import Failure,Response,Challenge,Success,Failure fr...
digsby/lib/pyxmpp/sasl/digest_md5.py
__revision__="$Id: digest_md5.py 703 2010-04-03 17:45:43Z jajcus $" __docformat__="restructuredtext en" from binascii import b2a_hex import re import logging import hashlib from pyxmpp.sasl.core import ClientAuthenticator,ServerAuthenticator from pyxmpp.sasl.core import Failure,Response,Challenge,Success,Failure fr...
0.811377
0.362405
import unittest import mock from azure.cli.core.util import CLIError class Test_Network_Unit_Tests(unittest.TestCase): def test_network_get_nic_ip_config(self): from azure.cli.command_modules.network.custom import _get_nic_ip_config # 1 - Test that if ip_configurations property is null, error...
src/command_modules/azure-cli-network/tests/test_network_unit_tests.py
import unittest import mock from azure.cli.core.util import CLIError class Test_Network_Unit_Tests(unittest.TestCase): def test_network_get_nic_ip_config(self): from azure.cli.command_modules.network.custom import _get_nic_ip_config # 1 - Test that if ip_configurations property is null, error...
0.642993
0.348174
def view(day, progress): linksP = [[60,'<NAME>','https://www.linkedin.com/posts/rodneydaut_failuretosuccess-linkedin30daysprint-activity-6886695645353127936-sRQx'],[61,'<NAME>','https://www.linkedin.com/posts/roseyhwang_coaching-business-entrepreneurship-activity-6886698097083224064-Lvdi']] linksC = [[60,'<NAM...
modal1.py
def view(day, progress): linksP = [[60,'<NAME>','https://www.linkedin.com/posts/rodneydaut_failuretosuccess-linkedin30daysprint-activity-6886695645353127936-sRQx'],[61,'<NAME>','https://www.linkedin.com/posts/roseyhwang_coaching-business-entrepreneurship-activity-6886698097083224064-Lvdi']] linksC = [[60,'<NAM...
0.21101
0.393036
__all__ = ['shuffle_data', 'train_test_split', 'decode_audio', 'get_label', 'get_waveform_and_label', 'get_spectrogram', 'get_spectrogram_and_label_id_digits', 'get_spectrogram_and_label_id_letters', 'get_spectrogram_and_label_id_mixed', 'preprocess_dataset'] # Cell from .fname_processing import...
car_speech/pipeline.py
__all__ = ['shuffle_data', 'train_test_split', 'decode_audio', 'get_label', 'get_waveform_and_label', 'get_spectrogram', 'get_spectrogram_and_label_id_digits', 'get_spectrogram_and_label_id_letters', 'get_spectrogram_and_label_id_mixed', 'preprocess_dataset'] # Cell from .fname_processing import...
0.571767
0.457258
from __future__ import absolute_import from __future__ import division from __future__ import print_function from deepcell.datasets import Dataset # pylint: disable=line-too-long #: nih_3t3 = Dataset( path='3T3_NIH.trks', url='https://deepcell-data.s3.amazonaws.com/tracked/3T3_NIH.trks', file_hash='0d90...
deepcell/datasets/tracked.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from deepcell.datasets import Dataset # pylint: disable=line-too-long #: nih_3t3 = Dataset( path='3T3_NIH.trks', url='https://deepcell-data.s3.amazonaws.com/tracked/3T3_NIH.trks', file_hash='0d90...
0.484624
0.244453
from typing import Tuple, Optional, Union, List, Type import warnings import numpy as np import torch from sklearn.model_selection import train_test_split def num_classes_from_labels(labels: np.ndarray) -> int: """ Gets number of classes from labels (aka ground truth aka masks) Args: labels (num...
atomai/utils/preproc.py
from typing import Tuple, Optional, Union, List, Type import warnings import numpy as np import torch from sklearn.model_selection import train_test_split def num_classes_from_labels(labels: np.ndarray) -> int: """ Gets number of classes from labels (aka ground truth aka masks) Args: labels (num...
0.931181
0.83612
import os from nipype.interfaces.afni.base import (AFNICommandBase, AFNICommandOutputSpec, isdefined) from nipype.utils.filemanip import split_filename as split_f from nipype.interfaces.base import (CommandLine, CommandLineInputSpec, ...
macapype/nodes/register.py
import os from nipype.interfaces.afni.base import (AFNICommandBase, AFNICommandOutputSpec, isdefined) from nipype.utils.filemanip import split_filename as split_f from nipype.interfaces.base import (CommandLine, CommandLineInputSpec, ...
0.489503
0.39321
from typing import NamedTuple import cv2 import numpy as np import tensorflow as tf from .util import EventThread class DetectedGrid(NamedTuple): """Detected object coordinate.""" xmin: int xmax: int ymin: int ymax: int def get(self): return (self.xmin, self.xmax), (self.ymin, se...
tegaki/detect.py
from typing import NamedTuple import cv2 import numpy as np import tensorflow as tf from .util import EventThread class DetectedGrid(NamedTuple): """Detected object coordinate.""" xmin: int xmax: int ymin: int ymax: int def get(self): return (self.xmin, self.xmax), (self.ymin, se...
0.936015
0.438966
import PyPDF2 as P import os dir_path = os.path.dirname(os.path.realpath(__file__)) def list_files(directory, extension): return (f for f in os.listdir(directory) if f.endswith('.' + extension)) pdfs = list_files(dir_path, "pdf") for pdf in pdfs: reader = P.PdfFileReader(open(pdf,'rb')) page...
format.py
import PyPDF2 as P import os dir_path = os.path.dirname(os.path.realpath(__file__)) def list_files(directory, extension): return (f for f in os.listdir(directory) if f.endswith('.' + extension)) pdfs = list_files(dir_path, "pdf") for pdf in pdfs: reader = P.PdfFileReader(open(pdf,'rb')) page...
0.155142
0.080719
from CIM100.IEC61970.Base.Generation.GenerationDynamics.PrimeMover import PrimeMover class HydroTurbine(PrimeMover): """A water driven prime mover. Typical turbine types are: Francis, Kaplan, and Pelton.A water driven prime mover. Typical turbine types are: Francis, Kaplan, and Pelton. """ def __init__(s...
CIM100/IEC61970/Base/Generation/GenerationDynamics/HydroTurbine.py
from CIM100.IEC61970.Base.Generation.GenerationDynamics.PrimeMover import PrimeMover class HydroTurbine(PrimeMover): """A water driven prime mover. Typical turbine types are: Francis, Kaplan, and Pelton.A water driven prime mover. Typical turbine types are: Francis, Kaplan, and Pelton. """ def __init__(s...
0.879341
0.733416
import torch import torch.nn as nn from vq_modules import Encoder, Decoder from vq_modules import VectorQuantizer2 as VectorQuantizer class VQModel(nn.Module): def __init__(self, ckpt_path=None): super().__init__() ddconfig = {'double_z': False, 'z_channels': 256, 'resolution': 256, 'in_c...
vq_f16.py
import torch import torch.nn as nn from vq_modules import Encoder, Decoder from vq_modules import VectorQuantizer2 as VectorQuantizer class VQModel(nn.Module): def __init__(self, ckpt_path=None): super().__init__() ddconfig = {'double_z': False, 'z_channels': 256, 'resolution': 256, 'in_c...
0.935553
0.280804
import collections import copy import inspect import sys import types import typing class Base: """Base class that is inherited by the majority of classes in River. This base class allows us to handle the following tasks in a uniform manner: - Getting and setting parameters. - Displaying information...
river/base/base.py
import collections import copy import inspect import sys import types import typing class Base: """Base class that is inherited by the majority of classes in River. This base class allows us to handle the following tasks in a uniform manner: - Getting and setting parameters. - Displaying information...
0.76454
0.375449
# Re-code by <NAME> # Source: https://github.com/fakhrirofi/twitter_autobase from os.path import getsize from requests import get, post from time import sleep from typing import NoReturn import json MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json' POST_TWEET_URL = 'https://api.twitter.com/1.1...
twitter_autobase/async_upload.py
# Re-code by <NAME> # Source: https://github.com/fakhrirofi/twitter_autobase from os.path import getsize from requests import get, post from time import sleep from typing import NoReturn import json MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json' POST_TWEET_URL = 'https://api.twitter.com/1.1...
0.333503
0.085786
import py_cui from typing import List from py_cui import widget_set class LocalPlayerSettingsMenu: MENU_OPTIONS:List[str]=["Repeat All","Repeat","Shuffle","Block N|P key on repeat"] TITLE:str="Player Settings" ROW:int=4 COLUMN:int=0 ROW_SPAN:int=2 COLUMN_SPAN:int=2 window:py_cui.widget_s...
pymusicterm/ui/menus.py
import py_cui from typing import List from py_cui import widget_set class LocalPlayerSettingsMenu: MENU_OPTIONS:List[str]=["Repeat All","Repeat","Shuffle","Block N|P key on repeat"] TITLE:str="Player Settings" ROW:int=4 COLUMN:int=0 ROW_SPAN:int=2 COLUMN_SPAN:int=2 window:py_cui.widget_s...
0.664758
0.060142
import os import cherrypy import pymongo from go_game import GoGame from go_board import GoBoard webroot = os.getcwd() + '/webroot' class GoApp( object ): def __init__( self ): try: # Run "heroku config:get MONGO_URI" to acquire this URI. Being in plain text here, anyone could find it and c...
go_app.py
import os import cherrypy import pymongo from go_game import GoGame from go_board import GoBoard webroot = os.getcwd() + '/webroot' class GoApp( object ): def __init__( self ): try: # Run "heroku config:get MONGO_URI" to acquire this URI. Being in plain text here, anyone could find it and c...
0.284179
0.055618
import os from sahara.plugins import edp from sahara.plugins import exceptions as ex from sahara.plugins import utils as plugin_utils from sahara_plugin_vanilla.i18n import _ from sahara_plugin_vanilla.plugins.vanilla import confighints_helper from sahara_plugin_vanilla.plugins.vanilla.hadoop2 import edp_engine from s...
sahara_plugin_vanilla/plugins/vanilla/v2_7_5/edp_engine.py
import os from sahara.plugins import edp from sahara.plugins import exceptions as ex from sahara.plugins import utils as plugin_utils from sahara_plugin_vanilla.i18n import _ from sahara_plugin_vanilla.plugins.vanilla import confighints_helper from sahara_plugin_vanilla.plugins.vanilla.hadoop2 import edp_engine from s...
0.338624
0.084871
import gym import ptan import argparse import random import numpy as np import torch import torch.optim as optim import torch.nn as nn from ignite.engine import Engine from .lib import dqn_model, common NAME = "03_double" STATES_TO_EVALUATE = 1000 EVAL_EVERY_FRAME = 100 def calc_loss_double_dqn(batch, net, tgt_ne...
Chapter08/03_dqn_double.py
import gym import ptan import argparse import random import numpy as np import torch import torch.optim as optim import torch.nn as nn from ignite.engine import Engine from .lib import dqn_model, common NAME = "03_double" STATES_TO_EVALUATE = 1000 EVAL_EVERY_FRAME = 100 def calc_loss_double_dqn(batch, net, tgt_ne...
0.80479
0.459986
import superimport import numpy as np import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn import datasets from sklearn.datasets import make_moons from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.preprocessing import StandardScaler from skl...
scripts/svm_classifier_feature_scaling.py
import superimport import numpy as np import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn import datasets from sklearn.datasets import make_moons from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.preprocessing import StandardScaler from skl...
0.686895
0.431704
import os import boto3 from dagster import ModeDefinition, solid from dagster.core.storage.file_cache import FSFileCache from dagster.seven import mock from dagster.utils.temp_file import get_temp_dir, get_temp_file_name from dagster.utils.test import execute_solid from dagster_aws.s3 import S3Coordinate from moto imp...
examples/airline_demo/airline_demo_tests/unit_tests/testing_guide_tests/test_cache_file_from_s3_in_guide_step_three.py
import os import boto3 from dagster import ModeDefinition, solid from dagster.core.storage.file_cache import FSFileCache from dagster.seven import mock from dagster.utils.temp_file import get_temp_dir, get_temp_file_name from dagster.utils.test import execute_solid from dagster_aws.s3 import S3Coordinate from moto imp...
0.459076
0.19546
import typing import asyncio import pytest import pyuavcan from pyuavcan.transport.udp import UDPTransport from pyuavcan.transport.redundant import RedundantTransport from pyuavcan.presentation import Presentation @pytest.mark.asyncio # type: ignore async def _unittest_slow_node(generated_packages: typing.List[pyua...
tests/application/node.py
import typing import asyncio import pytest import pyuavcan from pyuavcan.transport.udp import UDPTransport from pyuavcan.transport.redundant import RedundantTransport from pyuavcan.presentation import Presentation @pytest.mark.asyncio # type: ignore async def _unittest_slow_node(generated_packages: typing.List[pyua...
0.570451
0.341665
import copy import os import json import unicodecsv as csv import codecs from urllib2 import urlopen from jinja2 import Environment, FileSystemLoader CHINESE_WIKI_LANG = "zh" SIMPLIFIED_CHINESE_LANG = "zh-hans" TRADITIONAL_CHINESE_LANG = "zh-hant" # Wikis that cause problems and hence we pretend # do not exist. # -...
scripts/make-templates.py
import copy import os import json import unicodecsv as csv import codecs from urllib2 import urlopen from jinja2 import Environment, FileSystemLoader CHINESE_WIKI_LANG = "zh" SIMPLIFIED_CHINESE_LANG = "zh-hans" TRADITIONAL_CHINESE_LANG = "zh-hant" # Wikis that cause problems and hence we pretend # do not exist. # -...
0.515376
0.182553
"""An example custom `te.core.Encoder` for `tff`.""" import tensorflow as tf from tensorflow_model_optimization.python.core.internal import tensor_encoding as te @te.core.tf_style_adaptive_encoding_stage class OddEvenSparseEncodingStage(te.core.AdaptiveEncodingStageInterface): """An example custom implementation ...
tensorflow_federated/python/research/compression/sparsity.py
"""An example custom `te.core.Encoder` for `tff`.""" import tensorflow as tf from tensorflow_model_optimization.python.core.internal import tensor_encoding as te @te.core.tf_style_adaptive_encoding_stage class OddEvenSparseEncodingStage(te.core.AdaptiveEncodingStageInterface): """An example custom implementation ...
0.943465
0.743517
from django.contrib import messages from django.db.models import Q from django.http import HttpResponseRedirect from django.urls import reverse_lazy, reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic import ListView, DetailView, View, DeleteView from django.views.generic.detail i...
oscar_docdata/dashboard/views.py
from django.contrib import messages from django.db.models import Q from django.http import HttpResponseRedirect from django.urls import reverse_lazy, reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic import ListView, DetailView, View, DeleteView from django.views.generic.detail i...
0.438545
0.080357
from datetime import datetime from nzbclients.nzbdrone.common import ( DiskSpaceSchema, RootFolderSchema, SystemStatusSchema, ) def test_disk_space_serialization(disk_space_json): schema = DiskSpaceSchema() results = [schema.load(x) for x in disk_space_json] assert len(results) == 1 asse...
tests/test_common.py
from datetime import datetime from nzbclients.nzbdrone.common import ( DiskSpaceSchema, RootFolderSchema, SystemStatusSchema, ) def test_disk_space_serialization(disk_space_json): schema = DiskSpaceSchema() results = [schema.load(x) for x in disk_space_json] assert len(results) == 1 asse...
0.724968
0.583856
import cv2 import numpy as np from PIL import Image import os import imageio def index(m, n): if m >= 0 and m < n: return m elif m < 0: return 0 elif m >= n: return n-1 def make_palette(num_classes): """ Maps classes to colors in the style of PASCAL VOC. Close ...
utils.py
import cv2 import numpy as np from PIL import Image import os import imageio def index(m, n): if m >= 0 and m < n: return m elif m < 0: return 0 elif m >= n: return n-1 def make_palette(num_classes): """ Maps classes to colors in the style of PASCAL VOC. Close ...
0.582016
0.508239
import actionlib import os import rospy from bitbots_msgs.msg import DynUpAction from tf2_geometry_msgs import PoseStamped from humanoid_league_msgs.msg import GameState, HeadMode, Strategy, TeamData,\ RobotControlState, PoseWithCertainty, PoseWithCertaintyArray from move_base_msgs.msg import MoveBaseActionFeedback...
bitbots_body_behavior/src/bitbots_body_behavior/body_behavior.py
import actionlib import os import rospy from bitbots_msgs.msg import DynUpAction from tf2_geometry_msgs import PoseStamped from humanoid_league_msgs.msg import GameState, HeadMode, Strategy, TeamData,\ RobotControlState, PoseWithCertainty, PoseWithCertaintyArray from move_base_msgs.msg import MoveBaseActionFeedback...
0.279927
0.091992
from . import DATASET_REGISTRY from . import dataset_register, data_abspath from . import Corpus, sanity_check @dataset_register('iitb-hi-en', ['train', 'dev', 'test']) def IITB_meta(split): corpora = [] for lang in ['en', 'hi']: sub_path = 'filtered-iitb/{}.{}'.format(split, lang) corpus = Co...
fairseq/data/cvit/corpora.py
from . import DATASET_REGISTRY from . import dataset_register, data_abspath from . import Corpus, sanity_check @dataset_register('iitb-hi-en', ['train', 'dev', 'test']) def IITB_meta(split): corpora = [] for lang in ['en', 'hi']: sub_path = 'filtered-iitb/{}.{}'.format(split, lang) corpus = Co...
0.277571
0.199893
from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.db import models from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from ltrc.classes.manage_choices import year_choices from ltrc.classes.manage_date import get_current_year cl...
ltrc/registro/models.py
from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.db import models from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from ltrc.classes.manage_choices import year_choices from ltrc.classes.manage_date import get_current_year cl...
0.483161
0.139191
from PyQt4 import QtCore, QtGui import re from selectLibraries import Ui_Libraries from headerSelection import Ui_Header from filterSelection import Ui_Filter def selectLibraries(main,output_): def emit(dialog,output_): libraries = ','.join([str(main.ui.selected.item(i).text()) for i in range(main.ui.sel...
dialogs.py
from PyQt4 import QtCore, QtGui import re from selectLibraries import Ui_Libraries from headerSelection import Ui_Header from filterSelection import Ui_Filter def selectLibraries(main,output_): def emit(dialog,output_): libraries = ','.join([str(main.ui.selected.item(i).text()) for i in range(main.ui.sel...
0.203075
0.059537
import re import urllib2 import socket import subprocess from urllib2 import HTTPError from requests.exceptions import ConnectionError # Libraries from lib.core.dork_check import DorkScanner from lib.core.errors import GoogleBlockException from lib.core.hash_cracking import HashCracker from lib.core.hash_cracking.hash...
lib/pointers.py
import re import urllib2 import socket import subprocess from urllib2 import HTTPError from requests.exceptions import ConnectionError # Libraries from lib.core.dork_check import DorkScanner from lib.core.errors import GoogleBlockException from lib.core.hash_cracking import HashCracker from lib.core.hash_cracking.hash...
0.314577
0.082994
"""Flags for commands that deal with the CRM API.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.resource_manager import exceptions from googlecloudsdk.calliope import base from googlecloudsdk.calliope import exceptions as ...
lib/googlecloudsdk/command_lib/resource_manager/flags.py
"""Flags for commands that deal with the CRM API.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.resource_manager import exceptions from googlecloudsdk.calliope import base from googlecloudsdk.calliope import exceptions as ...
0.680242
0.174621
from json import dumps, loads from telebot.types import InlineKeyboardButton import UI.buttons.confirm import UI.misc from Bot.util import save_confirm_message def back(lang): return InlineKeyboardButton( UI.misc.messages[lang]['buttons']['common']['back'], callback_data=dumps(dict(G='back')) ...
UI/buttons/common.py
from json import dumps, loads from telebot.types import InlineKeyboardButton import UI.buttons.confirm import UI.misc from Bot.util import save_confirm_message def back(lang): return InlineKeyboardButton( UI.misc.messages[lang]['buttons']['common']['back'], callback_data=dumps(dict(G='back')) ...
0.363195
0.275762
import pytest from raiden.messages import ( decode, Processed, Ping, ) from raiden.constants import UINT256_MAX, UINT64_MAX from raiden.utils import sha3 from raiden.tests.utils.messages import ( make_direct_transfer, make_mediated_transfer, make_refund_transfer, ) from raiden.tests.utils.facto...
raiden/tests/unit/test_binary_encoding.py
import pytest from raiden.messages import ( decode, Processed, Ping, ) from raiden.constants import UINT256_MAX, UINT64_MAX from raiden.utils import sha3 from raiden.tests.utils.messages import ( make_direct_transfer, make_mediated_transfer, make_refund_transfer, ) from raiden.tests.utils.facto...
0.557845
0.358774
import logging from ocs_ci.ocs import constants, defaults from ocs_ci.ocs import exceptions from ocs_ci.ocs.ocp import OCP from ocs_ci.ocs.resources.ocs import OCS from ocs_ci.utility.utils import TimeoutIterator log = logging.getLogger(__name__) def get_job_obj(name, namespace=defaults.ROOK_CLUSTER_NAMESPACE): ...
ocs_ci/ocs/resources/job.py
import logging from ocs_ci.ocs import constants, defaults from ocs_ci.ocs import exceptions from ocs_ci.ocs.ocp import OCP from ocs_ci.ocs.resources.ocs import OCS from ocs_ci.utility.utils import TimeoutIterator log = logging.getLogger(__name__) def get_job_obj(name, namespace=defaults.ROOK_CLUSTER_NAMESPACE): ...
0.68342
0.233521
from opentamiltests import * import unittest from solthiruthi.tamil99kbd import inv_confusion_matrix as ta_kbd_cm from solthiruthi.qwertykbd import confusion_matrix as en_kbd_cm from solthiruthi.typographical import oridam_generate_patterns, corrections from solthiruthi.dictionary import DictionaryBuilder, TamilVU DE...
tests/solthiruthi_typographical.py
from opentamiltests import * import unittest from solthiruthi.tamil99kbd import inv_confusion_matrix as ta_kbd_cm from solthiruthi.qwertykbd import confusion_matrix as en_kbd_cm from solthiruthi.typographical import oridam_generate_patterns, corrections from solthiruthi.dictionary import DictionaryBuilder, TamilVU DE...
0.47025
0.368633
import datetime class qtime(object): # Takes a time of either a datetime object or a string of format "HH:MM" # (in 24-hour time), and optionally an "early" or "late" value of the same # format, which simply substracts or adds to the time. # Given both an early and a late value, the time will be rando...
web/qtime.py
import datetime class qtime(object): # Takes a time of either a datetime object or a string of format "HH:MM" # (in 24-hour time), and optionally an "early" or "late" value of the same # format, which simply substracts or adds to the time. # Given both an early and a late value, the time will be rando...
0.797478
0.517022
import jax.numpy as np from jax import grad, nn, random, jit from jax.experimental import stax, optimizers from jax.experimental.optimizers import l2_norm, clip_grads from jax.numpy import linalg from tqdm import tqdm def predict(W, X): """Forward propagation for logistic regression.""" return nn.sigmoid(np.dot(X...
logistic_regression.py
import jax.numpy as np from jax import grad, nn, random, jit from jax.experimental import stax, optimizers from jax.experimental.optimizers import l2_norm, clip_grads from jax.numpy import linalg from tqdm import tqdm def predict(W, X): """Forward propagation for logistic regression.""" return nn.sigmoid(np.dot(X...
0.901222
0.649356
import logging from typing import List from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from src.callbacks.base_callback import BaseCallback from src.callbacks.early_stopping import EarlyStopping from src.callbacks.save_checkpoints ...
src/trainer.py
import logging from typing import List from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from src.callbacks.base_callback import BaseCallback from src.callbacks.early_stopping import EarlyStopping from src.callbacks.save_checkpoints ...
0.950469
0.228544
import serial from serial import Serial import re import requests import json import time import sys ACCESS_TOKEN = '<KEY>' HEADERS = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(ACCESS_TOKEN), } def Get_Temp_From_Atmega(): ''' params: None Listen to the atmega for values,...
Code/ServerCode/serialConn.py
import serial from serial import Serial import re import requests import json import time import sys ACCESS_TOKEN = '<KEY>' HEADERS = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(ACCESS_TOKEN), } def Get_Temp_From_Atmega(): ''' params: None Listen to the atmega for values,...
0.288669
0.148263
import tensorflow as tf import tensornet as tn from common.config import Config as C from common.layers import FMLayer from common.feature_column import tn_category_columns_builder, embedding_columns_builder, create_emb_model def create_sub_model(linear_embs, deep_embs, deep_hidden_units): linear_emb_input_shape...
examples/models/wide_deep.py
import tensorflow as tf import tensornet as tn from common.config import Config as C from common.layers import FMLayer from common.feature_column import tn_category_columns_builder, embedding_columns_builder, create_emb_model def create_sub_model(linear_embs, deep_embs, deep_hidden_units): linear_emb_input_shape...
0.765418
0.478163
import logging from operator import attrgetter import re import shlex import subprocess import sys from textwrap import fill import time from typing import List, Optional, Tuple import click from in_place import InPlace from intspan import intspan from jinja2 import Environment, PackageLoader from linesep import split_...
src/pyrepo/util.py
import logging from operator import attrgetter import re import shlex import subprocess import sys from textwrap import fill import time from typing import List, Optional, Tuple import click from in_place import InPlace from intspan import intspan from jinja2 import Environment, PackageLoader from linesep import split_...
0.525125
0.234505
__all__ = [ 'OnscreenText', 'Plain', 'ScreenTitle', 'ScreenPrompt', 'NameConfirm', 'BlackOnWhite'] from panda3d.core import * import DirectGuiGlobals as DGG from direct.showbase.DirectObject import DirectObject import types Plain = 1 ScreenTitle = 2 ScreenPrompt = 3 NameConfirm = 4 BlackOnWhite = 5 class OnscreenText...
direct/gui/OnscreenText.py
__all__ = [ 'OnscreenText', 'Plain', 'ScreenTitle', 'ScreenPrompt', 'NameConfirm', 'BlackOnWhite'] from panda3d.core import * import DirectGuiGlobals as DGG from direct.showbase.DirectObject import DirectObject import types Plain = 1 ScreenTitle = 2 ScreenPrompt = 3 NameConfirm = 4 BlackOnWhite = 5 class OnscreenText...
0.39222
0.186706
import os import cv2 import filters import numpy as np import matplotlib.pyplot as plt from managers import CaptureManager, WindowManager class Cameo(object): def __init__(self): self.shootcount = 1 self.castcount = 1 self.mean = None self.sigma = None self._windowManager = WindowManager('REAL'...
cameo.py
import os import cv2 import filters import numpy as np import matplotlib.pyplot as plt from managers import CaptureManager, WindowManager class Cameo(object): def __init__(self): self.shootcount = 1 self.castcount = 1 self.mean = None self.sigma = None self._windowManager = WindowManager('REAL'...
0.126057
0.100481
import json import re import markdown2 import timeout_decorator from .helper import reputation_to_score, calc_flag_weight def make_index_config(type_name): return { 'settings': { 'analysis': { 'analyzer': { 'index_analyzer': { 'toke...
post/es_helpers.py
import json import re import markdown2 import timeout_decorator from .helper import reputation_to_score, calc_flag_weight def make_index_config(type_name): return { 'settings': { 'analysis': { 'analyzer': { 'index_analyzer': { 'toke...
0.475849
0.235757
import re import string import types from xen.xend import sxp from xen.xend.XendError import VmError from xen.xend.XendLogging import log from xen.xend.server.DevController import DevController from xen.xend.server.DevConstants import xenbusState from xen.xend.xenstore.xstransact import xstransact class VSCSIContro...
xen/xen-4.2.2/tools/python/xen/xend/server/vscsiif.py
import re import string import types from xen.xend import sxp from xen.xend.XendError import VmError from xen.xend.XendLogging import log from xen.xend.server.DevController import DevController from xen.xend.server.DevConstants import xenbusState from xen.xend.xenstore.xstransact import xstransact class VSCSIContro...
0.236076
0.059921
from tqdm import tqdm import numpy as np import os import glob from config import opt import random lfw_img_num = 18982 lfw_idx_num = 5749 lfw_data_dir = opt.lfw_data_dir + '/lfw/' indices_all_file_path = 'dataset/lfw_all_indices.txt' indices_trainval_file_path = 'dataset/lfw_trainval_indices.txt' indices_test_file_...
create_lfw_dataset.py
from tqdm import tqdm import numpy as np import os import glob from config import opt import random lfw_img_num = 18982 lfw_idx_num = 5749 lfw_data_dir = opt.lfw_data_dir + '/lfw/' indices_all_file_path = 'dataset/lfw_all_indices.txt' indices_trainval_file_path = 'dataset/lfw_trainval_indices.txt' indices_test_file_...
0.112028
0.202128
import numpy as np import tensorflow as tf from sleap.nn.system import use_cpu_only use_cpu_only() # hide GPUs for test from sleap.nn.architectures import upsampling from sleap.nn.architectures import resnet from sleap.nn.config import ResNetConfig class ResnetTests(tf.test.TestCase): def test_resnet50(self): ...
tests/nn/architectures/test_resnet.py
import numpy as np import tensorflow as tf from sleap.nn.system import use_cpu_only use_cpu_only() # hide GPUs for test from sleap.nn.architectures import upsampling from sleap.nn.architectures import resnet from sleap.nn.config import ResNetConfig class ResnetTests(tf.test.TestCase): def test_resnet50(self): ...
0.791176
0.477676
print("»» 1. AÑO BISIESTO") def anho_bisiesto(anho): if anho % 4 == 0: if anho % 100 == 0: if anho % 400 == 0: txt = 'es' else: txt = 'no es' else: txt = 'es' else: txt = 'no es' return txt anho = int(input('Ing...
ejercitario.04.py
print("»» 1. AÑO BISIESTO") def anho_bisiesto(anho): if anho % 4 == 0: if anho % 100 == 0: if anho % 400 == 0: txt = 'es' else: txt = 'no es' else: txt = 'es' else: txt = 'no es' return txt anho = int(input('Ing...
0.084205
0.484258
import github3.gists # Monkeypatch github3.gists.Gist to behave more like a repo github3.gists.gist._Gist.ssh_url = property(lambda self: 'git@gist.github.com:/%s.git' % self.id) github3.gists.gist._Gist.clone_url = property(lambda self: self.git_pull_url) github3.gists.gist._Gist.git_url = property(lambda self: 'git:...
lib/gitspindle/monkey.py
import github3.gists # Monkeypatch github3.gists.Gist to behave more like a repo github3.gists.gist._Gist.ssh_url = property(lambda self: 'git@gist.github.com:/%s.git' % self.id) github3.gists.gist._Gist.clone_url = property(lambda self: self.git_pull_url) github3.gists.gist._Gist.git_url = property(lambda self: 'git:...
0.312895
0.431764
from GameObject import * import pygame from Constants import IMAGE_BALLOON_PATH, ITEM_BALLOON_WIDTH, ITEM_BALLOON_HEIGHT, ITEM_BAR_WIDTH, ITEM_BRICKS_HEIGHT class ItemBalloon(GameObject): def __init__(self,gameObject): super(GameObject, self).__init__() pygame.sprite.Sprite.__init__(self) # call...
ItemBalloon.py
from GameObject import * import pygame from Constants import IMAGE_BALLOON_PATH, ITEM_BALLOON_WIDTH, ITEM_BALLOON_HEIGHT, ITEM_BAR_WIDTH, ITEM_BRICKS_HEIGHT class ItemBalloon(GameObject): def __init__(self,gameObject): super(GameObject, self).__init__() pygame.sprite.Sprite.__init__(self) # call...
0.311636
0.264486
from time import time from datetime import datetime, timedelta, tzinfo from quip import QuipClient class QuipClient4AHA(QuipClient): """A customized Quip client using Harry's token and dedicated for AHA Broadcast.""" AHABC_ID = "PCeAOAQx6sO" DESKTOP_ID = "LHEAOAhm7YS" # Harry's private desktop. KE...
quip4aha.py
from time import time from datetime import datetime, timedelta, tzinfo from quip import QuipClient class QuipClient4AHA(QuipClient): """A customized Quip client using Harry's token and dedicated for AHA Broadcast.""" AHABC_ID = "PCeAOAQx6sO" DESKTOP_ID = "LHEAOAhm7YS" # Harry's private desktop. KE...
0.52342
0.245006
from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django_otp import user_has_device from .models import RememberDeviceCookie from .utils import get_custom_auth UserModel = get_user_model() class CookieBackend(ModelBackend): part_login_key = 'part_login' ...
modal_2fa/backends.py
from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django_otp import user_has_device from .models import RememberDeviceCookie from .utils import get_custom_auth UserModel = get_user_model() class CookieBackend(ModelBackend): part_login_key = 'part_login' ...
0.391755
0.04952
load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts") load( "//rs_bindings_from_cc/bazel_support:rust_bindings_from_cc_aspect.bzl", "rust_bindings_from_cc_aspect", ) load( "//rs_bindings_from_cc/bazel_support:rust_bindings_from_cc_utils.bzl", "RustBindingsFromCcInfo", ) ActionsInfo = provi...
rs_bindings_from_cc/test/bazel_unit_tests/headers_and_targets/rust_bindings_from_cc_aspect_test.bzl
load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts") load( "//rs_bindings_from_cc/bazel_support:rust_bindings_from_cc_aspect.bzl", "rust_bindings_from_cc_aspect", ) load( "//rs_bindings_from_cc/bazel_support:rust_bindings_from_cc_utils.bzl", "RustBindingsFromCcInfo", ) ActionsInfo = provi...
0.652795
0.36139
"""Implement several encoder classes""" from keras.applications.resnet50 import ResNet50, preprocess_input as preprocess_resnet, decode_predictions from keras.applications.inception_v3 import InceptionV3, preprocess_input as preprocess_inception from keras.applications.vgg16 import VGG16, preprocess_input as preproces...
models.py
"""Implement several encoder classes""" from keras.applications.resnet50 import ResNet50, preprocess_input as preprocess_resnet, decode_predictions from keras.applications.inception_v3 import InceptionV3, preprocess_input as preprocess_inception from keras.applications.vgg16 import VGG16, preprocess_input as preproces...
0.94338
0.327077
from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisRrpproxyNetStatusRegistered(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.rrpproxy.net/status_registered.txt" host = "whois.rrpproxy.net" part =...
test/record/parser/test_response_whois_rrpproxy_net_status_registered.py
from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisRrpproxyNetStatusRegistered(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.rrpproxy.net/status_registered.txt" host = "whois.rrpproxy.net" part =...
0.468791
0.141045
from functools import reduce import numpy as np from scipy.stats import multinomial from ssrm_test import ssrm_test as st class SSRMSuite: def setup(self): self.intended_p_alloc = [0.1, 0.5, 0.4] self.actual_p_alloc = [0.1, 0.49, 0.41] self.n = 1000 self.alpha = 0.01 self....
benchmarks/benchmarks/bench_ssrm.py
from functools import reduce import numpy as np from scipy.stats import multinomial from ssrm_test import ssrm_test as st class SSRMSuite: def setup(self): self.intended_p_alloc = [0.1, 0.5, 0.4] self.actual_p_alloc = [0.1, 0.49, 0.41] self.n = 1000 self.alpha = 0.01 self....
0.774754
0.323554
# standard library from enum import Enum # first-party from tcex.api.tc.v3.api_endpoints import ApiEndpoints from tcex.api.tc.v3.filter_abc import FilterABC from tcex.api.tc.v3.tql.tql_type import TqlType class OwnerFilter(FilterABC): """Filter Object for Owners""" @property def _api_endpoint(self) -> s...
tcex/api/tc/v3/security/owners/owner_filter.py
# standard library from enum import Enum # first-party from tcex.api.tc.v3.api_endpoints import ApiEndpoints from tcex.api.tc.v3.filter_abc import FilterABC from tcex.api.tc.v3.tql.tql_type import TqlType class OwnerFilter(FilterABC): """Filter Object for Owners""" @property def _api_endpoint(self) -> s...
0.923316
0.267845
import pytest from memo import memlist, Runner, grid @pytest.mark.parametrize( "kw", [{"backend": "loky"}, {"backend": "threading"}, {"backend": "multiprocessing"}], ) def test_base_multiple_calls(kw): data = [] g = [{"a": 1}] * 100 @memlist(data=data) def count_values(n_jobs=-1, **kwargs): ...
tests/test_runner.py
import pytest from memo import memlist, Runner, grid @pytest.mark.parametrize( "kw", [{"backend": "loky"}, {"backend": "threading"}, {"backend": "multiprocessing"}], ) def test_base_multiple_calls(kw): data = [] g = [{"a": 1}] * 100 @memlist(data=data) def count_values(n_jobs=-1, **kwargs): ...
0.512205
0.485356
from absl import app from absl import flags from fontTools.ttLib import TTFont from gftools import fonts_public_pb2 from gftools.util import google_fonts as fonts from gftools.util import unicode_sections from google.protobuf import text_format import csv import glob import os import re FLAGS = flags.FLAGS flags.DEFIN...
bin/gftools-add-glyphs.py
from absl import app from absl import flags from fontTools.ttLib import TTFont from gftools import fonts_public_pb2 from gftools.util import google_fonts as fonts from gftools.util import unicode_sections from google.protobuf import text_format import csv import glob import os import re FLAGS = flags.FLAGS flags.DEFIN...
0.434941
0.140189
__author__ = "<NAME>" __email__ = "<EMAIL>" from selenium import webdriver from selenium.webdriver.common.keys import Keys import sys import time from datetime import datetime from datetime import date import calendar import math class bcolors: RED = "\033[1;31m" BLUE = "\033[1;34m" CYAN = "\033[1;36m" ...
python/khomp/banco_de_horas.py
__author__ = "<NAME>" __email__ = "<EMAIL>" from selenium import webdriver from selenium.webdriver.common.keys import Keys import sys import time from datetime import datetime from datetime import date import calendar import math class bcolors: RED = "\033[1;31m" BLUE = "\033[1;34m" CYAN = "\033[1;36m" ...
0.29381
0.099733
"""Utility to manipulate resource variables.""" from tensorflow.python.framework import composite_tensor from tensorflow.python.framework import ops from tensorflow.python.util import _pywrap_utils from tensorflow.python.util import nest def convert_variables_to_tensors(values): """Converts `ResourceVariable`s in ...
tensorflow/python/util/variable_utils.py
"""Utility to manipulate resource variables.""" from tensorflow.python.framework import composite_tensor from tensorflow.python.framework import ops from tensorflow.python.util import _pywrap_utils from tensorflow.python.util import nest def convert_variables_to_tensors(values): """Converts `ResourceVariable`s in ...
0.955475
0.640804
from flask import Flask, render_template, request, redirect from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import LogisticRegression from sklearn.externals import joblib from bokeh.e...
Machine Learning/Consumer Complaint Classification/web app/app.py
from flask import Flask, render_template, request, redirect from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import LogisticRegression from sklearn.externals import joblib from bokeh.e...
0.55929
0.095941
from math import log2 import json import pandas from pandas import DataFrame def probe(func): name = func.__name__.strip("calc") def wrapper(*args, **kwargs): result = func(*args, **kwargs) if len(args) >= 2: print(f"${name}(D, \\text{'{'}{args[1]}{'}'}) = {result:.3f}$") ...
ML/Ml.py/decision_tree.py
from math import log2 import json import pandas from pandas import DataFrame def probe(func): name = func.__name__.strip("calc") def wrapper(*args, **kwargs): result = func(*args, **kwargs) if len(args) >= 2: print(f"${name}(D, \\text{'{'}{args[1]}{'}'}) = {result:.3f}$") ...
0.519521
0.622717
from amqplib import client_0_8 as amqp class BaseAMQPConnection(object): virtual_host = "/" port = 5672 insist = False def __init__(self, hostname, userid, password, virtual_host=None, port=None, **kwargs): self.hostname = hostname self.userid = userid self.passwor...
carrot/connection.py
from amqplib import client_0_8 as amqp class BaseAMQPConnection(object): virtual_host = "/" port = 5672 insist = False def __init__(self, hostname, userid, password, virtual_host=None, port=None, **kwargs): self.hostname = hostname self.userid = userid self.passwor...
0.624064
0.068662
from puzzle_generator import PuzzleGenerator from typing import List # See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-puzzle to learn about adding puzzles class BirthdayParadox(PuzzleGenerator): """ Adaptation of the classic [Birthday Problem](https://en.wikipedia.org/wiki/...
generators/probability.py
from puzzle_generator import PuzzleGenerator from typing import List # See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-puzzle to learn about adding puzzles class BirthdayParadox(PuzzleGenerator): """ Adaptation of the classic [Birthday Problem](https://en.wikipedia.org/wiki/...
0.815563
0.734381
import numpy as np from .box import Box class Question: """Models a question in a form. Attributes ---------- title : str The title of the question. answers : list The possible answers for each box. coords : list The list of the coordinates of the cente...
survey/question.py
import numpy as np from .box import Box class Question: """Models a question in a form. Attributes ---------- title : str The title of the question. answers : list The possible answers for each box. coords : list The list of the coordinates of the cente...
0.877667
0.611034
from sympy.functions import sqrt, sign from sympy.core import S, Wild, Rational, sympify def sqrtdenest (expr): """ Denests an expression that contains nested square roots. This algorithm is based on <http://www.almaden.ibm.com/cs/people/fagin/symb85.pdf>. """ expr = sympify(expr) if expr.is_Po...
sympy/simplify/sqrtdenest.py
from sympy.functions import sqrt, sign from sympy.core import S, Wild, Rational, sympify def sqrtdenest (expr): """ Denests an expression that contains nested square roots. This algorithm is based on <http://www.almaden.ibm.com/cs/people/fagin/symb85.pdf>. """ expr = sympify(expr) if expr.is_Po...
0.553747
0.670718
from password import User import pyperclip def create_account(user_name,email,password): ''' Function to create a new account ''' new_account = User(user_name,email,password) return new_account def save_accounts(account): ''' Function to save accountt ''' account.save_account() def d...
run.py
from password import User import pyperclip def create_account(user_name,email,password): ''' Function to create a new account ''' new_account = User(user_name,email,password) return new_account def save_accounts(account): ''' Function to save accountt ''' account.save_account() def d...
0.154983
0.1798
from pythran.tests import TestEnv from pythran.syntax import PythranSyntaxError class TestNamedParameters(TestEnv): def test_call_with_named_argument(self): self.run_test(""" def foo(a): return a def call_with_named_argument(n): return foo(a=n)""", 1, call_with_named_argument=[int]) def test_...
pythran/tests/test_named_parameters.py
from pythran.tests import TestEnv from pythran.syntax import PythranSyntaxError class TestNamedParameters(TestEnv): def test_call_with_named_argument(self): self.run_test(""" def foo(a): return a def call_with_named_argument(n): return foo(a=n)""", 1, call_with_named_argument=[int]) def test_...
0.674372
0.434821
from msrest.serialization import Model class X12FramingSettings(Model): """The X12 agreement framing settings. All required parameters must be populated in order to send to Azure. :param data_element_separator: Required. The data element separator. :type data_element_separator: int :param compo...
azure-mgmt-logic/azure/mgmt/logic/models/x12_framing_settings_py3.py
from msrest.serialization import Model class X12FramingSettings(Model): """The X12 agreement framing settings. All required parameters must be populated in order to send to Azure. :param data_element_separator: Required. The data element separator. :type data_element_separator: int :param compo...
0.912473
0.398758
import time import tensorflow as tf import scipy.io as sio import os flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('num_evecs', 120, 'number of eigenvectors used for representation. The first 500 are precomputed and stored in input') flags.DEFINE_string('test_shapes_dir', './faust_synthetic/netw...
Learning Correspondence of Synthetic Shapes/test_FMnet_unsupervised.py
import time import tensorflow as tf import scipy.io as sio import os flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('num_evecs', 120, 'number of eigenvectors used for representation. The first 500 are precomputed and stored in input') flags.DEFINE_string('test_shapes_dir', './faust_synthetic/netw...
0.310485
0.24629
from tqdm import tqdm from sklearn.feature_extraction.image import extract_patches import numpy as np def array_normalization(X,M=None,norm=0): """Normalization for image regression Inputs : X : array of data M : array of mask used to compute normalization parameters Outputs : X : normaliz...
AnkleSegmentation/extract_slices.py
from tqdm import tqdm from sklearn.feature_extraction.image import extract_patches import numpy as np def array_normalization(X,M=None,norm=0): """Normalization for image regression Inputs : X : array of data M : array of mask used to compute normalization parameters Outputs : X : normaliz...
0.493409
0.539529
import os import shutil import photohandler as PH from operator import itemgetter FOLDERSONLY=True DEBUG=True defaultpath="" NAME=0 DATE=1 class FileList: def __init__(self,folder): """Class constructor""" self.folder=folder self.listFileDates() def getPhotoNamedates(self): """returns the list of...
Chapter03/filehandler.py
import os import shutil import photohandler as PH from operator import itemgetter FOLDERSONLY=True DEBUG=True defaultpath="" NAME=0 DATE=1 class FileList: def __init__(self,folder): """Class constructor""" self.folder=folder self.listFileDates() def getPhotoNamedates(self): """returns the list of...
0.315103
0.093719
"""generated automatically by auto_dao.py""" from __future__ import division from vistrails.db.versions.v0_3_0.persistence.xml.xml_dao import XMLDAO from vistrails.db.versions.v0_3_0.domain.auto_gen import * class DBChangeParameterXMLDAOBase(XMLDAO): def __init__(self, daoList): self.daoList = daoList ...
vistrails/db/versions/v0_3_0/persistence/xml/auto_gen.py
"""generated automatically by auto_dao.py""" from __future__ import division from vistrails.db.versions.v0_3_0.persistence.xml.xml_dao import XMLDAO from vistrails.db.versions.v0_3_0.domain.auto_gen import * class DBChangeParameterXMLDAOBase(XMLDAO): def __init__(self, daoList): self.daoList = daoList ...
0.601008
0.071364
import numpy from PIL import Image from contextlib import contextmanager @contextmanager def acquire_and_normalise(filename, display_panel_controller, background_colour=-1, rotate_count=0): """ Reads in input image, and converts to correct size. Adds a border if necessary. :param filename: path to imag...
pyepd/ImageHandler.py
import numpy from PIL import Image from contextlib import contextmanager @contextmanager def acquire_and_normalise(filename, display_panel_controller, background_colour=-1, rotate_count=0): """ Reads in input image, and converts to correct size. Adds a border if necessary. :param filename: path to imag...
0.802942
0.498169
from typing import List, Optional from .data import ( MappedEvents, LinkHandlerData, ) from .link import ( EventLinkStart, ) from ..lifecycle.listener_set import ListenerSet from ...base import ( EventBus, EventId, ParticipantId, TARGET_WILDCARD, as_request_dispose_listener, send_d...
src/petronia/aid/event_chain/owner.py
from typing import List, Optional from .data import ( MappedEvents, LinkHandlerData, ) from .link import ( EventLinkStart, ) from ..lifecycle.listener_set import ListenerSet from ...base import ( EventBus, EventId, ParticipantId, TARGET_WILDCARD, as_request_dispose_listener, send_d...
0.701509
0.206294
from mock import ( patch, call, MagicMock, ANY ) from test_utils import ( CharmTestCase, ) from charmhelpers.contrib.openstack.ip import PUBLIC with patch('charmhelpers.contrib.hardening.harden.harden') as mock_dec: mock_dec.side_effect = (lambda *dargs, **dkwargs: lambda f: l...
unit_tests/test_hooks.py
from mock import ( patch, call, MagicMock, ANY ) from test_utils import ( CharmTestCase, ) from charmhelpers.contrib.openstack.ip import PUBLIC with patch('charmhelpers.contrib.hardening.harden.harden') as mock_dec: mock_dec.side_effect = (lambda *dargs, **dkwargs: lambda f: l...
0.61115
0.212784
import roslib; roslib.load_manifest('smacha') import rospy import smach import smach_ros from actionlib import * from actionlib_msgs.msg import * # Create a trivial action server class TestServer: def __init__(self,name): self._sas = SimpleActionServer(name, TestAction, exe...
smacha/test/executive_smach_tutorials/smach_tutorials/examples/actionlib_test.py
import roslib; roslib.load_manifest('smacha') import rospy import smach import smach_ros from actionlib import * from actionlib_msgs.msg import * # Create a trivial action server class TestServer: def __init__(self,name): self._sas = SimpleActionServer(name, TestAction, exe...
0.425844
0.168344