id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3375876 | import random
from collections import defaultdict
import numpy as np
from amplification.tasks.core import idk, uniform, Task, sequences
class IterTask(Task):
interaction_length = 3
zero = 1
one = 2
fixed_vocab = 3
def repr_symbol(self, x):
if x == idk: return '?'
if x == self.on... |
3375879 | import pya
import math
import cmath
from pya import *
from SiEPIC.utils import get_technology, get_technology_by_name
from SiEPIC.scripts import path_to_waveguide
MODULE_NUMPY = True
dbu = 0.001
pi = cmath.pi
j = cmath.sqrt(-1)
sign = lambda x: math.copysign(1,x) #define the sign function
alpha = 1 #related to the sp... |
3375895 | import os
import unittest
import torch
from transformers import AutoTokenizer, GlueDataset
from transformers import GlueDataTrainingArguments as DataTrainingArguments
from transformers import default_data_collator
from fluence.datasets import MetaDataset
class Test_Meta(unittest.TestCase):
@classmethod
def ... |
3375949 | from urllib.parse import urljoin
import requests
from cypherpunkpay.common import *
from cypherpunkpay import disable_unverified_certificate_warnings
from cypherpunkpay.bitcoin.ln_invoice import LnInvoice
from cypherpunkpay.net.http_client.clear_http_client import ClearHttpClient
class LightningException(Exception... |
3375962 | from newt.views import JSONRestView
from newt.views import AuthJSONRestView
from common.response import json_response
from django.shortcuts import render
from django.conf import settings
import logging
logger = logging.getLogger("newt." + __name__)
from importlib import import_module
acct_adapter = import_module(sett... |
3375963 | from typing import List, Optional, Tuple
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx import addnodes
from sphinx.application import Sphinx
from sphinx.util.docutils import ReferenceRole, SphinxDirective, SphinxRole
from sphinx_design.shared import SEMANTIC_COLORS, make_choice, t... |
3375968 | import threading
import weakref
from typing import Callable
def _make_id(receiver):
if hasattr(receiver, "__self__") and hasattr(receiver, "__func__"):
return (id(receiver.__self__), id(receiver.__func__)) # noqa
else:
return id(receiver)
class Signal(object):
def __init__(self, name: s... |
3375978 | import asyncio
from .engine.fanhuaji import FanhuajiEngine
from .engine.opencc import OpenCC as OpenCCEngine
class Converter():
def __init__(self, engine, converter):
self.engine = engine
self.converter = converter
def convert(self, content: str) -> str:
"""轉換 epub 內文
Args:... |
3376009 | import math
from functools import reduce
import operator
from typing import Union
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as dist
from torch.nn.utils import parameters_to_vector
from .base import VariationalMixin
__all__ = ["FCGMixin"]
def _prod(iterable):
... |
3376056 | if sm.getChr().getJob() == 2300:
sm.jobAdvance(2310)
sm.addSP(2)
sm.completeQuest(parentID)
sm.dispose()
|
3376084 | from ztag.annotation import *
def _process(self, obj, meta):
vendor = obj["mei_response"]["objects"]["vendor"].lower()
product_code = obj["mei_response"]["objects"]["product_code"].lower()
if "schneider electric" not in vendor \
and "telemecanique" not in vendor:
return
for model in... |
3376105 | import datetime
import math
import mpyq
import binascii
import requests
import struct
from pathlib import Path
from io import BytesIO
from importlib import import_module
from typing import Dict
from zephyrus_sc2_parser.events import (
ObjectEvent,
AbilityEvent,
SelectionEvent,
ControlGroupEvent,
Upg... |
3376126 | from typing import Dict
from botocore.paginate import Paginator
class GetBotAliases(Paginator):
def paginate(self, botName: str, nameContains: str = None, PaginationConfig: Dict = None) -> Dict:
"""
Creates an iterator that will paginate through responses from :py:meth:`LexModelBuildingService.Cli... |
3376130 | from pathlib import Path
from setuptools import Extension, setup # type: ignore
if __name__ == "__main__":
with (Path(__file__).parent / "README.md").open(encoding="UTF-8") as file:
long_description = file.read()
setup(
author="<NAME>",
author_email="<EMAIL>",
description="O... |
3376216 | import vamp
import librosa
import numpy as np
import pretty_midi
import jams
import os
import argparse
def rough_midi(args):
# gets a rough midi trasncription using pYin Note from inpath.wav to outpath.mid
if os.path.exists(args.outpath):
print('file already exist')
return 0
#check if o... |
3376217 | from functools import wraps
from flask import abort, request
def json_required(*required_keys):
def decorator(fn):
if fn.__name__ == 'get':
print('[WARN] JSON with GET method? on "{}()"'.format(fn.__qualname__))
@wraps(fn)
def wrapper(*args, **kwargs):
if not requ... |
3376235 | import torch.nn as nn
from torch.nn import BCEWithLogitsLoss
from transformers.modeling_electra import ElectraModel, ElectraPreTrainedModel
class ElectraForMultiLabelClassification(ElectraPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
... |
3376276 | import sys
sys.path.insert(0, '/gpfs/share/home/1601210097/projects/style_transfer_aaai/stylenas/')
import numpy as np
import os
import cv2
import torch
import torch.nn as nn
from matplotlib import pyplot as plt
from dataset import TransferDataset
from torch.utils.serialization import load_lua
import argparse
from torc... |
3376375 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Author(s): <NAME> (github.com/andrewliew)
__all__ = [
'Element',
'BeamElement',
'SpringElement',
'TrussElement',
'StrutElement',
'TieElement',
'ShellElement',
'MembraneEleme... |
3376400 | from app.utils import parse_image_name, timestamp_to_iso, remove_head_sha256
from dockerclient import Client
def blockchain_verified(repoTag):
# return docker_client().verify_image_hash(repoTag)
return
def blockchain_stat(repoTag):
return {
# 'confirm': 5,
# 'transaction_id': '0x15527ae6... |
3376421 | import enum
class Direction(enum.Enum):
HORIZONTAL_LEFT = "HORIZONTAL_LEFT"
HORIZONTAL_RIGHT = "HORIZONTAL_RIGHT"
VERTICAL_LEFT = "VERTICAL_LEFT"
VERTICAL_RIGHT = "VERTICAL_RIGHT"
DIAGONAL_UP_RIGHT = "DIAGONAL_UP_RIGHT"
DIAGONAL_UP_LEFT = "DIAGONAL_UP_LEFT"
DIAGONAL_DOWN_RIGHT = "DIAGON... |
3376434 | from oauthlib import oauth2
class Client():
client_id = None
class OAuth2_ResourceValidator(oauth2.RequestValidator):
def validate_bearer_token(self, token, scopes_required, request):
if not token:
return False
"""We are using a static dict for the sake of the exercice, but we c... |
3376493 | import os
import importlib_metadata
def get_source_version():
d = dict(MAJOR='6', MINOR='0', MICRO='0', EXTRA='none')
here = os.path.abspath(os.path.dirname(__file__))
try:
f = open(os.path.join(here, '..', '..', 'CMakeLists.txt'))
except FileNotFoundError:
return None
for line in ... |
3376529 | import time
# Move: Tilt Forward
hexy.LF.setFootY(floor/4)
hexy.LM.setFootY(floor/2)
hexy.LB.setFootY(floor)
hexy.RF.setFootY(floor/4)
hexy.RM.setFootY(floor/2)
hexy.RB.setFootY(floor)
|
3376538 | import unittest
try:
from unittest import mock
except ImportError:
import mock
import argparse
from pythontabcmd2.parsers.publish_parser import PublishParser
class PublishParserTest(unittest.TestCase):
@mock.patch('argparse.ArgumentParser.parse_args',
return_value=argparse.Namespace(name=... |
3376560 | from secml.testing import CUnitTest
from secml.figure import CFigure
from secml.array import CArray
from secml.core import constants
class TestCPlot(CUnitTest):
"""Unit test for TestCPlot."""
def test_quiver(self):
"""Test for `CPlot.quiver()` method."""
# gradient values creation
x... |
3376561 | import numpy as np
import scipy.sparse as sp
from ..base_transforms import SparseTransform
from ..transform import Transform
from ..decorators import multiple
__all__ = ['SparseAdjToEdge', 'sparse_adj_to_edge']
@Transform.register()
class SparseAdjToEdge(SparseTransform):
def __call__(self, adj_matr... |
3376611 | import server
# This script is run by the install script when spotbit is being set up.
# It allows for spotbit to function as a systemd service on a user's system.
# Once the database has been opened, spotbit can easily be run in the background.
server.configure_db()
print("database configured in /home/spotbit/.spotbi... |
3376655 | from kubernetes import client
from kubernetes.client.rest import ApiException
from .load_kube_config import kubeConfig
kubeConfig.load_kube_config()
rbac = client.RbacAuthorizationV1Api()
class K8sClusterRole:
def list_cluster_role(logger):
logger.info ("Fetching clusterRoles data...")
try:
... |
3376715 | from ConfigParser import SafeConfigParser
def load_ini_file(file_name, defaults={}):
config = SafeConfigParser()
config.readfp(open(file_name))
results = {}
for section in config.sections():
for key, value in config.items(section):
results[section + '.' + key] = value
results... |
3376723 | import torch
import network
def test_checkerboard_shapes():
net = network.Conv2dCheckerboard(inner_activation='leaky_relu', final_activation=None, hidden_size=16)
for L in [4, 10, 16, 32]:
x = torch.round(torch.rand(1, L, L)) * 2 - 1
out = net(x)
print('L', L, 'out:', out.shape)
# shifting the odd... |
3376724 | from django.shortcuts import get_object_or_404, render
from django.contrib.auth import get_user_model
from manabi.apps.flashcards.models import Deck
def user_profile(request, username):
user = get_object_or_404(get_user_model(), username=username)
decks = Deck.objects.of_user(user)
if request.user.is_an... |
3376733 | import re
import unittest
import ir_datasets
from ir_datasets.datasets.gov import GovWeb02Query, GovDoc
from ir_datasets.formats import TrecQrel, TrecQuery, GenericQuery
from .base import DatasetIntegrationTest
_logger = ir_datasets.log.easy()
class TestGov(DatasetIntegrationTest):
def test_docs(self):
... |
3376734 | from typing import Dict
from django.core.management.base import BaseCommand
from django.db.models import Count
from core.models import (Source, Journey, JourneyStop)
class Command(BaseCommand):
help = 'Fix/Merge Journeys which have multiple external IDs. This is only build for one time use to fix the bug. Becau... |
3376752 | import json
import os
import shutil
import time
import urllib
from collections import namedtuple
import utility as util
import unittest
# Temporary tests (mostly copy-pasted from blob tests) to guarantee simple sync scenarios still work
# TODO Replace with better tests in the future
class Blob_Sync_User_Scenario(unit... |
3376765 | from os.path import dirname, join
import yaml
with open(join(dirname(__file__), 'typemap.yaml')) as f:
TYPE_MAP = yaml.load(f)
# from pprint import pprint
# pprint(TYPE_MAP)
# exit()
def type_name(t):
return TYPE_MAP.get(t, {}).get('_name', t)
def format_arg(a):
if a['type'] not in TYPE_MA... |
3376772 | import os
from dotenv import load_dotenv
import shutil
if not os.path.isfile('.env.example'):
print("The .env file was not found in the following directory: " + os.getcwd())
shutil.copy2('.env.example', '.env')
print("Copied the default .env.example presets to .env")
load_dotenv()
CONSTANTS = {
"HTT... |
3376844 | from scipy.integrate import ode, solve_ivp, odeint
class OdeSolver:
"""
Interface and base class for all used OdeSolvers in gym-electric-motor.
"""
#: Current system time t
_t = 0
#: Current system state y
_y = None
#: Function parameters that are passed to the system equa... |
3376846 | from .trig import *
from .elem import *
from .trig import __all__ as trigA
from .elem import __all__ as elem
from difflib import get_close_matches
__all__ = trigA + elem
def getClosestMatch(name: str) -> None:
return get_close_matches(name, __all__)
|
3376854 | import collections.abc
import inspect
import six
from .base import BaseItem, BaseSection
def parse_config_schema(schema, parent_section=None, root=None):
if root:
parent_section = root
is_valid_config_root_schema = (
inspect.ismodule(schema)
or
(
... |
3376882 | import sys
A = [64, 25, 12, 22, 11]
# Traverse through all array elements
for i in range(len(A)):
# Find the minimum element in remaining unsorted array
min_idx = i #it stores the index of minimum number
for j in range(i+1, len(A)):
if A[min_idx] > A[j]: #if we got a number less th... |
3376930 | import sys, traceback, time, os, os.path
EL = None
# Maximum file size of log file before it is thrown away
FILE_CLEAR_LIMIT = 512 * 1024
# global exception control
class StdErrReplacement:
def write(self, data):
global EL
# try:
# import ExceptionLogger as EL
# ... |
3376933 | from discord.ext.commands import Context
import discord
class BetterContext(Context):
def __init__(self, *args, embed_color: discord.Color = None, **kwargs):
super().__init__(*args, **kwargs)
self.embed_color = embed_color # used in send_embed(...) and reply_embed(...)
self.l = None # th... |
3376984 | import json
import logging
import os
import re
import shutil
import subprocess
import sys
import time
import urllib.request
import yaml # pip install pyyaml
log = logging.getLogger(__name__)
def stdout_lines(res):
return res[1].splitlines()
def joinlines(lines):
return "".join([x + os.linesep for x in line... |
3377009 | import pytest
import asyncio
import uvloop
import aiotask_context as context
@pytest.fixture()
def asyncio_loop():
asyncio.set_event_loop_policy(None)
loop = asyncio.get_event_loop()
yield loop
loop.close()
# restore the virgin state
asyncio.set_event_loop_policy(None)
@pytest.fixture()
de... |
3377059 | import asyncio
import logging
from typing import Dict, Type, IO, Optional
from lft.event import EventSimulator, EventRecorder, EventReplayer, EventMediator
__all__ = ("EventSystem", )
class EventSystem:
def __init__(self, logger: Optional[logging.Logger] = None, use_priority=True):
self.simulator = Event... |
3377116 | import re
from typing import List, Optional
class QGramTransformer:
def __init__(self, qgram_size: Optional[int] = None):
"""
This object performs qgram extraction.
Parameters
----------
qgram_size : Optional[int]
The default qgram size.
"""
self... |
3377132 | from baconian.test.tests.set_up.setup import TestWithAll
from baconian.config.global_config import GlobalConfig
import glob
class TestPlaceholderInput(TestWithAll):
def test_tf_param(self):
a, _ = self.create_ph('test')
for i in range(5):
a.save(save_path=GlobalConfig().DEFAULT_LOG_PAT... |
3377142 | from db.models import Victim
# webhook/url only at this point, email or something in the future
# would require reworking config loading into something fancier
class NotificationSource():
def send_new_victim_notification(url: str, victim: Victim) -> bool:
raise Exception("Function implementation not found"... |
3377146 | import difflib
import argparse
import sys
def main(argv):
parser = argparse.ArgumentParser(description='Compare two text files and report differences')
parser.add_argument('file1', help='file 1')
parser.add_argument('file2', help='file 2')
args = parser.parse_args()
l1 = open(args.file1, 'r').rea... |
3377168 | from collections import defaultdict
from dockerscan import SharedConfig, String
class DockerImageInfoModel(SharedConfig):
image_path = String()
class DockerImageAnalyzeModel(SharedConfig):
image_path = String()
class DockerImageExtractModel(SharedConfig):
image_path = String()
extract_path = Stri... |
3377170 | import sublime
from ruamel.yaml.comments import CommentedMap
ORDERED_KEYS = [
'meta_scope',
'meta_content_scope',
'match',
'scope',
'captures',
'push',
'set',
'pop',
]
def order_output(syntax):
if isinstance(syntax, dict):
ordered_syntax = CommentedMap()
for key in... |
3377237 | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "SBU"
addresses_name = "2021-03-18T18:05:00.006119/Bucks_dedupe.tsv"
stations_name = "2021-03-18T18:05:00.006119/Bucks_dedupe.tsv"
elections = ["2021-05-06"... |
3377239 | from mpi4py import MPI
mpi_comm = MPI.COMM_WORLD
mpi_rank = mpi_comm.Get_rank()
mpi_size = mpi_comm.Get_size()
print('mpi_rank = {}, mpi_size = {}'.format(mpi_rank, mpi_size))
mpi_comm.Barrier()
MPI.Finalize()
|
3377254 | import cv2
import numpy as np
def resize_image(img, new_width, new_height):
"""Resize image to a ``new_width`` and ``new_height``.
Args:
img (np.array): An image.
new_width (int): New width.
new_height (int): New height.
Returns:
np.array: A resized image.
... |
3377263 | from datetime import datetime
from django.http import Http404
from django.utils import timezone
from rating.models import RatingResult
def get_latest_rating_date(rating):
today = timezone.now().date()
rating_results = RatingResult.objects.filter(rating=rating).filter(date__lte=today).order_by("date")
re... |
3377327 | from Rationale_Analysis.models.thresholders.base_thresholder import Thresholder
from Rationale_Analysis.models.thresholders.global_objective import max_limited_min
from allennlp.models.model import Model
@Model.register("global_top_k")
class GlobalTopKThresholder(Thresholder) :
def __init__(self, max_length_ratio:... |
3377339 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
import h5py
from sklearn.metrics import confusion_matrix
import json
number_of_classes = 62
step_notes_class = 1
#########################################################
## GET PATH FUNCTIONS: Functions to return paths
def get_path():
... |
3377392 | from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='simple_pyspin',
version='0.1.1',
description='An easy-to-use Pythonic wrapper for the FLIR PySpin Library. Developed by the Kleckner Lab at UC Merced.',
url='https://github.com/klecknerlab/si... |
3377407 | import json, time, random, datetime
import os, sys, glob, csv, re, argparse
import numpy as np
import networkx as nx
from collections import defaultdict
from scipy.sparse import csr_matrix, lil_matrix, save_npz, load_npz
from collections import defaultdict
import nltk
# nltk.download('punkt')
from nltk.corpus import s... |
3377411 | from datetime import datetime, timedelta
from pagarme.resources import handler_request
import time
import requests
import json
AUTH_TEST = handler_request.authentication_key(None, True)
POSTBACK_URL = 'http://teste.url.com'
BUSINESS_CALENDAR_URL = 'https://pagarme.github.io/business-calendar/data/brazil/{0}.json'
de... |
3377413 | def test_settings(logged_rocket):
settings = logged_rocket.settings().json()
assert settings.get("success")
settings_get = logged_rocket.settings_get(_id="API_Allow_Infinite_Count").json()
assert settings_get.get("success")
assert settings_get.get("value")
settings_update = logged_rocket.setting... |
3377501 | import requests
from bs4 import BeautifulSoup
import pandas as pd
def get_data_dictionary(url: str) -> pd.DataFrame:
"""
Simple function to grab the data dictionary given the World Bank url for the
the data dictionary.
NOT VERIFIED ON ALL TABLES
"""
#Grab the page
page = requests.ge... |
3377526 | import json
import errno
import logging
log = logging.getLogger(__name__)
class CacheHandler:
"""
Handles the caching for TickTick auth tokens to disk
"""
def __init__(self,
path):
"""
Initializes the path of the cache
:param path:
"""
# set p... |
3377547 | try:
import nsml
except:
from tensorfn import nsml_wrapper as nsml
from tensorfn.util import (
read_config,
preset_argparser,
load_config,
load_arg_config,
add_distributed_args,
load_wandb,
ensure_tuple,
get_logger,
create_small_table,
)
from tensorfn.checker import Checker... |
3377558 | import sys
def input():
return sys.stdin.readline()
N = int(input())
arr = list(map(int, input().split()))
ans = 0
idx = 0
while idx < N:
found = False
for j in range(idx+1, N, 2):
pali = True
L = idx
R = j
while L <= R:
if arr[L] != arr[R]:
pal... |
3377568 | import os
import yaml
import argparse
import numpy as np
import torch
from discor.env import make_env
from discor.algorithm import EvalAlgorithm
def test(env, algo, render):
state = env.reset()
episode_return = 0.0
success = 0.0
done = False
while (not done):
action = algo.exploit(state)... |
3377578 | import numpy as np
import tensorflow as tf
import vgg16
import utils
from imagenet1000_clsid_to_human import labels
img1 = utils.load_image("./test_data/tiger.jpeg")
img2 = utils.load_image("./test_data/puzzle.jpeg")
batch1 = img1.reshape((1, 224, 224, 3))
batch2 = img2.reshape((1, 224, 224, 3))
batch = np.concaten... |
3377642 | from mock import MagicMock
import sys
from sonic_platform_base.sonic_xcvr.api.public.sff8472 import Sff8472Api
from sonic_platform_base.sonic_xcvr.codes.public.sff8472 import Sff8472Codes
from sonic_platform_base.sonic_xcvr.fields.public.sff8472 import VoltageField
from sonic_platform_base.sonic_xcvr.mem_maps.public.s... |
3377658 | from unittest import TestCase
from tests.plan.tasks.test_utils import get_
from xmd.lexers import PanelBlockLexer
class TestPanelBlockLexer(TestCase):
def setUp(self):
self.lexer = PanelBlockLexer()
def test_basic(self):
markdown = (
'[ Panel title\n'
'\n'
... |
3377663 | from collections.abc import ABCMeta, abstractmethod
class MixinError(TypeError): pass
class MixinMeta(type):
"""Build classes that easily mix in to other classes."""
def __new__(self, name, bases, namespace):
cls = super(MixinMeta, self).__new__(self, name, bases, namespace)
if "__mixins__" n... |
3377675 | import serial
import random, time, math
port = "\\\\.\\CNCB0"
ser = serial.Serial(port, 38400)
incycle = 0
while True:
t = int(random.randint(60, 80) * (1 + math.sin(incycle)))
x = ser.write(chr(t))
time.sleep(0.02)
incycle += 0.01
if incycle >= 2 * math.pi:
incycle ... |
3377691 | import sys
import time
import copy
import pickle
import numpy as np
import pandas as pd
import normalizedDistance
from modelConversion import *
from pysmt.shortcuts import *
from pysmt.typing import *
from pprint import pprint
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestCl... |
3377707 | P8 = {}
P9 = {}
def _set(name, modes=None, mode=None, offset=None, enable_pullupdown=False,\
pullup=False, input=False, slew=False):
pin = {
"name": name,
"modes": [None] * 8,
"mode": mode,
"offset": offset,
"enable_pullupdown": enable_pullupdown,
"pullup": pullup,
"input": input,
"slew": slew
}
... |
3377729 | import argparse
import glob
import os.path
from hic import HiC
import pandas
import numpy as np
import sys
from neighborhoods import read_bed, process_gene_bed
def parseargs():
parser = argparse.ArgumentParser(description='Convert HiC matrices to bedgraphs for a set of genes')
parser.add_argument('--outdir', r... |
3377734 | def resistancebands(bc1, bc2, bc3, bc4): #define 4 band resistor colors
bandcolors = {'black': '0',
'brown': '1',
'red': '2',
'orange': '3',
'yellow': '4',
'green' : '5',
'blue' : '6',
... |
3377741 | import pygame
import constants
import os, sys
import utils
# from environment import Walkables, Obstacles
from environment import Environment
# ------------------------------------------------------
# class Player
# ------------------------------------------------------
class Player(pygame.sprite... |
3377788 | from .models import *
from .augmentations import *
from .dataset import *
from .loss import *
from .visualization import *
from .optim import *
from .scheduler import *
from .metric import *
from .tsa import *
from .predict import *
|
3377789 | from glob import glob
from os.path import basename
from os.path import isdir
from os.path import join
from typing import List
from typing import Tuple
import cv2
import numpy as np
import skimage.io as io
import torch
from skimage.transform import resize
from torch.utils.data.dataloader import default_collate
from tor... |
3377805 | import random
import torch.utils.data
import copy
from collections import defaultdict
def filter_kcore(ratings, user_k=5, item_k=5):
while True:
item_count, user_count = defaultdict(int), defaultdict(int)
for user_id, item_id, rating, timestamp in ratings:
item_count[item_id] += 1
... |
3377824 | from stacksort._meta import injector
from stacksort._meta.stackoverflow import SelectionStrategy
import sys
#
# I'm being pretty sneaky here by naming the loader 'config'
#
# This allows me to keep the python library flow for typical usage (lol, as if this would be used)
# >>> from stacksort import quicksort
#
# Howev... |
3377834 | from __future__ import print_function
import io
import gzip
from datetime import datetime, timedelta
from reloadium.vendored.sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps
from reloadium.vendored.sentry_sdk.worker import BackgroundWorker
from reloadium.vendored.sentry_sdk.envelope impor... |
3377867 | import pandas as pd
import re
import encode_production_company as epc
import os.path as p
from addPrefixToColumn import addPrefixToColumn
pathVariable = "../../data/interim/actors_encoded.csv"
def encodeActors(df, filter, threshold):
if (p.isfile(pathVariable)):
actors_encoded = pd.read_csv(pathVariable, i... |
3377889 | import configparser
import os
import arrow
import pytz
from arrow.parser import ParserError
from src.utils import safe_input as input
weekday_dict = {
"monday": 0,
"tuesday": 1,
"wednesday": 2,
"thursday": 3,
"friday": 4,
"saturday": 5,
"sunday": 6,
}
zones = pytz.all_timezones # list o... |
3377905 | from flask import Flask,jsonify,send_from_directory,request
from flask.ext import restful
from flask.ext.restless import APIManager
from flask.ext.restful.utils import cors
from backend.user import User
from backend.simulation import Simulation,Argument,Diagnostic
from backend.kernel import Kernel,Note
from json_encod... |
3377916 | def test_import_zivid_globals_changes():
before = sorted(globals().keys())
import zivid # pylint: disable=unused-import
after = sorted(globals().keys())
assert before == after
def test_import_zivid_globals_locals():
expected_changes = sorted(["before", "zivid"])
before = sorted(locals().keys... |
3377917 | from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import f1_score, precision_score, recall_score, \
accuracy_score, confusion_matrix, c... |
3377921 | from functools import reduce
from test.pycardano.util import chain_context
from typing import List
import pytest
from pycardano.coinselection import LargestFirstSelector, RandomImproveMultiAsset
from pycardano.exception import (
InputUTxODepletedException,
InsufficientUTxOBalanceException,
MaxInputCountEx... |
3377955 | from rxbp.acknowledgement.continueack import ContinueAck, continue_ack
from rxbp.init.initobserverinfo import init_observer_info
from rxbp.observablesubjects.cacheservefirstobservablesubject import CacheServeFirstObservableSubject
from rxbp.observerinfo import ObserverInfo
from rxbp.testing.testcasebase import TestCase... |
3377962 | from rest_framework import serializers
from modelchimp.models.comment import Comment
from modelchimp.serializers.profile import ProfileSerializer
class CommentSerializer(serializers.ModelSerializer):
user_detail = ProfileSerializer(source='user.profile', read_only=True)
class Meta:
model = Comment
... |
3377976 | import sys
import os
import subprocess
import time
def start_query():
for i in range(10):
if os.path.isfile("query"+str(i+1)+".txt"):
print "Query file exist!"
num = 0
while num < 1000000:
for i in range(10):
return_code = subprocess.call("./klee-stats klee-out-"+s... |
3378032 | class ValidationError(Exception):
message = "Bad request"
args = {}
def __init__(self):
pass
def get_dict(self):
return {
'name': self.__class__.__name__,
'message' : self.message,
'args' : self.args
}
class MissingField(... |
3378049 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from models.actor import MLPBase, PointnetMLP
class VanillaCritic(nn.Module):
"""a vanilla actor module that outputs a node's action given only its observation (no message between nodes)"""
def __init__(self, state_dim, act... |
3378065 | import numpy as np
from common.data import jsdict
from common.time import Timer
import os.path
from multiprocessing import Pool
import h5py
import sys
import re
import glob
def read_hdf5_segment(file, key, start=None, end=None):
dset = file[key]
meta = {}
for key, value in dset.attrs.iteritems():
... |
3378093 | from tabulator.parser import Parser
from tabulator.helpers import reset_stream
class TXTParser(Parser):
"""Parser to parse TXT data format.
"""
# Public
options = []
def __init__(self, loader, **options):
super(TXTParser, self).__init__(loader, **options)
# Set attributes
... |
3378100 | if __name__ == "__main__":
import test
import json
cves = json.loads(open("VIA4CVE-feed.json").read())
test.testAll(cves, test.tests, test._verbose)
|
3378117 | from .fileio import DataSaver
from .fileio import DataReader
from .batch_task import BatchTasks
from .citation import citation
from .cuboid_mesh import CuboidMesh
#from .neb_cartesian import NEB_Sundials
from .helper import init_scalar, init_vector
from .plot import plot, plot_micro, plot_atom_cub, plot_atom_hex
|
3378153 | import torch.nn as nn
import torch
from torch.distributions import MultivariateNormal
from math import log
class BaseNet(nn.Module):
def __init__(self,
input_dim,
output_dim,
network_config,
activation_func=nn.Tanh):
super(BaseNet, self).... |
3378166 | from .helper import PillowTestCase, hopper
from PIL import Image, SgiImagePlugin
class TestFileSgi(PillowTestCase):
def test_rgb(self):
# Created with ImageMagick then renamed:
# convert hopper.ppm -compress None sgi:hopper.rgb
test_file = "Tests/images/hopper.rgb"
im = Image.op... |
3378184 | from bitshares_pricefeed.pricefeed import Feed
config = 'examples/hertz.yaml'
def test_hertz_computation(conf, checkers):
feed = Feed(conf)
feed.fetch()
feed.derive({'HERTZ'})
prices = feed.get_prices()
checkers.check_price(prices, 'HERTZ', 'BTS', 0.1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.