id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9854774 | import re
import sys
sys.path.append('../../common')
from env_indigo import *
indigo = Indigo()
indigo.setOption("ignore-stereochemistry-errors", True)
indigo.setOption("molfile-saving-skip-date", True)
def reducePrecision(str_data):
# Remove last digit because of float-point rounding differences between Windows ... |
9854825 | from __future__ import print_function
from random import shuffle
import os
import argparse
import pickle
from get_image_paths import get_image_paths
from get_tiny_images import get_tiny_images
from build_vocabulary import build_vocabulary
from get_bags_of_sifts import get_bags_of_sifts
from visualize import visualize
... |
9854878 | import pytest
from flask_unchained.constants import DEV
from flask_unchained.unchained import Unchained
from ._bundles.empty_bundle import EmptyBundle
from ._bundles.myapp import MyAppBundle
from ._bundles.vendor_bundle import VendorBundle, awesome
class FakeApp:
def add_url_rule(self, rule, endpoint=None, view... |
9854888 | from django.apps import apps
from django.conf import settings
from django.conf.urls import url
from django.utils.safestring import mark_safe
from wagtail.admin.site_summary import SiteSummaryPanel
from wagtail.core import hooks
from .views import QuickCreateView
class QuickCreatePanel:
order = 50
def rende... |
9854903 | from .base import BaseDistribution, DiagGaussian, ClassCondDiagGaussian, \
GlowBase, AffineGaussian, GaussianMixture, GaussianPCA
from .target import Target, TwoMoons, CircularGaussianMixture, RingMixture
from .encoder import BaseEncoder, Dirac, Uniform, NNDiagGaussian
from .decoder import BaseDecoder, NNDiagGauss... |
9854935 | import functools
import os
import pytest
import testinfra
if os.environ.get('KITCHEN_USERNAME') == 'vagrant':
if 'windows' in os.environ.get('KITCHEN_INSTANCE'):
test_host = testinfra.get_host('winrm://{KITCHEN_USERNAME}:{KITCHEN_PASSWORD}@{KITCHEN_HOSTNAME}:{KITCHEN_PORT}'.format(**os.environ), no_ssl=Tru... |
9854967 | import json
import asyncpg
__all__ = ['create_pool']
async def _set_codec(con):
await con.set_type_codec(
'jsonb',
schema='pg_catalog',
encoder=json.dumps,
decoder=json.loads,
format='text'
)
async def _create_pool(*, init=None, **kwargs):
if not init:
a... |
9854971 | import sys, os; sys.path.insert(0, os.path.abspath('..'))
# Read the Docs needs this bit to import Hyrule.
html_title = 'The Hyrule manual'
extensions = [
'sphinx.ext.napoleon',
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinxcontrib.hydomain']
exclude_patterns = ['_build']
smartquotes = Fa... |
9854975 | import importlib
from utils.hparams import set_hparams, hparams
def run_task():
assert hparams['task_cls'] != ''
pkg = ".".join(hparams["task_cls"].split(".")[:-1])
cls_name = hparams["task_cls"].split(".")[-1]
task_cls = getattr(importlib.import_module(pkg), cls_name)
task_cls.start()
if __name... |
9854987 | import json
import networkx as nx
class JsonImportMixin:
"""Json import/export mixin for DnaSupplier."""
@classmethod
def from_json_data(cls, json_file=None, data=None, dna_suppliers_dict="default"):
"""
Returns
-------
levels, suppliers_dict, main_id.
"""
... |
9854993 | def train_PixelLink(config_file):
import sys
sys.path.append('./detection_model/PixelLink')
import net
import numpy as np
import torch
import torch.nn as nn
import datasets
from torch import optim
from criterion import PixelLinkLoss
import loss
import config
import post... |
9855018 | import warnings
import numpy as np
import graphgallery as gg
import scipy.sparse as sp
from typing import Optional
from .shape import maybe_shape, maybe_num_nodes
from ..functions import get_length
__all__ = ['remove_self_loops_edge',
'add_selfloops_edge', 'segregate_self_loops_edge',
... |
9855041 | import matplotlib.pyplot as plt
import warnings
from trackintel.visualization.osm import plot_osm_streets
from trackintel.visualization.util import regular_figure, save_fig
from trackintel.geogr.distances import check_gdf_planar
def plot_positionfixes(positionfixes, out_filename=None, plot_osm=False, axis=None):
... |
9855134 | import json
from tvm.tensor_graph.nn.functional import cross_entropy
from tvm.tensor_graph.testing.datasets import load_mnist_dataset
from tvm.tensor_graph.testing.learners.image_classification_learner import ImageClassificationLearner
from tvm.tensor_graph.testing.models import LeNet
def pprint_dict(d):
return ... |
9855154 | import functools
import inspect
import os
import random
import subprocess
from datetime import datetime
from io import StringIO
import dj_database_url
from dulwich import porcelain
from fabric import task
from fabric.connection import Connection
from invoke import Exit
from invoke.exceptions import UnexpectedExit
ENV... |
9855174 | import unittest
from unittest.mock import patch, MagicMock, call
from botocore.exceptions import ClientError
from examples.examples import (extract_example, extract_to_kwargs_example, extract_mandatory_param_example,
extract_from_json_example, extract_from_event_example, extract_from_cont... |
9855184 | import warnings
from cynergy import container
warnings.simplefilter("ignore", UserWarning)
class Example(object):
pass
class Example2(object):
pass
def setup():
container.initialize()
def test_class_mapping():
container.initialize()
container.register_class(Example, Example2)
instanc... |
9855200 | import os
import sys
sys.path.append(os.path.join(os.getcwd().split('xtraderbacktest')[0],'xtraderbacktest'))
import modules.other.logg
import logging
import modules.other.sys_conf_loader as sys_conf_loader
import time
import datetime
import pandas as pd
all_products_info = sys_conf_loader.get_all_products_info()
cl... |
9855204 | from __future__ import absolute_import
import celery
import os
import os.path
import sys
# Add the project to the python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
# Configure the application only if it seemingly isnt already configured
from django.conf import settings
if not setting... |
9855206 | import subprocess
from openpype.lib import PreLaunchHook
class LaunchFoundryAppsWindows(PreLaunchHook):
"""Foundry applications have specific way how to launch them.
Nuke is executed "like" python process so it is required to pass
`CREATE_NEW_CONSOLE` flag on windows to trigger creation of new console.
... |
9855244 | from os import path
from pathlib import Path
from subprocess import run
from colorama import Fore, Back, Style
class Options():
def get(self):
DIR = path.dirname(path.realpath(__file__))
custom_options_path = path.expanduser("~") + "/.ggo-options.dat"
options_path = f"{DIR}/ggo-options.dat"... |
9855255 | import json
from urllib3_mock import Responses
from alteia.core.errors import QueryError
from alteia.core.resources.resource import Resource
from tests.core.resource_test_base import ResourcesTestBase
responses = Responses()
class TestProjects(ResourcesTestBase):
@responses.activate
def test_create(self):... |
9855270 | from setuptools import setup
from torch.utils.cpp_extension import CppExtension, BuildExtension
setup(name='cpp_extension',
ext_modules=[CppExtension('cpp_extension', ['extension.cpp'])],
cmdclass={'build_ext': BuildExtension})
|
9855273 | from pathlib import Path
from typing import Any, Union
import dask.array as da
import numpy as np
ArrayLike = Union[np.ndarray, da.Array]
DType = Any
NDArray = Any
PathType = Union[str, Path]
RandomStateType = Union[np.random.RandomState, da.random.RandomState, int]
|
9855294 | import logging
import re
import pytest
from ixmp import Scenario
from ixmp.model.base import Model, ModelError
from ixmp.model.dantzig import DantzigModel
from ixmp.model.gams import gams_version
from ixmp.testing import assert_logs, make_dantzig
def test_base_model():
# An incomplete Backend subclass can't be ... |
9855301 | import firenado.tornadoweb
class App1IndexHandler(firenado.tornadoweb.TornadoHandler):
def get(self):
self.write("App1 IndexHandler output")
class App2IndexHandler(firenado.tornadoweb.TornadoHandler):
def get(self):
self.write("App2 IndexHandler output")
|
9855313 | import os
import sys
current_path = os.path.dirname(os.path.realpath(__file__))
root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(root_path)
import time
import json
import random
import numpy as np
import torch
from flownmt.data import NMTDataSet, DataIterator
from flownmt imp... |
9855341 | import random
import torch as ch
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import train_test_split
def gen_data(x, y, n=5, std=0.1, xnoise=False):
x = ch.cat([x] * n)
y = ch.cat([y] * n)
y += std * ch.randn_like(y)
if xnoise:
x += std * ch.randn_like(x)
... |
9855344 | from __future__ import division
from xfel.merging.application.publish.publisher import publisher
from xfel.merging.application.worker import factory as factory_base
class factory(factory_base):
@staticmethod
def from_parameters(params, additional_info=None, mpi_helper=None, mpi_logger=None):
return [publisher(... |
9855347 | import unittest
from ..usb.endpoint import *
class InputEndpointTestCase(unittest.TestCase):
def test_simple(self):
ep = InputEndpoint(xfer=Transfer.CONTROL, max_size=64)
self.assertEqual(ep.xfer, Transfer.CONTROL)
self.assertEqual(ep.max_size, 64)
def test_wrong_xfer(self):
... |
9855356 | import numpy as np
from wellcomeml.ml import BertClassifier
X = ["Hot and cold", "Hot", "Cold"]
Y = np.array([[1, 1], [1, 0], [0, 1]])
bert = BertClassifier(batch_size=8)
bert.fit(X, Y)
print(bert.score(X, Y))
|
9855474 | import requests
# 功能:获取对应网址的网页
class HtmlDownloader(object):
def download(self, url):
if url is None:
return None
headers_pc = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
'A... |
9855500 | import pytest
pytestmark = pytest.mark.asyncio
@pytest.mark.integtest
async def test_hello_world(test_client):
resp = await test_client.get("/")
assert resp.status_code == 200
async def test_world():
assert True
|
9855513 | import FWCore.ParameterSet.Config as cms
from DQMOffline.PFTau.PFJetResDQMAnalyzer_cfi import pfJetResDQMAnalyzer
pfJetResValidation1 = pfJetResDQMAnalyzer.clone(
InputCollection = 'ak4PFJets', # for global Validation
MatchCollection = 'ak4GenJets', # for global Validatio
BenchmarkLabel = 'PFJetResValida... |
9855538 | from handofcats import as_command
import pathlib
@as_command
def run(dirpath: str) -> None:
import re
rx = re.compile("^[0-9]+")
print("CANDIDATES = [")
for p in pathlib.Path(dirpath).glob("*.py"):
m = rx.search(p.name)
if m is None:
continue
print(
f' ... |
9855566 | from crate.theme.rtd.conf.python import *
if "sphinx.ext.intersphinx" not in extensions:
extensions += ["sphinx.ext.intersphinx"]
if "intersphinx_mapping" not in globals():
intersphinx_mapping = {}
intersphinx_mapping.update({
'reference': ('https://crate.io/docs/crate/reference/en/latest/', None),
... |
9855637 | from __future__ import print_function, unicode_literals, absolute_import, division
from six.moves import range, zip, map, reduce, filter
from ..utils import _raise, backend_channels_last
import numpy as np
from ..utils.tf import keras_import
K = keras_import('backend')
def _mean_or_not(mean):
# return (lambda ... |
9855644 | import numpy as np
import cv2
class BackGroundSubtractor:
# When constructing background subtractor, we
# take in two arguments:
# 1) alpha: The background learning factor, its value should
# be between 0 and 1. The higher the value, the more quickly
# your program learns the changes in the background. Therefore... |
9855666 | import sys
import argparse
from progressbar import Bar, ETA, Percentage, ProgressBar
from keras.models import model_from_json
from spacy.en import English
import numpy as np
import scipy.io
from sklearn.externals import joblib
from features import get_questions_matrix_sum, get_images_matrix, get_answers_matrix
fr... |
9855678 | import io
import logging
from typing import Any, Dict, Iterator, Optional
from redis import StrictRedis
from plz.controller.containers import Containers
from plz.controller.images import Images
from plz.controller.instances.docker import DockerInstance
from plz.controller.instances.instance_base \
import Instance... |
9855699 | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
import os
import threading
import asyncio
from sqlalchemy import Column, Integer, Boolean, String, ForeignKey, UniqueConstraint, func
from ..config import Config
de... |
9855711 | import unittest
import pytest
from twitter.common.process.process_handle import ProcessHandleParser
class TestHandleParser(unittest.TestCase):
@classmethod
def setup_class(cls):
cls.attrs = "first last year_of_birth day_of_birth".split()
cls.type_map = {
'first': '%s',
'last': '%s',
'year... |
9855783 | import unittest
from test import string_tests
from collections import UserString
class UserStringTest(string_tests.CommonTest, string_tests.
MixinStrUnicodeUserStringTest, unittest.TestCase):
type2test = UserString
def checkequal(self, result, object, methodname, *args, **kwargs):
result = self.f... |
9855854 | import math
import numpy as np
def add_border(img, border_thickness, border_color):
imheight, imwidth = img.shape[:2]
framed_img = np.ones(
(
imheight + 2 * border_thickness,
imwidth + 2 * border_thickness,
img.shape[2]
),
dtype=np.uint8
) * bor... |
9855858 | spacing_test_text_001 = '''
def function():
return 1
'''
spacing_test_text_002 = '''
def function():
return 1
'''
spacing_test_text_003 = '''
def function():
arg = 1
return 1
'''
spacing_test_text_004 = '''
def function():
arg = 1
return 1
'''
spacing_test_text_005 = '''
def function():
ar... |
9855878 | import unittest
from unittest.mock import patch
import pytest
import fs.path
from moban.deprecated import GitRequire
from moban.exceptions import NoGitCommand
from moban.deprecated.repo import (
git_clone,
get_repo_name,
get_moban_home,
make_sure_git_is_available,
)
@patch("appdirs.user_cache_dir", ... |
9855879 | from icevision.visualize.utils import *
from icevision.visualize.draw_data import *
from icevision.visualize.show_data import *
from icevision.visualize.wandb_img import *
|
9855884 | import dearpygui.dearpygui as dpg
import musicplayer.musicplayer as musicplayer
def setup(first_song):
return musicplayer.Player(first_song)
def mp_interface(sender, data, user_data):
"""mp_interface provides an interface between the GUI callbacks
and the musicplayer object. It enables updating of the G... |
9855907 | import six
from ...cereal import serializable
from ..core import assert_is_proxytype
from .dict_ import BaseDict
@serializable()
class KnownDict(BaseDict):
"""
``KnownDict[<{key: KnownType, ...}>, KeyType, ValueType]``: Proxy mapping from specific keys to specific value
types, with default type for unkno... |
9855951 | import os
import pytest
import pandas as pd
from ..data import (limit_rows, MaxRowsError, sample, pipe, to_values,
to_json, to_csv)
def _create_dataframe(N):
data = pd.DataFrame({"x": range(N), "y": range(N)})
return data
def _create_data_with_values(N):
data = {'values': [{'x': i... |
9855962 | import os
# set these variables according to your experiments #
dirpath = 'data'
experiments_type = [
'default_experiment'
]
runs = 1
# set these variables according to your experiments #
def build_headers(path):
print(path + "/all_measures.txt")
file_summary = open(p... |
9855995 | import aiohttp
import hashlib
import packaging.requirements
import packaging.tags
import packaging.utils
import packaging.version
import pathlib
import sys
from hat import util
Environment = util.namedtuple('Environment',
['pypi_url', 'str'],
['python_versi... |
9856030 | import tak
def parse_tps(tps):
bits = tps.split(' ')
if len(bits) != 3:
raise IllegalTPS("need three components")
board, who, move = bits
if not who in '12':
raise IllegalTPS("Current player must be either 1 or 2")
try:
ply = 2 * (int(move)-1) + int(who)-1
except ValueError:
raise IllegalT... |
9856038 | import ctypes
import Image
from PIL import ImageDraw
from pi3d.constants import *
from pi3d.Texture import Texture
# Text and fonts
# TODO TEXTURES NEED CLEANING UP
class Font(Texture):
def __init__(self, font, color="#ffffff"):
"""
A method of writing in pi3d using 'hand designed' fonts, where the top
... |
9856053 | import shapely.wkb, shapely.geometry
import osgeo.ogr
import sys, os.path
def read_with_ogr (filename, fatal_errors=True):
"""Read features out of a shapefile and yield a tuple of (geometry, attrs)
for each feature."""
source = osgeo.ogr.Open(filename, False)
layer = source.GetLayer(0)
defn = l... |
9856061 | import invoke
import os
from . import jobs, machines
import shutil
import psutil
import tarfile
from subprocess import Popen, check_output
from pathlib import Path
from dataclasses import dataclass, field
from typing import Dict, List, Optional
from shlex import quote
#TODO: Is there a way to just not create zombies i... |
9856067 | import os
import requests
import sys
OFO_URL = 'http://ofo-global.open.ofo.com/api/bike'
OFO_DATA = {
'token': '<PASSWORD>',
'name': 'Washington',
'lat': 38.894432,
'lng': -77.013655,
}
resp = requests.post(
OFO_URL,
data=OFO_DATA,
)
print(len(resp.json()['values']['cars']))
#333 available... |
9856076 | import metadrive.register
from metadrive.envs import MetaDriveEnv, TopDownMetaDrive, TopDownSingleFrameMetaDriveEnv, TopDownMetaDriveEnvV2, \
SafeMetaDriveEnv, MultiAgentRoundaboutEnv, MultiAgentIntersectionEnv, MultiAgentParkingLotEnv, \
MultiAgentTollgateEnv, MultiAgentBottleneckEnv, MultiAgentMetaDrive
|
9856111 | import logging
import os
import sys
from pathlib import Path
from typing import Tuple
import pytest
import torch
from ride.core import RideModule
from ride.finetune import Finetunable
from ride.optimizers import AdamWOneCycleOptimizer
from ride.utils.checkpoints import get_latest_checkpoint
from ride.utils.io import ... |
9856123 | from KratosMultiphysics import *
from KratosMultiphysics.DamApplication import *
def Factory(settings, Model):
if not isinstance(settings, Parameters):
raise Exception("expected input shall be a Parameters object, encapsulating a json string")
return ImposeTemperaturebyDeviceProcess(Model, settings["P... |
9856142 | import datetime
import unittest
from twilio.base import serialize, values
class Iso8601DateTestCase(unittest.TestCase):
def test_unset(self):
value = values.unset
actual = serialize.iso8601_date(value)
self.assertEqual(values.unset, actual)
def test_datetime(self):
value = d... |
9856150 | import itertools
import numpy as np
import gym
def generate_itoa_dict(
bucket_values=[-0.33, 0, 0.33], valid_movement_direction=[1, 1, 1, 1]):
"""
Set cartesian product to generate action combination
spaces for the fetch environments
valid_movement_direction: To set
"""
action_spac... |
9856208 | from asyncio import sleep
from random import choice, getrandbits, randint
from re import sub
from covid import Covid
covid = Covid(source="worldometers")
from datetime import datetime
from ub import CMD_HELP
from telethon import events
import asyncio
import io
from random import randint, uniform
from PIL import Image, ... |
9856215 | import traceback
import logging
import pkg_resources
from sqlalchemy.exc import SQLAlchemyError
from dispatch.plugins.base import plugins, register
logger = logging.getLogger(__name__)
# Plugin endpoints should determine authentication # TODO allow them to specify (kglisson)
def install_plugin_events(api):
"""... |
9856219 | import numpy as np
def duplicate_soft_assignment(fname_template_soft_assignment,
threshold=0.7, units_in=None):
# load soft assignment
tmp = np.load(fname_template_soft_assignment)
probs_all = tmp['probs_templates']
units_all = tmp['units_assignment']
# number of uni... |
9856255 | from collections import namedtuple
User = namedtuple('User', ['username', 'password', 'permissions'])
user_map = {
user.username: user for user in [
User('devin', 'password', ('public',)),
User('jack', 'password', ('public', 'protected',)),
]
}
|
9856272 | import re
from git_analysis.analyze_git_logs import commit_id_line_pattern
from config import conf
from git_analysis.git_stats.git_numstat import GitNumStat
from git_analysis.git_stats.git_numstat import RawGitNumStat
merge_commit_id_line_pattern = re.compile('[0-9a-f]{40}')
def load_numstat_lines(project, is_merge... |
9856300 | from collections import abc
from enum import Enum
from operator import attrgetter
from typing import Dict, Iterable, List, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import torch
from matplotlib.figure import Figure
from ptflops import get_model_complexity_info
from supers im... |
9856323 | from sqlalchemy import Column, Integer, String
from Agent import Base, Session
import jwt, datetime, os
class Offer(Base):
"""description of class"""
__tablename__ = 'agent_offers'
Id = Column(Integer, primary_key = True)
OfferId = Column(String)
OfferName = Column(String)
PublisherId ... |
9856358 | import numpy
np_random = numpy.random.RandomState()
def seed(seed=None):
"""Seed the common numpy.random.RandomState used in spaces
CF
https://github.com/openai/gym/commit/58e6aa95e5af2c738557431f812abb81c505a7cf#commitcomment-17669277
for some details about why we seed the spaces separately from the... |
9856387 | from helpers.time_utils import days
import json
import brownie
import pytest
from brownie import *
from helpers.constants import *
from helpers.registry import registry
from helpers.registry.artifacts import artifacts
from collections import namedtuple
with open("merkle/badger-bouncer.json") as f:
yearnDistributio... |
9856425 | class EggHunter:
def __init__(self, shellcode, egg):
self.__shellcode = shellcode;
self.__egg = egg;
def generate(self):
return self.__egg+self.__egg+self.__shellcode
def hunter_code(self):
return "\\x31\\xc9\\xf7\\xe1\\x66\\x81\\xca\\xff\\x0f\\x42\\x8d\\x5a\\x04\\x31\\xc0\\xb0\\x21\\xcd\\x80\\x... |
9856436 | import sys
import traceback
import event
import types
from eventlet.support import greenlets as greenlet
import six
from eventlet.hubs.hub import BaseHub, READ, WRITE
class event_wrapper(object):
def __init__(self, impl=None, seconds=None):
self.impl = impl
self.seconds = seconds
def __repr... |
9856445 | class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
# build a list of tuples (char, number)
patterns = []
i = 0
while i<len(p):
if p[i]==".":
_id = "dot"
else:
... |
9856455 | import math
#output frequency
a = [161,168,167,92,123]
f = 50 #input freq
print a
for i in a:
m = 1000/f
d = 0
while True:
new_d = math.floor(4*f*m/i)/4
new_m = math.ceil(4*new_d*i/f)/4
if new_m ==m and new_d==d:
break
m = new_m
d = new_d
print "FI... |
9856483 | from django.contrib import admin
from . import models
admin.site.register(models.AllModel)
admin.site.register(models.Float)
admin.site.register(models.Decimal)
admin.site.register(models.BigInteger)
admin.site.register(models.Integer)
admin.site.register(models.SmallInteger)
admin.site.register(models.PositiveInteg... |
9856511 | from operators.operator import Operator
__author__ = ''
class Unary(Operator):
"""
Represent unary operator
"""
__slots__ = ('_operand', '_norm')
def __init__(self, operand, norm):
"""
Initialize an unary operator
:param operand: single operand
:pa... |
9856532 | from artefact_nca.config.base.base_config import (
BaseDatasetConfig,
BaseLoggingConfig,
BaseModelConfig,
BaseTrainerConfig,
DefaultConfig,
make_trainer_defaults,
)
__all__ = [
"make_trainer_defaults",
"BaseModelConfig",
"BaseDatasetConfig",
"BaseLoggingConfig",
"BaseTrainer... |
9856576 | from __future__ import print_function
import numpy as np
from scipy.special import logsumexp
from optimization.loss import calculate_loss_array
def calculate_likelihood(X, model, args, S=5000, MB=500):
# set auxiliary variables for number of training and test sets
N_test = X.size(0)
X = X.view(-1, *args... |
9856584 | import logging
logger = logging.getLogger(__name__)
import os
#import psana.pyalgos.generic.Utils as gu
import os
import sys
from psana.graphqt.CMWControlBase import cp, CMWControlBase
from psana.graphqt.QWFileName import QWFileName
from PyQt5.QtCore import Qt, pyqtSignal, QPoint, QPointF, QRect, QRectF, QSize, QTime... |
9856595 | import random
import numpy
import math
import numpy as np
import matplotlib.pyplot as plt
# Define monitor class:
class monitor:
# check pixel resolution of the computer where
# phsychophysics will be used.
pixel_res_width = None
pixel_res_height = None
# specify these values in cm of the visible
# screen area ... |
9856604 | import torch
import torch.nn as nn
import torch.optim as optim
from deepproblog.utils import count_parameters
from deepproblog.utils.standard_networks import MLP
vocab = dict()
hidden_size = 512
embed_size = 256
with open("data/vocab_746.txt") as f:
for i, word in enumerate(f):
word = word.strip()
... |
9856669 | from __future__ import print_function
#State attributes for the different layers
StateAttributes = {
'bass1': {
'HOME_CHORD_MOVEMENT_DISTANCE': 0,
},
'bass2': {
'DURATION_CHORD_TONES_FOR_CHORD_LENGTH': 0,
'DURATION_NON_CHORD_TONES_FOR... |
9856713 | import signal
import sys
import types
import typing as tp
try:
# noinspection PyProtectedMember
SIG_TYPE = signal._SIG
except AttributeError:
SIG_TYPE = int # we are running on Windows
# noinspection PyUnusedLocal
def dump_frames_on(sig_no: tp.Optional[SIG_TYPE] = None,
stack_frame: t... |
9856733 | from hetdesrun.component.registration import register
from hetdesrun.datatypes import DataType
import pandas as pd
# ***** DO NOT EDIT LINES BELOW *****
# These lines may be overwritten if input/output changes.
@register(
inputs={"left": DataType.Any, "right": DataType.Any},
outputs={"result": DataType.Any},
... |
9856741 | from setuptools import setup, find_packages
setup(
name='budapestcode',
version='0.0.1',
author='<NAME> di <NAME>, <NAME>',
author_email='<EMAIL>, <EMAIL>',
description='Code for analyses related to the Budapest dataset',
packages=find_packages(),
install_requires=[],
)
|
9856797 | import logging
logger = logging.getLogger("message_analyser")
logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
|
9856822 | import unittest
import zserio
from testutils import getZserioApi
class StructTemplateClashTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "templates.zs").struct_template_clash
def testReadWrite(self):
testStruct_uint32 = self.api.TestStruct_uint... |
9856862 | import numpy as np
import nengo
from nengo.exceptions import ValidationError
from nengo.networks.ensemblearray import EnsembleArray
from nengo.spa.module import Module
class State(Module):
"""A module capable of representing a single vector, with optional memory.
This is a minimal SPA module, useful for pas... |
9856874 | from ctypes import *
from mirage.libs.common.sdr.hackrf_definitions import *
from mirage.libs.common.sdr.pipeline import *
from mirage.libs.common.sdr.hardware import *
from mirage.libs import io,utils
import os,threading,numpy
'''
This component implements the supported Software Defined Radio Sources (e.g. RX).
'''
... |
9856877 | import numpy as np
#
# AGENT
# Section Evaluation Agent
#
# INTRODUCTION
# This agent follows the principles of the normal TFT agent, but tries to improve on possible weaknesses.
#
# STRATEGY
# The agent checks sections at the end of the history of increasing size (powers of 2),
# to check if the opponent breached tr... |
9856879 | from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser
from django.db import models
from django.contrib.auth.models import User, PermissionsMixin
from django.urls import reverse
class UserManager(BaseUserManager):
use_in_migrations = True
def create_superuser(self, username: str, passwor... |
9856906 | def count_by_weekday(start_date, end_date):
"""
returns a list of length 7 with the number of occurrences of each day over a given period
:param start_date: first day of the period
:type start_date: datetime.datetime
:param end_date: first day after the period
:type end_date: datetime.datetim... |
9856908 | import re
from setuptools import find_packages, setup
with open('README.rst', encoding='utf8') as f:
long_description = f.read()
with open('brawlstats/__init__.py') as f:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
requirements = []
with open('requirements... |
9856928 | import datetime
import torch
import random
import numpy as np
import torch.nn.functional as F
from torch import optim, nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
import time
from config import *
from resnext import D4Net
# from util.folder_mvtec im... |
9856937 | from datetime import datetime, date
from marqeta.response_models import datetime_object
import json
import re
class ClearingRetryModel(object):
def __init__(self, json_response):
self.json_response = json_response
def __str__(self):
return json.dumps(self.json_response, default=self.json_seri... |
9856940 | import setuptools
with open("README.md", "r") as readme:
long_description = readme.read()
with open("requirements.txt", "r") as reqs:
requirements = reqs.read()
setuptools.setup(
name="redis-sitesearch",
version="1.0",
author="<NAME>",
author_email="<EMAIL>",
description="Redis-powered ... |
9856955 | import FWCore.ParameterSet.Config as cms
vertexFromMuon = cms.EDProducer("VertexFromTrackProducer",
verbose = cms.untracked.bool(False),
trackLabel = cms.InputTag("hltL3MuonCandidates"),
isRecoCandidate = cms.bool(False),
useTriggerFilterElectrons = cms.bool(False),
triggerFilterElectronsSrc = cms.... |
9856960 | from icevision.parsers.parser import *
from icevision.parsers.coco_parser import *
from icevision.parsers.voc_parser import *
from icevision.parsers.via_parser import *
|
9856984 | import sys
sys.path[0] = sys.path[0][:-len("scripts/")] # hacky way to treat it as root directory
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision as tv
from src.neural_blocks import ( SkipConnMLP, FourierEncoder )
from src.utils import ( fat_sigmoid )
from tqdm impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.