id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3237147 | r"""
expressions.py
Defines classes to parse and evaluate mathematical expressions. Implements
similar functionality and API as edX's calc.py, but re-written with enhancements
and to better separate parsing and evaluation.
To evaluate a mathematical expression like '2^a + [x, 2]*[y, 4]', we proceed
in two steps:
... |
3237195 | import sys
import os
import subprocess
import json
from scipy import stats
from argparse import ArgumentParser
parser = ArgumentParser(description="Get Ideogram.js annotations for an SRR")
parser.add_argument("--acc", required=True, help="SRR accession")
args = parser.parse_args()
acc = args.acc
out = acc + "_counts"... |
3237215 | import numpy as np
from nilabels.tools.aux_methods.utils_nib import set_new_data
def get_rgb_image_from_segmentation_and_label_descriptor(im_segm, ldm, invert_black_white=False, dtype_output=np.int32):
"""
From the labels descriptor and a nibabel segmentation image.
:param im_segm: nibabel segmentation w... |
3237231 | import pytest
from apps.contributors.models import Contributor
from utils.auth import get_instance
from utils.merge_model_objects import merge_instances
@pytest.fixture
def jimmy(request):
return Contributor.objects.create(
display_name='<NAME>', email='<EMAIL>'
)
@pytest.fixture
def jimmy_twin(req... |
3237245 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import str
from past.utils import old_div
from builtins import object
try:
from . import mesh
except:
import mesh
fr... |
3237263 | import os
import xml.dom.minidom
import StringIO
RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
EM_NS = "http://www.mozilla.org/2004/em-rdf#"
class RDF(object):
def __str__(self):
# real files have an .encoding attribute and use it when you
# write() unicode into them: they read()/write() ... |
3237274 | from pyftdi.spi import SpiController
import time
from commands import *
RILEYLINK_XTAL_FREQUENCY = 24000000
class SPITimeout(Exception):
pass
class SPILink:
BIT_REV = [int('{:08b}'.format(n)[::-1], 2) for n in range(0,256)]
def __init__(self, device='ftdi://ftdi:232h/1', debug=False):
self.devic... |
3237316 | import unittest
def test_function():
pass
class TestClass:
def test_class(self):
pass
class TestCase(unittest.TestCase):
def test(self):
pass
|
3237320 | from typing import List
import numpy as np
from sklearn.utils.multiclass import type_of_target
from tensorflow.keras.backend import floatx as tf_floatx
from scikeras.utils.transformers import ClassifierLabelEncoder
from scikeras.wrappers import KerasClassifier
class MultiLabelTransformer(ClassifierLabelEncoder):
... |
3237330 | class Solution(object):
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
dic = {}
for c in s:
dic[c] = dic.get(c, 0) + 1
odd, even = 0, 0
for c in dic:
if dic[c] % 2 == 0:
even += 1
... |
3237331 | import logging
import time
import itertools
from bbb_pru_adc.capture import capture
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
data = []
bad = 0
good = 0
count = 0
with capture([0, 1, 2, 3, 4, 5, 6, 7], auto_install=True, step_avg=4) as cap:
start = time.time(... |
3237334 | from __future__ import annotations
import asyncio
from typing import Any
import attr
__all__ = ("Ratelimiter",)
@attr.s(slots=True)
class Ratelimiter:
rate: int = attr.field()
per: int = attr.field()
semaphore: asyncio.Semaphore = attr.field(init=False)
def __attrs_post_init__(self) -> None:
... |
3237352 | def intersecting_lines(p, q):
intersections = 0
for i in range(len(p)):
for j in range(len(p) - i - 1):
if (q[j + 1] < q[i]):
intersections = intersections + 1
return intersections
print(intersecting_lines([1, 2, 3], [1, 2, 3])) |
3237355 | import copy
import datetime
import decimal
import json
import uuid
import pytest
from boto3.dynamodb.types import TypeSerializer
from botocore import stub
from fixtures import context, lambda_module # pylint: disable=import-error
from helpers import compare_dict # pylint: disable=import-error,no-name-in-module
lambda... |
3237438 | from delphifmx import *
from TipMain import Main_Window
def main():
Application.Initialize()
Application.Title = 'Tip Calculator'
Application.MainForm = Main_Window(Application)
Application.MainForm.Show()
Application.Run()
Application.MainForm.Destroy()
if __name__ == '__main__':
main()
|
3237440 | import time
# noinspection PyUnresolvedReferences
import cv2
from CONSTANTS import IS_RASPBERRY_PI, CAMERA_PORT, RESOLUTION_H, RESOLUTION_W
from camera.camera_utils import preview_image
class Camera:
def __init__(self, height=RESOLUTION_H, width=RESOLUTION_W):
self.current_frame = None
self.hei... |
3237477 | import numpy as np
import pandas as pd
import plotly.express as px
import pycountry
from plotly.offline import plot
metric = 'Recovery Rate'
multiplier = 1 # Use this to manually lower the color scale (e.g. for Death Rate)
# Load CSVs
covid_df = pd.read_csv('https://raw.githubusercontent.com/datasets/covid-19/master/... |
3237483 | import logging
from django.test import TestCase, tag
from oldp.apps.cases.models import Case
from oldp.apps.references.models import CaseReferenceMarker, ReferenceFromCase
from oldp.apps.references.models import Reference
logger = logging.getLogger(__name__)
@tag('models')
class ReferencesModelsTestCase(TestCase):... |
3237508 | from typing import NamedTuple, Optional
from mypy.plugin import MethodContext
from mypy.types import CallableType, TupleType
from mypy.types import Type as MypyType
from typing_extensions import final
from classes.contrib.mypy.typeops import inference
@final
class _InferredArgs(NamedTuple):
"""Represents our ar... |
3237551 | from typing import Any
import pandas
from pdpcli.stages.stage import Stage
@Stage.register("pass_through")
class PassThroughStage(Stage):
def __init__(self, **kwargs: Any) -> None:
super_kwargs = {
"desc": "Pass through stage.",
}
super_kwargs.update(**kwargs)
super()... |
3237577 | import argparse
from xpotato.graph_extractor.rule import RuleSet
def get_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument("-f", "--features", type=str, required=True)
parser.add_argument("-o", "--output", type=str, required=True)
return parser.parse_args()
def main():
... |
3237623 | class email:
sender = ""
def send_mail(self,recv,subject,contents):
print("From:\t" + self.sender)
print("To: \t" + recv)
print("Subject: \t" + subject)
print("Contents \t")
print(contents,"\n")
print("-"*20)
'''
e = email()
e.sender = "<EMAIL>"
recv_list = ['<E... |
3237629 | import unittest
import hcl2
from checkov.terraform.checks.resource.azure.CutsomRoleDefinitionSubscriptionOwner import check
from checkov.common.models.enums import CheckResult
class TestCustomRoleDefinitionSubscriptionOwner(unittest.TestCase):
def test_failure_1(self):
hcl_res = hcl2.loads("""
... |
3237650 | import pandas as pd
import celescope.tools.utils as utils
from celescope.tools.step import Step
from celescope.tools.analysis_mixin import AnalysisMixin
from celescope.rna.analysis import get_opts_analysis
class Analysis_rna_virus(Step, AnalysisMixin):
def __init__(self, args, step_name):
Step.__init__(s... |
3237661 | from lib.python_actions import PuppetBasePythonAction
__all__ = [
'PuppetCertCleanAction'
]
class PuppetCertCleanAction(PuppetBasePythonAction):
def run(self, environment, host):
success = self.client.cert_clean(environment=environment, host=host)
return success
|
3237663 | import femagtools
import os
import logging
machine = dict(
name="PM 130 L4",
lfe=0.1,
poles=4,
outer_diam=0.13,
bore_diam=0.07,
inner_diam=0.015,
airgap=0.001,
stator=dict(
num_slots=12,
num_slots_gen=3,
mcvkey_yoke="dummy",
rlength=1.0,
st... |
3237669 | from common import *
people = ["Roi", "Alon", "Ailon", "Boaz", "Tal", "Omri", "Ori"]
redis_graph = None
class testEdgeByIndexScanFlow(FlowTestsBase):
def __init__(self):
self.env = Env(decodeResponses=True)
def setUp(self):
global redis_graph
redis_con = self.env.getConnection()
... |
3237673 | import sys
import string
import random
def with_resource(resource):
return 'https://ads-api.twitter.com{resource}'.format(resource=resource)
def with_fixture(name):
f = open('tests/fixtures/{name}.json'.format(name=name), 'r')
return f.read()
def characters(length):
chars = string.ascii_uppercase + s... |
3237683 | import os
import signal
import subprocess
import time
from unittest import TestCase
from scripttest import TestFileEnvironment
from .cli import setup_user_dir
from .meter import Meter
from .utils import create_executable
d = os.path.dirname(__file__)
PROJECT_PATH = os.path.abspath(os.path.join(d, os.pardir))
def cr... |
3237691 | from __future__ import absolute_import
from __future__ import print_function
__author__ = 'a_medelyan'
import rake
# EXAMPLE: Extracting single words from a French text
# French stopwords
stoppath = "FrenchStoplist.txt"
# 1. initialize RAKE by providing a path to a stopwords file and setting phrase length in words t... |
3237693 | from unittest import TestCase
import os
import sys
import time
try:
from core.datadog_client import DatadogClient
except ImportError:
sys.path.append(os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)),
os.pardir), os.pardir))
from core.datadog_client impo... |
3237728 | import os
from onadata.settings.common import *
DEBUG = os.environ.get('DJANGO_DEBUG', 'True') == 'True'
TEMPLATE_DEBUG = os.environ.get('TEMPLATE_DEBUG', 'True') == 'True'
TEMPLATE_STRING_IF_INVALID = ''
import dj_database_url
DATABASES = {
'default': dj_database_url.config(
env='TEST_DATABASE_URL', def... |
3237731 | from tqdm import tqdm
import pandas as pd
import os
import numpy as np
import torch
from global_parameters import HOW2QA_PATH, HOWTO_FEATURES_PATH
train_csv = pd.read_csv(os.path.join(HOW2QA_PATH, "how2QA_train_release.csv"))
train_csv.columns = ["vid_id", "timesteps", "a2", "a3", "a4", "question", "a1"]
print(len(tra... |
3237734 | import os
from pathlib import Path
import ctypes
from ctypes import *
import array as arr
import sys
import argparse
import time
import numpy
# Load binaries
ME = Path(os.path.abspath(__file__)).parent
SRC = ME / "src"
BIN = SRC
model_descriptor = ctypes.CDLL(str(BIN / 'model_descriptor.so'))
model_arrays = ctypes.C... |
3237737 | import tensorflow as tf
from tensorflow.python.ops.init_ops import Initializer
from libspn.utils.serialization import register_serializable
from libspn import conf
def _tf_init_serialize(self):
return self.get_config()
def _tf_init_deserialize(self, data):
self.__init__(**{k: v for k, v in data.items() if k... |
3237744 | import functools
import time
from flask import current_app, g, url_for
import requests
from patchserver.models import WebhookUrls
def webhook_event(func):
"""A decorator that will send a webhook event notification to a all URLs
saved in the Patch Server database.
"""
@functools.wraps(func)
def ... |
3237779 | import torch
from torch.nn import Module, MSELoss, L1Loss
from .common_losses import SmoothnessLoss
class SupervisedL1Loss(Module):
def __init__(self, **kwargs):
super(SupervisedL1Loss, self).__init__()
self.l1_loss = L1Loss()
def forward(self, pc_source: torch.Tensor, pc_target: torch.Tensor... |
3237784 | import cv2
img = cv2.imread("image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
new_img = cv2.threshold(gray,120,255,cv2.THRESH_BINARY)
cv2.imwrite("thresholding.jpg", new_img[1])
cv2.imshow("thresholding", new_img[1])
|
3237795 | import medic
from maya import OpenMaya
from maya import cmds
class UnFrozenTransforms(medic.PyTester):
Identity = OpenMaya.MMatrix()
def __init__(self):
super(UnFrozenTransforms, self).__init__()
def Name(self):
return "UnFrozenTransforms"
def Description(self):
return "Chec... |
3237853 | load("//bazel/rules/cpp:object.bzl", "cpp_object")
def generate_unilang_token_files():
native.genrule(
name = "unilang_tokens",
outs = ["token_group.hpp", "token_group.cpp", "token_name.hpp", "token_name.cpp"],
tools = ["//code/programs/transcompilers/old_unilang/tokens:unilang_token_file_g... |
3237854 | from uuid import UUID
import graphene
import graphene_django_optimizer as gql_optimizer
from graphql.error import GraphQLError
from atlas.models import Change
from atlas.schema import ChangeNode
class Query(object):
changes = graphene.List(
ChangeNode,
id=graphene.UUID(),
object_type=gra... |
3237855 | import PyPDF2, os
#get all pdf files from directory
pdf_files=[filename for filename in os.listdir('.') if filename.endswith('.pdf')]
#sort filenames
pdf_files.sort()
count_merged_files = 0
pdfWriter = PyPDF2.PdfFileWriter()
#copy each pdf file to the final output file
for filename in pdf_files:
print(f'Merging \'... |
3237860 | class Animal():
name = 'Amy'
noise = "Grunt"
size = "Large"
color = "Brown"
hair = 'Covers body'
def get_color(self, abc):
return self.color + " " + abc
@property
def make_noise(self):
return self.noise
dog = Animal()
dog.get_color("red")
dog.make_noise
#arg = Posit... |
3237995 | from flask import Flask, jsonify, render_template, request
import os, urllib
from maraschino import app, RUNDIR, logger
from socket import *
from xbmc.xbmcclient import *
from maraschino.tools import get_file_list
from maraschino.models import XbmcServer
@app.route('/xhr/xbmc_notify', methods=['post'])
def xhr_notify... |
3238018 | import numpy as np
import math
class MLP:
def __init__(self, input_size, learning_rate):
self.weights = []
self.biases = []
self.input_size = input_size
self.num_layers = 1
self.learning_rate = learning_rate
def add_layer(self, k):
# Check if network only has o... |
3238037 | from e2edet.dataset.reader.image_reader import ImageReader
from e2edet.dataset.reader.point_reader import PointReader
__all__ = ["ImageReader", "PointReader"]
|
3238043 | from .adjust_code import adjust
from .expected_failure import NotImplementedToExpectedFailure
from .samples import SAMPLE_DATA, SAMPLE_SUBSTITUTIONS
IGNORE_ORDER_DICTIONARY = {
'tuple': ['set', 'frozenset', 'dict'],
'list': ['set', 'frozenset', 'dict'],
}
def _builtin_test(test_name, datatype, operation, sma... |
3238112 | import os
import app
import json
def real_path(file_name):
return os.path.dirname(os.path.abspath(__file__)) + file_name
def main():
try:
config_file = real_path('/config/config.json')
config = json.loads(open(config_file).read())
tunnel_type = str(config['tunnel_type'])
... |
3238117 | from ._version import __version__
from .mapping_utils import *
from .utils import *
from .plot_utils import * |
3238130 | import numpy as np
from bokeh.layouts import row, widgetbox
from bokeh.models import CustomJS, Slider, Legend
from bokeh.plotting import figure, output_file, show, ColumnDataSource
# Unchanged variables
N_years = 50
# Slider variables
annual_ROI = .06
annual_inflation = .03
annual_savings = 10000
retired_tax_rate = ... |
3238138 | from tir import Webapp
import unittest
class TECA700(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup("SIGATEC","11/12/2020","T1","D MG 01","28")
inst.oHelper.Program("TECA700")
def test_TECA700_001(self):
self.oHelper.SetButton("Incluir")
self.oHelper.Se... |
3238188 | import tensorflow as tf
from utils.nn import NN
class AttnGRU(object):
""" Attention-based GRU (used by the Episodic Memory Module). """
def __init__(self, config):
self.nn = NN(config)
self.num_units = config.num_gru_units
def __call__(self, inputs, state, attention):
with tf.vari... |
3238191 | from abc import abstractmethod
class IProvider(object):
""" SmsFramework provider interface
Implements methods to interact with the :class:`smsframework.Gateway`
"""
def __init__(self, gateway, name, **config):
""" Initialize the provider
:type gateway: Gateway
:... |
3238231 | import operator
import random
import re
from collections import OrderedDict
from hashlib import md5
from uuid import uuid4
from faker import Faker
from pganonymizer.exceptions import InvalidProvider, InvalidProviderArgument, ProviderAlreadyRegistered
fake_data = Faker()
class ProviderRegistry(object):
"""A reg... |
3238275 | def checkio(array):
if array:
return sum(array[::2])*array[-1]
return 0
if [-45]:
print [-45][-1]
print [-45][::2]
else:
print "321"
print checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"
print checkio([1, 3, 5]) == 30, "(1+5)*5=30"
print checkio([6]) == 36, "(6)*6=36"
print checkio([]) ... |
3238332 | import argparse
import torch
from torch import nn
import torch.nn.functional as F
import torchvision
from torchvision import transforms
torch.manual_seed(0)
from fedlab.core.server.handler import SyncParameterServerHandler
from fedlab.core.server.scale.manager import ScaleSynchronousManager
from fedlab.core.network ... |
3238338 | import mumaxc as mc
import micromagneticmodel.tests as mmt
class TestZeeman(mmt.TestZeeman):
def test_script(self):
for H in self.valid_args:
zeeman = mc.Zeeman(H=H)
script = zeeman._script
assert script.count("\n") == 3
assert script[0:2] == "//"
... |
3238358 | import unittest
from collections import namedtuple
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from typing import Any, AsyncGenerator, ContextManager, Generator, Iterable
import aiohttp
import asyncio
from aiohttp_wsgi.wsgi import run_server, WSGIEnviron, WSGIStartResponse
from aiohttp... |
3238386 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
SiPixelPhase1ResidualsExtra = DQMEDHarvester("SiPixelPhase1ResidualsExtra",
TopFolderName = cms.string('PixelPhase1/Tracks/ResidualsExtra'),
MinHits = cms.int32(30)
)
|
3238389 | import sys
import os
from typing import Any
import string
import json
template = """
/*
* DO NOT EDIT THIS FILE.
* This files was generated by test-generator.py.
* Any changes should be done there.
* DO NOT EDIT THIS FILE.
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include... |
3238443 | import collections
class Extractor:
"""
Extractor is a class that extracts and normalizes values from
incoming message dictionaries into ordered dictionaries based on the
`type` key of each message.
"""
def __init__(self, omit=None, normalizers=None, keys_by_type=None,
accept... |
3238459 | import unittest
from itertools import islice
# class TestNullTuningDriver(unittest.TestCase):
# def test_import(self):
# import ctree.tune
# def test_null_driver_stream(self):
# from ctree.tune import NullTuningDriver
# driver = NullTuningDriver()
# for cfg in islice(driver.c... |
3238506 | import unittest
from traits.testing.api import doctest_for_module
import codetools.util.tree as tree
class TreeDocTestCase(doctest_for_module(tree)):
pass
if __name__ == '__main__':
import sys
unittest.main(argv=sys.argv)
|
3238569 | from os.path import dirname, abspath, join
from setuptools import setup
with open(abspath(join(dirname(__file__), 'README.rst'))) as fileobj:
README = fileobj.read().strip()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
setup(
name='live_thumb',
description='M... |
3238609 | from __future__ import unicode_literals, print_function
import sys
import os
import re
def process_input(line_stream, basepath, chunksize, context_path):
outfile = None
try:
for i, line in enumerate(line_stream):
line = line.strip()
if not line:
continue
... |
3238669 | import types
import dis
import dill
from .serialization_helpers import has_uuid, do_import
GLOBALS_ERROR_MESSAGE="""
The function you tried to save uses information from global scope, which
can't be saved. This most frequently occurs when you use a package imported
outside the function. For more information, see:
http... |
3238688 | from .methods import InducingPointInitializer, FirstSubsample, ConditionalVariance, UniformSubsample, Kmeans
from .rls import RLS
from .kdpp_mcmc import KdppMCMC |
3238717 | from packaging import version
from .. import VERSION
from ..exceptions import B5ExecutionError
B5_VERSION = version.parse(VERSION)
def ensure_config_version(config_version_str: str) -> None:
if not isinstance(config_version_str, str):
config_version_str = str(config_version_str)
try:
config_... |
3238743 | class Solution:
def countTriples(self, n: int) -> int:
cnt = 0
for a in range(1, n + 1):
a2 = a * a
for b in range(1, n + 1):
c = (a2 + b * b) ** 0.5
cnt += c == int(c) and c <= n
return cnt
|
3238790 | import pathlib
import structlog
import click
import requests
import pandas as pd
from covidactnow.datapublic import common_init
from covidactnow.datapublic import common_df
from covidactnow.datapublic.common_fields import CommonFields
DATASET_URL = (
"https://github.com/covid-projections/covid-projections/raw/de... |
3238809 | import demistomock as demisto
from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import]
from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import]
import math
import string
def calculate_shannon_entropy(data, minimum_entropy):
"""Algorithm to determine the randomness of a given ... |
3238810 | import sys
from typing import List, Optional, TypeVar, Union
import torch
from torch import nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from squeezer.logging.abstract import AbstractLogger
from squeezer.logging.stub import StubLogger
from squeezer.policy import AbstractDistillationPolicy
from squ... |
3238854 | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "ASF"
addresses_name = "2021-03-18T09:55:17.756012/Ashford Democracy_Club__06May2021.tsv"
stations_name = "2021-03-18T09:55:17.756012/Ashford Democracy_Club__06... |
3238872 | from django.test import TestCase
from django.urls.resolvers import URLResolver, RegexPattern
class UrlsTestCase(TestCase):
def setUp(self):
pass
# "/"にアクセスしたときHomePageViewが呼ばれることを確認する
def test_access_index(self):
url_resolver = URLResolver(RegexPattern(''), "backend.urls")
... |
3238923 | import torch
from torch.nn import Module
def dice_loss(input, target):
"""Dice loss.
:param input: The input (predicted)
:param target: The target (ground truth)
:returns: the Dice score between 0 and 1.
"""
eps = 0.0001
iflat = input.view(-1)
tflat = target.view(-1)
intersectio... |
3238935 | import inspect
import sys
from unittest import mock
import pytest
from bottery.message import Response
from bottery.platforms import BaseEngine
from utils import AsyncMock
@pytest.fixture
def settings():
settings = mock.Mock()
sys.modules['settings'] = settings
yield settings
del sys.modules['settin... |
3238957 | import unittest
import numpy as np
import pandas as pd
from supervised.preprocessing.preprocessing_utils import PreprocessingUtils
class PreprocessingUtilsTest(unittest.TestCase):
def test_get_type_numpy_number(self):
tmp = np.array([1, 2, 3])
tmp_type = PreprocessingUtils.get_type(tmp)
se... |
3238997 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.plant_heating_and_cooling_equipment import DistrictHeating
log = logging.getLogger(__name__)
class TestDistrictHeating(unittest.TestCase):
def setUp(self):
self.fd,... |
3239005 | import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss
from torch_util.hypers_base import HypersBase
import logging
from transformers import (
AlbertConfig,
AlbertModel,
AlbertTokenizer,
BertConfig,
BertModel,
BertTokenizer,
)
logger = logging.getLogger(__name__)
MO... |
3239010 | works = {
'schema': {
'title': {
'type': 'string',
'required': True,
},
'description': {
'type': 'string',
},
'owner': {
'type': 'objectid',
'required': True,
# referential integrity constraint: value mus... |
3239047 | from __future__ import absolute_import, division, print_function, unicode_literals
# Which attributes we extract (with gumbocy) from the HTML.
# All the others are ignored
ATTRIBUTES_WHITELIST = frozenset([
"id",
"class",
"role",
"content",
"name",
"href",
"alt",
"src",
"hidden",
... |
3239072 | import csv
import torch
import logging
import imageio
import numpy as np
import functools
from scipy.misc import imsave
from tqdm import tqdm
from pathlib import Path
from src.runner.predictors.base_predictor import BasePredictor
from src.utils import denormalize
class Dsb15VSRPredictor(BasePredictor):
"""The DS... |
3239109 | ENRICH_SNAPSHOT_TASK_NAME = "enrich_snapshot_task"
PREVIEW_TASK_NAME = "preview_task"
SIMILARITY_SCAN_TASK_NAME = "similarity_scan_task"
SNAPSHOT_TASK_NAME = "take_snapshot_task"
YARA_SCAN_TASK_NAME = "yara_scan_task"
|
3239143 | import os
from setuptools import setup
def read(fname: str = None) -> str:
"""read files with in dir"""
if fname:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="Contact Book API",
version="0.0.1",
description=read('read.md'),
packages=(
'fast... |
3239162 | import torch
import math
######################################################################
############################ MODEL UTILS #############################
######################################################################
def num_trainable_params(model):
total = 0
for p in model.parameters()... |
3239190 | from contextlib import contextmanager
from unittest.mock import patch
from corehq.util.urlvalidate.ip_resolver import CannotResolveHost
@contextmanager
def hostname_resolving_to_ips(hostname, ips):
ip_tuples = [_create_tuple(ip) for ip in ips]
with patch('socket.getaddrinfo') as mock_getaddrinfo:
moc... |
3239194 | import io
from .STDFRecordTest import STDFRecordTest
from Semi_ATE.STDF import SBR
# Software Bin Record
# Function:
# Stores a count of the parts associated with a particular logical bin after
# testing. Thisbin count can be for a single test site (when parallel
# testing) or a total for all test sites.Th... |
3239222 | from typing import Any, Dict, Hashable
class SolverResult:
def __init__(
self, decisions, attempted_solutions
): # type: (Dict[Hashable, Any], int) -> None
self._decisions = decisions
self._attempted_solutions = attempted_solutions
@property
def decisions(self): # type: () -... |
3239253 | from django.db import models
# Model Tasks 1-5
#####################################
class Teacher(models.Model):
firstname = models.CharField(max_length=100)
surname = models.CharField(max_length=100)
def __str__(self):
return self.firstname
class Student(models.Model):
firstn... |
3239265 | import click
import sys
from elliottlib import Runtime
from elliottlib.cli.common import cli, use_default_advisory_option, find_default_advisory
from elliottlib import errata
pass_runtime = click.make_pass_decorator(Runtime)
@cli.command('advisory-impetus', short_help='Get advisory impetus')
@click.option(
'--a... |
3239393 | from flask_restplus import Namespace, fields, Resource, reqparse, inputs
from . import status_model
from rekcurd_dashboard.models import db, DataServerModel, DataServerModeEnum
from rekcurd_dashboard.utils import RekcurdDashboardException
from rekcurd_dashboard.apis import DatetimeToTimestamp
data_server_api_namespa... |
3239407 | HOME_PATH = "~/.autovizwidget"
CONFIG_FILE = "config.json"
GRAPH_RENDER_EVENT = "notebookGraphRender"
GRAPH_TYPE = "GraphType"
|
3239476 | from scripts.helpful_scripts import LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_account
from brownie import (
GovernorContract,
GovernanceToken,
GovernanceTimeLock,
Box,
Contract,
config,
network,
accounts,
chain,
)
from web3 import Web3, constants
# Governor Contract
QUORUM_PERCENTAGE = 4
#... |
3239482 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
rpcDcsInfoClient = DQMEDHarvester("RPCDcsInfoClient",
dcsInfoFolder = cms.untracked.string("RPC/DCSInfo"),
dqmProvInfoFolder = cms.untracked.string("In... |
3239497 | b"foo"
"foo"
"foo" "bar"
b"foo" b"bar"
r"\nfoo\s"
rb"\nfoo\s"
"a\\b\'b\"b"
"a\sb"
"a\x01b"
"a\0"
"a\00"
"a\000"
"a\0000"
b"\x90"
"""foo
bar"""
"""\
foo
bar
"""
"a\u007fb"
"a\U0000007fb"
b"a\u007fb"
b"a\U0000007fb"
|
3239535 | import pytest
from sqlalchemy.ext.hybrid import hybrid_method
from sqlalchemy.ext.hybrid import hybrid_property
from graygram import cache
@pytest.fixture(autouse=True)
def change_model_base_class(request):
cache.MODEL_BASE_CLASS = Model
def teardown():
from graygram.orm import db
cache.MOD... |
3239587 | from django.contrib import sitemaps
from django.core.urlresolvers import reverse
class StaticViewSitemap(sitemaps.Sitemap):
priority = 0.5
changefreq = 'monthly'
def items(self):
return ['landpage','robots','humans','google_plus_verify','terms','privacy',]
def location(self, item):
... |
3239595 | from reader._plugins import global_metadata
def test_plugin(make_reader, db_path):
reader = make_reader(db_path, plugins=[global_metadata.init_reader])
reader = make_reader(db_path, plugins=[global_metadata.init_reader])
reader.update_feeds()
assert dict(reader.get_global_metadata()) == {}
asser... |
3239601 | from itertools import islice, groupby
import time
from flask import render_template, current_app, request
from hubmap_api_py_client import Client
from .utils import get_default_flask_data, make_blueprint
from operator import itemgetter
from collections import defaultdict
from dataclasses import dataclass
bluepri... |
3239612 | USERNAME = 'username'
PASSWORD = 'password'
UPDATED_AT = 'updated_at'
EXPIRES_AT = 'expires_at'
CREATED_AT = 'created_at'
ACTIVE = 'active'
LOGINS_COUNT = 'logins_count'
SU = 'su'
BLANK = ''
INFO = 'info'
WARNING = 'warning'
SUCCESS ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.