id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3329516 | import base64
import json
import datetime
import os
import zipfile
import boto3
# DEFINE WHITELIST & RULESET LOCATION
# Define the Bucket prefix where the ruleset.zip and whitelist are posted in the Compliance Account.
BUCKET_PREFIX = 'compliance-engine-codebuild-source'
ORIGINAL_ZIP_RULES = 'ruleset.zip'
ORIGINAL_ZIP... |
3329523 | import numpy as np
import manifolds
from manifolds import Scene as CppScene
from manifolds import Ray2f, Shape
from misc import *
from path import Path
from draw import *
class Scene:
def __init__(self, shapes):
self.shapes = shapes
self.offset = [0, 0]
self.zoom = 1.0
self.scale ... |
3329572 | import numpy as np
import cv2
img1 = cv2.imread('city1.jpg')
img2 = cv2.imread('city2.jpg')
# numpy image addition will give modulo operation (img1+img2)%256
img_np = img1 + img2
# cv2 image addition will give simple addition
img_cv = cv2.add(img1,img2)
# to show the image
cv2.imshow('image numpy',img_np)
cv2.waitK... |
3329585 | import torch
import torch.nn as nn
class Transformer(nn.Module):
def __init__(self, base_model, num_classes, method):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
self.method = method
self.linear = nn.Linear(base_model.config.hidden_size, ... |
3329590 | from ppq.core import (PASSIVE_OPERATIONS, OperationQuantizationConfig,
QuantizationPolicy, QuantizationProperty,
QuantizationStates, RoundingPolicy, TargetPlatform,
TensorQuantizationConfig)
from ppq.IR import BaseGraph
from ppq.IR.base.graph import Oper... |
3329601 | import sys
import os
import docassemble.base.config
if __name__ == "__main__":
docassemble.base.config.load(arguments=sys.argv)
def main():
from docassemble.base.config import daconfig
webapp_path = daconfig.get('webapp', '/usr/share/docassemble/webapp/docassemble.wsgi')
wsgi_file = webapp_path
if... |
3329609 | from flask import request
from clay import app, config
import json
log = config.get_logger('clay.docs')
def parse_docstring_param(directive, key, value):
p = {
'name': key,
'description': value.split('{', 1)[0],
'required': False,
'dataType': 'string',
'type': 'primitive',... |
3329670 | from __future__ import unicode_literals
from django.apps import AppConfig
lorem = """
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At
vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd g... |
3329691 | import sys
import time
import logging
import functools
from typing import List, Mapping, Callable
from nspawn.base import engine
from nspawn.base import token
from nspawn.app.engine.parser import SetupAction
from nspawn.base.machine import (
machine_result_from_url,
perform_machine_create,
perform_machine_d... |
3329766 | import torch
class SplitNN(torch.nn.Module):
def __init__(self, clients, optimizers):
super().__init__()
self.clients = clients
self.optimizers = optimizers
self.num_clients = len(clients)
self.recent_output = None
def forward(self, x):
intermidiate_to_next_cli... |
3329838 | from numpy import pi, array, transpose
from SciDataTool import Data1D, DataTime
from ....Functions.Electrical.coordinate_transformation import dq2n
from ....Functions.Winding.gen_phase_list import gen_name
def get_Is(self):
"""Return the stator current DataTime object
Parameters
----------
self : O... |
3329872 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import h5py
from PIL import Image
import os.path as osp
from scipy.io import loadmat
from urllib.request import urlretrieve
from .datasetbase import DataSetBase
from lib.utils.util import un... |
3329880 | from .config import YamlConfig
from .registry import Registry, build_from_cfg, build_ray_obj_from_cfg
__all__ = [
"Registry",
"build_from_cfg",
"build_ray_obj_from_cfg",
"YamlConfig",
]
|
3329884 | import random
from audiomate.corpus.subset import utils
def run_split_identifiers():
identifiers = list(range(10000))
proportions = {'a': 0.2, 'b': 0.2, 'c': 0.6}
utils.split_identifiers(identifiers, proportions)
def test_split_identifiers(benchmark):
benchmark(run_split_identifiers)
def run_get_... |
3329893 | from osr2mp4.ImageProcess import imageproc
def prepare_rankingscorecounter(scorenumber):
"""
:param scorenumber: ScoreNumber
:return: [PIL.Image]
"""
img = {}
hitresultimg = {}
c = 0
for image in scorenumber.score_images:
imgscore = imageproc.change_size(image.img, 1.2999, 1.2999)
img[c] = imgscore
hit... |
3329910 | import re
import string
import Stemmer
# top 25 most common words in English and "wikipedia":
# https://en.wikipedia.org/wiki/Most_common_words_in_English
STOPWORDS = set(['the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have',
'i', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you',
... |
3329941 | class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return "Node({})".format(self.value)
__repr__ = __str__
class Stack:
def __init__(self):
self.top = None
self.count = 0
self.minimum = None
def __str__(s... |
3329961 | import fnmatch
from scrapyd_client.utils import get_request, post_request
def get_projects(url, pattern='*'):
""" Returns the project names deployed in a Scrapyd instance.
:param url: The base URL of the Scrapd instance.
:type url: str
:param pattern: A globbing pattern that is used to fi... |
3329976 | import time
import random
import itertools
# import gc
import os
import sys
import datetime
import numpy as np
import yaml
import pickle
from operator import itemgetter
from optparse import OptionParser
from sklearn.model_selection import KFold
from sklearn.metrics import roc_curve, auc, average_precision_score
sys.... |
3329995 | import numpy as np
from TorchTSA.model import ARMAGARCHModel
from ParadoxTrading.Chart import Wizard
from ParadoxTrading.Fetch.ChineseFutures import FetchDominantIndex
from ParadoxTrading.Indicator import LogReturn
from ParadoxTrading.Indicator.TSA import ARMAGARCH
fetcher = FetchDominantIndex()
market = fetcher.fet... |
3330082 | r"""
Produces a plot of the densities of infall, star formation, and gas as a
function of simulation time for all models.
"""
from .. import env
from .utils import (named_colors, mpl_loc, yticklabel_formatter,
dummy_background_axes)
from ..._globals import ZONE_WIDTH
import matplotlib.pyplot as plt
import math as m
i... |
3330094 | import numpy as np
from . import _fastmath_ext
__all__ = ['inv2', 'inv3']
def inv3(matrices):
if matrices.shape[-2:] != (3, 3):
raise ValueError("Can only invert 3x3 matrices")
Ts = matrices.reshape((-1, 3, 3))
Qs = _fastmath_ext.inv3(Ts)
return Qs.reshape(matrices.shape).astype(matrices.dtyp... |
3330130 | from itertools import combinations
from typing import List
import numpy as np
from numpy.typing import ArrayLike
from dexp.utils import xpArray
from dexp.utils.backends import Backend
__all__ = [
"first_derivative_func",
"first_derivative_kernels",
"second_derivative_func",
"second_derivative_kernels... |
3330134 | if __name__ == '__main__':
start = int(input('Start: '))
stop = int(input('Stop: '))
step = int(input('Step: '))
print(sum(list(range(start, stop + 1, step))))
|
3330202 | from abc import ABC, abstractmethod
class NullBase(ABC):
"""
Abstract class for generating null model parcellations.
"""
@abstractmethod
def __init__(self):
pass
@abstractmethod
def fit(self):
pass
|
3330222 | import thunderbolt
import unittest
from unittest.mock import patch
from mock import MagicMock
from contextlib import ExitStack
import pandas as pd
from thunderbolt.client.local_directory_client import LocalDirectoryClient
from thunderbolt.client.gcs_client import GCSClient
from thunderbolt.client.s3_client import S3Cli... |
3330240 | import os
import getopt
import sys
import subprocess
from winappdbg import Debug, Crash, win32, HexDump
from time import time
from winappdbg.util import MemoryAddresses
class Coverage:
verbose = False
bbFiles = {}
bbFilesBreakpints = []
bbFilesData = {}
bbOriginalName = {}
modules = []
fileOutput = None
#Co... |
3330295 | import matplotlib.pyplot as plt
import numpy as np
BLUE = (55 / 255, 125 / 255, 255 / 255)
fig, ax = plt.subplots()
ax.bar(np.arange(1, 7), [6.58, 7.55, 8.21, 8.25, 11.58, 31.82], 0.4, color=BLUE)
for spine in plt.gca().spines.values():
if spine.spine_type != 'bottom' and spine.spine_type != 'left':
spi... |
3330335 | from typing import Generator, Tuple
import numpy as np
from showml.utils.exceptions import InvalidShapeError
def initialize_params(num_dimensions: int) -> Tuple[np.ndarray, np.ndarray]:
"""Initialize the weights and bias for a model.
Args:
num_dimensions (int): The number of dimensions/features nee... |
3330344 | import argparse
import os
parser = argparse.ArgumentParser(description="Run commands")
parser.add_argument("--logdir", type=str)
parser.add_argument("--hpconfig", type=str, default=",")
parser.add_argument("--datadir", type=str)
def new_tmux_cmd(name, cmd):
if isinstance(cmd, (list, tuple)):
cmd = " ".jo... |
3330347 | def coding_problem_18(arr, k):
"""
Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each
sub-array of length k. Do this in O(n) time and O(k) space. You can modify the input array in-place and you do not
need to store the results. You can simp... |
3330384 | c.fonts.default_family = "Iosevka"
c.fonts.messages.error = "11pt default_family"
c.fonts.messages.info = "11pt default_family"
c.fonts.messages.warning = "11pt default_family"
c.fonts.statusbar = "bold default_size default_family"
|
3330434 | import pickle
import numpy as np
def convert_task_sub(task, sub):
timestamps_list = []
types_list = []
lengths_list = []
timeintervals_list = []
file_path = '../data/' + task + '/' + sub +'.pkl'
with open(file_path, 'rb') as f:
try:
file = pickle.load(f, encoding='latin1')
... |
3330509 | from collections import deque
from hwt.hdl.constants import NOP
from hwt.simulator.agentBase import SyncAgentBase
from hwtSimApi.hdlSimulator import HdlSimulator
from hwtSimApi.triggers import WaitCombRead, WaitWriteOnly
class RdSyncedAgent(SyncAgentBase):
"""
Simulation/verification agent for RdSynced inter... |
3330518 | from distutils.core import setup
setup(
name='event-bus',
version='1.0.2',
packages=['event_bus'],
url='https://github.com/seanpar203/event-bus',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='A simple python event bus.',
download_url='https://github.com/seanpar203/event-bus/archive/1.0.... |
3330554 | from absl import app
from absl import flags
from bark_ml.experiment.experiment_runner import ExperimentRunner
FLAGS = flags.FLAGS
flags.DEFINE_enum("mode",
"visualize",
["train", "visualize", "evaluate", "print", "save"],
"Mode the configuration should be executed... |
3330592 | from functools import reduce
import fym
default_settings = fym.parser.parse()
settings = fym.parser.parse(default_settings)
def register(d, base=None):
"""Register a configuration.
.. versionadded:: 1.2.2
Parameters
----------
d : dict_like
A configuration dictionary to be registered.
... |
3330596 | from task_geo.data_sources.mobility.mobility_connector import mobility_connector
from task_geo.data_sources.mobility.mobility_formatter import mobility_formatter
def mobility():
"""Retrieve the mobility reports from Google.
Arguments:
None
Returns:
pandas.DataFrame
Example:
>>>... |
3330599 | from torch import nn
import torch.nn.functional as F
def _reduce(x, reduction='elementwise_mean'):
if reduction is 'none':
return x
elif reduction is 'elementwise_mean':
return x.mean()
elif reduction is 'sum':
return x.sum()
else:
raise ValueError('No such reduction {} defined'.format(reducti... |
3330636 | from snoo.client import Client
from snoo import run
import pytest
def test_client():
client = Client()
assert client.config is not None
def test_cli():
with pytest.raises(SystemExit):
run()
|
3330643 | def main():
print "This program calculates the future value"
print "of a 10 year investment."
principal = input("Enter the initial principal: ")
apr = input("Enter the annualized interest rate: ")
print "Year","Value"
print "-----------"
for i in range(10):
print i,
principal ... |
3330646 | from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def index():
username = request.form['username']
password = request.form['password']
if username == "xugaoxiang" and password == "<PASSWORD>":
return f"<html><body>Welcome {username}</body></html>"
else:
... |
3330648 | from django.urls import path, include, re_path
from rest_framework import routers
from django_candy import views
app_name = 'django_candy'
router = routers.SimpleRouter()
router.register(r'api/v1/(?P<app_label>[\w]+)/(?P<model_name>[\w]+)', views.CommonViewSet, basename='candy')
urlpatterns = router.urls
urlpatt... |
3330692 | import h5py
from .descriptions import three_groups_record_description
from .utils import generate_fake_record
def test_standardize_signals_length_durations():
record_description = three_groups_record_description
generate_fake_record(record_description)
with h5py.File('/tmp/fake.h5', 'r') as fake_h5:
... |
3330784 | import io
import os
import unittest
import chess.pgn
from puzzlemaker.puzzle_finder import find_puzzle_candidates
from puzzlemaker.analysis import AnalysisEngine
def pgn_file_path(pgn_filename) -> io.TextIOWrapper:
cur_dir = os.path.dirname(os.path.abspath(__file__))
return open(os.path.join(cur_dir, '..', ... |
3330793 | import string
# Ceaser Cipher
# plain text: A B C D.... (if key is 3) || ascii value: 65, 66, 67, 68
# cipher text: D E F G (adding the key to the ascii value) || ascii value: 68, 69, 70, 71
class CaeserCipher:
def __init__(self, key=3):
self.key = key%26 # whatever the key value it is append to th... |
3330831 | from typing import Dict, Optional
from fastapi import Form, HTTPException
from fastapi.openapi.models import OAuthFlows
from fastapi.security import OAuth2
from fastapi.security.utils import get_authorization_scheme_param
from pydantic import BaseModel
from starlette.requests import Request
from starlette.status impor... |
3330913 | import sys
from .core import *
import pymel.core as pymel
__dependencies__ = [
('deps',)
]
current_dir = os.path.dirname(os.path.realpath(__file__))
for dependency in __dependencies__:
path = os.path.realpath(os.path.join(current_dir, *dependency))
sys.path.append(path)
# HACK: Load matrixNodes.dll
pymel... |
3330933 | import vcf
import sys
# HOW TO RUN:
# use snpEff to annoate VCF file
# SLOW:
# python kaks.py annotated_vcf.vcf > kaks.txt
# FASTER:
# grep '^#\|missense_variant\|synonymous_variant' annotated_vcf.vcf > mis_syn.txt
# python kaks.py mis_syn.txt > kaks.txt
file = sys.argv[1]
vcf_reader = vcf.Reader(open(file, 'r'))
g... |
3330958 | from asdl import const # For const.NO_INTEGER
from asdl import py_meta
from osh.meta import RUNTIME_TYPE_LOOKUP as TYPE_LOOKUP
class part_value_e(object):
StringPartValue = 1
ArrayPartValue = 2
class part_value(py_meta.CompoundObj):
ASDL_TYPE = TYPE_LOOKUP.ByTypeName('part_value')
class StringPartValue(part_v... |
3330997 | from pylab import *
ion()
import MMCorePy
mmc = MMCorePy.CMMCore()
mmc.loadDevice("cam","DemoCamera","DCam")
mmc.initializeDevice("cam")
print "Test acquire and display of monochrome images."
figure()
mmc.setCameraDevice("cam")
mmc.snapImage()
im1 = mmc.getImage()
imshow(im1,cmap = cm.gray)
"""
print "Test acquire ... |
3331030 | import sys
import threading
from django.core.management import call_command
class ProcessFirmwareThread(threading.Thread):
def __init__(self):
super(ProcessFirmwareThread, self).__init__()
def run(self):
call_command('process_firmware')
def start_process_thread():
thread = ProcessFirmwar... |
3331057 | from globals import *
import life as lfe
import judgement
import rawparse
import action
import speech
import brain
import jobs
import logging
def create_question(life, life_id, gist, ignore_if_said_in_last=0, recent_time=0, **kwargs):
_target = brain.knows_alife_by_id(life, life_id)
_question = {'gist': gist, 'ar... |
3331126 | import functools
from contextlib import closing
from copy import deepcopy
from xml.etree import ElementTree
from zipfile import ZipFile
from heroicons._compat import open_binary, str_removeprefix
class IconDoesNotExist(Exception):
pass
@functools.lru_cache(maxsize=128)
def _load_icon(style: str, name: str) -> ... |
3331145 | import re
from rest_framework import serializers, renderers, parsers
class JSONRenderer(renderers.JSONRenderer):
def render(self, data, *args, **kwargs):
if data:
data = recursive_key_map(underscore_to_camelcase, data)
return super(JSONRenderer, self).render(data, *args, **kwargs)
c... |
3331204 | import os
class LinuxFfmpegConversionWorker(object):
"""
A batch converter that relies on a boolean as the final argument to determine if we should run the method.
"""
@staticmethod
def execute_commands():
sudoPassword = '<PASSWORD>'
command = 'mount -t vboxsf myfolder /home/myus... |
3331229 | from .constant import (PAD,
UNK,
BOS,
EOS,
DIGIT,
PAD_WORD,
UNK_WORD,
BOS_WORD,
EOS_WORD,
DIGIT_WORD,
... |
3331265 | from __future__ import print_function
import array
import atexit
import errno
import gc
import logging
import _multiprocessing
import os
import pwd
import random
import signal
import socket
import struct
import sys
import threading
import time
import traceback
def preload():
import argparse
import base64
... |
3331294 | import os as os
import json
import numpy as np
import time
import random
import logging
import pickle
from abc import abstractmethod
from sklearn.model_selection import train_test_split
class BaseBaseline():
def __init__(self, name):
self.configure_logging()
self.name = name
self.confi... |
3331308 | import os
BENEPAR_SERVER_INDEX = "https://kitaev.com/benepar/index.xml"
_downloader = None
def get_downloader():
global _downloader
if _downloader is None:
import nltk.downloader
_downloader = nltk.downloader.Downloader(server_index_url=BENEPAR_SERVER_INDEX)
return _downloader
def downloa... |
3331335 | import logging
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
def get_first_missing_key(inp_dict: Dict, keys: List[str]) -> Optional[str]:
cur_val = inp_dict
for key in keys:
if cur_val is None:
return None
if not isinstance(cur_val, dict) or key... |
3331356 | from collections import defaultdict
from os import replace
import numpy as np
from copy import deepcopy
from .base_sampler import BaseSampler
class MPerClassFullSampler(BaseSampler):
"""
Give m samples per class (Try to cover all the samples). In the distributed mode, random seed should be asigned manually.
... |
3331384 | from app import db
import datetime
from flask_login import current_user
import pytz
from sqlalchemy import and_, or_
from sqlalchemy.orm import aliased
# exact match, provides text input
class Filter:
def __init__(self, column, nullable=False):
self.column = column
self.nullable = nullable
def... |
3331391 | string, num = input(), int(input())
while len(string) < num:
string += string
string = string[:num]
print(string.count('a'))
|
3331430 | from misc.callback import callback
from gui.objects.group import Group
from gui.objects.scene import Scene
class LayerManager(Group, Scene):
def __init__(self):
Group.__init__(self, 'root', self)
Scene.__init__(self)
@callback
def add_layer(self, layer_name, layer, path=None):
i... |
3331443 | import unittest
import os
from icolos.core.containers.compound import Compound, Enumeration
from icolos.core.workflow_steps.prediction.predictor import StepPredictor
from icolos.utils.enums.step_enums import StepBaseEnum, StepPredictorEnum
from tests.tests_paths import PATHS_EXAMPLEDATA, get_mol_as_Conformer
from ic... |
3331455 | def rob(self, nums: List[int]) -> int:
length = len(nums)
if length == 0:
return 0
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1,length):
if i==1:
dp[i] = max(dp[0],nums[i])
elif i==2:
dp[i] = dp[0]+nums[i]
else:
dp[i] = max(dp[i-2],dp[i-3]) + nums... |
3331498 | import torch
class PrefixEncoder(torch.nn.Module):
r'''
The torch.nn model to encode the prefix
Input shape: (batch-size, prefix-length)
Output shape: (batch-size, prefix-length, 2*layers*hidden)
'''
def __init__(self, config):
super().__init__()
self.prefix_projection = conf... |
3331517 | from ..factory import Type
class pageBlockMap(Type):
location = None # type: "location"
zoom = None # type: "int32"
width = None # type: "int32"
height = None # type: "int32"
caption = None # type: "pageBlockCaption"
|
3331560 | import sys, os.path
from datetime import datetime, timedelta
if len(sys.argv) < 2:
print(f'usage: {sys.argv[0]} [log_files]')
sys.exit()
last_line = None
start_datetime = None
duration = timedelta(0)
for log_file in sys.argv[1:]:
with open(log_file) as f:
lines = f.readlines()
for line in... |
3331601 | from ..CloudCoverage import CloudCoverage
from .BaseComponent import BaseComponent
class SkyConditionObservationComponent(BaseComponent):
''' handler for GF1 data type '''
def loads(self, string):
self.sky_condition_observation = {'total_coverage': CloudCoverage(string[0:2],
... |
3331612 | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class EventsConfig(AppConfig):
name = 'purpleserver.events'
verbose_name = _('Custom Pricing')
def ready(self):
from purpleserver.events import signals
signals.register_signals()
|
3331631 | from django.db import models
from hello_django.storage_backends import PublicMediaStorage, PrivateMediaStorage
class Upload(models.Model):
uploaded_at = models.DateTimeField(auto_now_add=True)
file = models.FileField(storage=PublicMediaStorage())
class UploadPrivate(models.Model):
uploaded_at = models.... |
3331634 | from __future__ import print_function
import nifty
import numpy
G = nifty.graph.UndirectedGraph
CG = G.EdgeContractionGraph
GMCO = G.MulticutObjective
CGMCO = CG.MulticutObjective
def testUndirectedGraph():
g = nifty.graph.UndirectedGraph(4)
edges = numpy.array([[0,1],[0,2],[0,3]],dtype='uint64')
... |
3331648 | import pandas as pd
import cv2
import geopandas as gpd
import os,sys
from tqdm import tqdm as tqdmn
import numpy as np
import pickle
import argparse
from scipy.special import binom
import multiprocessing
from joblib import Parallel, delayed
from functools import reduce
from scipy.stats import entropy
from skimage impor... |
3331655 | from PIL import Image
from ..config import Config
import os
from ..tools.debug import Debug
from .compress_manager import CompressManager
from ..tools.file_tools import FileTools
class Compress:
def __init__(self, imageFile: str, compressLimit: int = 500) -> None:
"""初始化压缩上下文管理器
imageFile: 用于压缩的原图... |
3331660 | import numpy as np
import matplotlib.pyplot as plt
freq = 5.
time = np.arange(0., 1.0, 0.01)
sine = np.sin(2 * np.pi * freq * time)
fig = plt.figure()
fig.set_size_inches(5.5, 2.5)
ax = fig.add_subplot(111)
ax.plot(time, sine, color="dodgerblue", marker='.', markersize=5, label="sinewave",
ls="solid", lw=1.2... |
3331686 | import numpy as np
def RotZ(heading):
psi = heading
R = np.array([[np.cos(heading), -np.sin(heading), 0],
[np.sin(heading), np.cos(heading), 0],
[0, 0, 1]])
return R
R = RotZ(-1.889)
wayp = np.array([[6000],
[-300],
[-... |
3331691 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import subprocess
import threading
import json
import numpy as np
import ast
import tempfile
import time
import shutil
FNULL = open(os.devnull, 'w')
# Assumes spice.jar is in the same di... |
3331692 | import json
import os
import pathlib
import shutil
import subprocess
import pytest
from zntrack import zn
from zntrack.core.base import Node
@pytest.fixture
def proj_path(tmp_path):
shutil.copy(__file__, tmp_path)
os.chdir(tmp_path)
subprocess.check_call(["git", "init"])
subprocess.check_call(["dvc"... |
3331710 | from mongo_dynamic_fixture.fixture import Fixture
def N(*args, **kwargs):
schema_cls = args[0] if args else None
extra = kwargs.pop('extra', {})
kwargs.update(extra)
if schema_cls is not None:
data = schema_cls().generate(**kwargs)
else:
data = kwargs
return data
def G(conn,... |
3331711 | def ans(n, data, c):
cowplaced = 0
lastpos = data[0]
for i in xrange(1, len(data)):
if data[i] - lastpos >= n:
cowplaced += 1
lastpos = data[i]
if cowplaced == c:
return True
return False
data = [int(i) for i in raw_input().split()]
n = data[0... |
3331775 | from .locations import (
LocationByAddress,
LocationByPoint,
LocationByQuery
)
from .elevations import ElevationsApi
from .trafficincidents import TrafficIncidentsApi
|
3331830 | import sys
from floyd.manager.auth_config import AuthConfigManager
from floyd.exceptions import (
FloydException, AuthenticationException, NotFoundException
)
from floyd.client.base import FloydHttpClient
from floyd.model.project import Project
from floyd.log import logger as floyd_logger
from floyd.cli.utils impor... |
3331838 | import pyOcean_cpu as ocean
a = ocean.cfloat(1+2j)
b = ocean.cfloat([1,2,3+2j])
print(b)
print("\n--------- Scalar A times tensor B ---------")
print(ocean.multiply(a,b))
print(ocean.multiply(a,'C',b))
print(ocean.multiply(a,b,'C'))
print(ocean.multiply(a,'C',b,'C'))
print("\n--------- Tensor B times scalar A -----... |
3331843 | from bingads.v13.internal.bulk.mappings import _SimpleBulkMapping
from bingads.v13.internal.bulk.string_table import _StringTable
from bingads.service_client import _CAMPAIGN_OBJECT_FACTORY_V13
from bingads.v13.internal.extensions import *
from .common import _BulkAdExtensionBase
from .common import _BulkCampaignAdExt... |
3331850 | from .callables import \
getID, getArgs, getRawFunction,\
ListenerInadequate, \
CallArgsInfo
from .listenerimpl import Listener, ListenerValidator
|
3331895 | S = int(input()) # number of stones in heap
N = int(input()) # min number of stones in heap, when game ends
# player is allowed to do +1, +3 or x2
Plus = [1, 3]
Mul = [2]
def winner(s, n):
win_loose = [-1] * n
win_loose[n - 1] = 0
for i in range(n - 2, s - 2, -1):
flag = False
for k in P... |
3331913 | from . import tests
from .data_structures import (
YTClumpContainer,
YTClumpTreeDataset,
YTDataContainerDataset,
YTGrid,
YTGridDataset,
YTGridHierarchy,
YTNonspatialDataset,
YTNonspatialGrid,
YTNonspatialHierarchy,
YTProfileDataset,
YTSpatialPlotDataset,
)
from .fields import... |
3331983 | from rllab.policies.base import StochasticPolicy
from sandbox.finetuning.policies.test_hier_snn_mlp_policy import GaussianMLPPolicy_snn_hier
from rllab.envs.normalized_env import normalize
from sandbox.finetuning.envs.mujoco.swimmer_env import SwimmerEnv
from sandbox.finetuning.envs.mujoco.gather.swimmer_gather_env imp... |
3331988 | from django import forms
from data_interrogator.fields import CSVMultipleCharField
from data_interrogator.forms import PivotTableForm, InterrogatorTableForm
class AdminPivotTableForm(PivotTableForm):
column_1 = forms.CharField()
column_2 = forms.CharField()
aggregators = CSVMultipleCharField(required=Fal... |
3332009 | def snake_case_to_camel_case(snake_case: str) -> str:
"""
Helper method for converting a snake_case'd value to camelCase
input: pub_key_cred_params
output: pubKeyCredParams
"""
parts = snake_case.split("_")
converted = parts[0].lower() + "".join(part.title() for part in parts[1:])
# Ma... |
3332015 | def extractTwelveMonthsofMay(item):
"""
# 'Twelve Months of May'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'My Mister Ostrich' in item['tags']:
return buildReleaseMessageWithType(item, '<NAME>... |
3332036 | import pytest
import sqlalchemy as sa
from sqlalchemy.orm import backref
from sqlalchemy_utils import auto_delete_orphans, ImproperlyConfigured
@pytest.fixture
def tagging_tbl(Base):
return sa.Table(
'tagging',
Base.metadata,
sa.Column(
'tag_id',
sa.Integer,
... |
3332064 | import os
from src.svg_wheel import generate_svg_wheel
from src.utils import get_packages, remove_irrelevant_packages, save_to_file, compare_and_notify
from src.clients import s3Client, gsClient
IS_LAMBDA_FUNCTION = os.environ["IS_LAMBDA_FUNCTION"]
S3_BUCKET = os.environ["S3_BUCKET"]
SENDER_EMAIL = os.environ["SEND... |
3332078 | from PIL import Image
import os
import argparse
class DataPreprocessor(object):
def __init__(self, root_dir, new_w, v_crop_size, stride):
assert os.path.exists(root_dir), f'{root_dir} does not exist'
self.root_dir = root_dir
self.v_crop_size = v_crop_size
self.stride = stride
... |
3332103 | import argparse
import time
import numpy
import netket as nk
from flowket.utils.jacobian import predictions_jacobian as get_predictions_jacobian
from flowket.layers import ToComplex64, ToComplex128, ComplexConv1D
from flowket.deepar.layers import PeriodicPadding
from flowket.layers.complex.tensorflow_ops import lncosh... |
3332117 | from .data.dataset_utils import (
Thermopack,
get_coordinate,
load,
)
from .data import thermostat_configs
from .data import tokenization
from .visualize import Heatmap
__all__ = [Thermopack, get_coordinate, load, thermostat_configs, tokenization, Heatmap]
|
3332149 | import torch.nn as nn
from ..abs import BridgeBase
class Bridge(BridgeBase):
r"""
Bridge the connection between encoder and decoder.
"""
def __init__(self, args):
super().__init__(args)
self.num_layers = args.num_layers
self.dec_init = nn.Sequential(nn.Linear(args.hidden_size... |
3332156 | import pytest
from pylenium.driver import Pylenium
@pytest.fixture
def qap_dev(py) -> Pylenium:
py.visit('https://qap.dev')
py.getx('//*[contains(@class, "Footer") and text()="Present at QAP"]').should().be_visible()
return py
def test_custom_perf_metrics(qap_dev):
""" Check Pylenium's native web p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.