id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
462271 | import os
import sys
import threading
import subprocess
def _try_to_kill(process):
try:
process.kill()
except Exception:
pass
def touch(path):
if not os.path.exists(path):
with open(path, 'w') as _:
pass
class Process(object):
def __init__(self, args):
s... |
462275 | from twitch.helix import Video
from tcd.settings import Settings
class Format:
def __init__(self, video: Video, format_name: str):
self.video: Video = video
self.format_name: str = format_name
self.format_dictionary: dict = Settings().config['formats'][format_name]
|
462319 | import input_parser
import pandas as pd
import app_classifier
import config
import timing
class ClassificationResult:
def __init__(self, accuracy, file_name):
self.accuracy = accuracy
self.file_name = file_name
def __str__(self):
return "Total accuracy: " + str(self.accuracy) + " for "... |
462325 | def message_says_hello(msg):
"""Make sure that the response was friendly"""
assert msg.payload.get("message") == "hello world"
|
462346 | from typing import Mapping, Sequence, Union
import torch
from pyro.distributions import TorchDistribution
from torch.distributions import register_kl
from torch.distributions.constraints import Constraint
from .multivariate import MultivariateDistribution
def _iterate_parts(value, ndims: Sequence[int]):
for ndi... |
462368 | from fabric.api import hide, run, env
import time
import json
def run_cmd(cmd):
with hide('output', 'running', 'warnings'):
return run(cmd, timeout=1200)
def check(**kwargs):
''' Login over SSH and execute shell command '''
jdata = kwargs['jdata']
logger = kwargs['logger']
env.gateway = j... |
462374 | import pysinsy
from nnmnkwii.io import hts
# TODO: consider replacing pysinsy to pure python implementation
_global_sinsy = None
def _lazy_init(dic_dir=None):
if dic_dir is None:
dic_dir = pysinsy.get_default_dic_dir()
global _global_sinsy
if _global_sinsy is None:
_global_sinsy = pysins... |
462390 | def main():
for x in range(4):
if x == 5:
break
else:
print("Well of course that didn't happen")
for x in range(7):
if x == 5:
break
else:
print("H-hey wait!")
i = 0
while i < 3:
print("Works with while too")
for x in rang... |
462396 | import unittest
from chainer import function_node
from chainer import testing
def dummy():
pass
class TestNoNumpyFunction(unittest.TestCase):
def test_no_numpy_function(self):
with self.assertRaises(ValueError):
testing.unary_math_function_unittest(dummy) # no numpy.dummy
class Dumm... |
462401 | import os
from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, \
core, multiprocess, start_http_server
from prometheus_client.exposition import generate_latest
from sanic.response import raw
from . import endpoint, metrics
from .exceptions import SanicPrometheusError
class MonitorSetup:
def... |
462409 | from typing import List, Tuple
from drkns.configunit.ConfigUnit import ConfigUnit
from drkns.generation.GenerationTemplate import GenerationTemplate
from drkns.generation.generation.get_group_block import get_group_block
from drkns.generation.pattern_util \
import format_list_in_template
from drkns.generation._tag... |
462414 | import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
import pdb
import requests
import time
from random import randint
import csv
class amazon_review_scraper:
# Ignore SSL certificate errors
ssl._create_default_https_context = ssl._create_unverified_context
csv_data = []
cs... |
462422 | from pylab import *
from scipy import *
from scipy import optimize
import argparse
import sys
import os
# Generate data points with noise
# Read in csv file and set length and width
"""
This program reads in a set of points from a csv file and interprets these points.
These points correspond to a torpedo, emperor, or... |
462509 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.daylighting import DaylightingDelightControls
log = logging.getLogger(__name__)
class TestDaylightingDelightControls(unittest.TestCase):
def setUp(self):
self.fd, s... |
462510 | class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Using Boyer-Moore Majority Vote Algorithm
# Since we only use equality comparison, and cnt_a and cnt_b are initialized to 0
# thus initializing a and b t... |
462524 | from __future__ import print_function, division
import unittest
class Vector:
def __init__(s, *args, **_kwargs):
kwargs = {
'base_class': (int, float),
}
kwargs.update(_kwargs)
s.base = kwargs['base_class']
if len(args) == 1 and hasattr(args[0], '__iter__'):
s.v = tuple(args[0])
... |
462535 | import numpy as np
import warnings
import os
import h5py
from tqdm import tqdm
import pickle
from torch.utils.data import Dataset
warnings.filterwarnings('ignore')
def pc_normalize(pc):
centroid = np.mean(pc, axis=0)
pc = pc - centroid
m = np.max(np.sqrt(np.sum(pc**2, axis=1)))
pc = pc / m
return... |
462538 | def getResNet50Init():
string = '\
layer {\n\
bottom: "image"\n\
top: "conv1"\n\
name: "conv1"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 7\n\
pad: 3\n\
stride: 2\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "conv1"\n\
top: ... |
462540 | import time
import torch
import torch.utils.data
from kge.job import Job
from kge.job.train import TrainingJob, _generate_worker_init_fn
class TrainingJob1vsAll(TrainingJob):
"""Samples SPO pairs and queries sp_ and _po, treating all other entities as negative."""
def __init__(
self, config, datase... |
462542 | favorite_places = {
'znn': ['chengdu', 'shanghai', 'hangzhou'],
'yl': ['chengdu', 'huang montains'],
'other': ['xian', 'xinjiang', 'nanji']
}
for name, places in favorite_places.items():
print("\n" + name.title() + " likes the following places:")
for place in places:
print("- " + place.... |
462594 | import os
import types
import pandas as pd
import pytest
from skmine.datasets import fimi
from skmine.datasets import get_data_home
def mock_urlopen(url):
for i in range(2):
transaction = " ".join("{}".format(i * j) for j in range(2)) + " \n"
yield bytes(transaction, encoding="utf-8")
def mock... |
462613 | from typing import Optional
from typing import Text, Dict, Any
from tfx import types
from tfx.dsl.components.base import base_component
from tfx.dsl.components.base import executor_spec
from tfx.types.component_spec import ChannelParameter
from tfx.types.component_spec import ComponentSpec
from tfx.types.component_spe... |
462620 | import numpy as np
import tensorflow as tf
from collections import Counter
from textdect.convertmodel import ConvertedModel
from misc.freezemodel import FreezedModel
from mesgclsf.datapreptools import resize_to_desired
from mesgclsf.s2train import FEATURE_HEIGHT, FEATURE_WIDTH
def classify(classifier, session, img_a... |
462635 | import sys
import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QDialog, QPushButton, QWidget, QHBoxLayout, QApplication, QLabel, QVBoxLayout, QGridLayout
from PyQt5.uic import loadUi
import cv2
imageT = None
import windowSize
class mywin(QtWidgets.QDialo... |
462667 | from citrus import *
import img
import sf2d
ST_LOAD = 0
ST_DISP = 1
ST_END = 2
class App:
state = ST_LOAD
bg = None
load_pat = ['-', '\\', '|', '/']
load_pat_idx = 0
def __init__(self):
sf2d.init()
console.init(gfx.SCREEN_BOTTOM)
self.bg_loader = img.load_png(open('romf... |
462692 | import os
from pathlib import Path
from unittest.mock import patch
import pytest
from streamlink_cli.utils.path import replace_chars, replace_path
from tests import posix_only, windows_only
@pytest.mark.parametrize("char", [i for i in range(32)])
def test_replace_chars_unprintable(char: int):
assert replace_cha... |
462693 | import theano, cPickle
import theano.tensor as T
import numpy as np
from fftconv import cufft, cuifft
def initialize_matrix(n_in, n_out, name, rng, init='rand'):
if (init=='rand') or (init=='randSmall'):
bin = np.sqrt(6. / (n_in + n_out))
values = np.asarray(rng.uniform(low=-bin,
... |
462702 | from numpy.random import random, normal
figure(4)
clf()
axis([-10, 10, -10, 10])
# Define properties of the "bouncing balls"
n = 10
pos = (20 * random(n*2) - 10).reshape(n, 2)
vel = (0.3 * normal(size=n*2)).reshape(n, 2)
sizes = normal(200, 100, size=n)
# Colors where each row is (Red, Green, Blue, Alpha). Each can ... |
462808 | from rest_framework.pagination import PageNumberPagination
class PageSizeNumberPagination(PageNumberPagination):
page_size_query_param = 'page_size' |
462862 | import pytest
from stake.watchlist import AddToWatchlistRequest, RemoveFromWatchlistRequest
# flake8: noqa
@pytest.mark.asyncio
async def test_add_to_watchlist(tracing_client):
added = await tracing_client.watchlist.add(AddToWatchlistRequest(symbol="SPOT"))
assert added.watching
@pytest.mark.asyncio
async... |
462868 | E = EuclideanSpace(3)
x, y, z = E.default_chart()[:]
v = E.vector_field(-y, x, sin(x*y*z), name='v')
sphinx_plot(v.plot(max_range=1.5, scale=0.5)) |
462891 | import torch
import torch.nn as nn
from deepblast.ops import operators
import numba
import numpy as np
use_numba = True
@numba.njit
def _soft_max_numba(X):
M = X[0]
for i in range(1, 3):
M = X[i] if X[i] > M else M
A = np.empty_like(X)
S = 0.0
for i in range(3):
A[i] = np.exp(X[i... |
462901 | from unittest import TestCase
from bot.duel_links_runtime import DuelLinkRunTimeOptions
from bot.utils.data import read_json_file, write_data_file
class TestDuelLinkRunTimeOptions(TestCase):
def setUp(self):
file = r'D:\Sync\OneDrive\Yu-gi-oh_bot\run_at_test.json'
self.runtimeoptions = DuelLinkRu... |
462904 | import re
from functools import partial
import markdown
from veripress.helpers import to_list
class Parser(object):
"""Base parser class."""
# this should be overridden in subclasses,
# and should be a compiled regular expression
_read_more_exp = None
def __init__(self):
if self._read_... |
462915 | import logging
import os
from django import forms
from django.utils.translation import ugettext_lazy as _
from mayan.apps.views.forms import DetailForm
from ..models.document_models import Document
from ..settings import setting_language
from ..utils import get_language, get_language_choices
__all__ = ('DocumentFor... |
462918 | import os, glob, platform
#find out if we're running on mac or linux and set the dynamic library extension
dylib_ext = ""
if platform.system().lower() == "darwin":
dylib_ext = ".dylib"
else:
dylib_ext = ".so"
print("Running on " + platform.system())
#make sure the release folder exists, and cl... |
462931 | import datetime
import ipaddress
from tests.common import constants
class TrafficPorts(object):
""" Generate a list of ports needed for the PFC Watchdog test"""
def __init__(self, mg_facts, neighbors, vlan_nw):
"""
Args:
mg_facts (dict): parsed minigraph info
neighbors... |
462972 | class BaseData(object):
def __init__(self, unit):
self.unit = unit
def change_units(self, new_units):
self.unit = new_units |
463005 | import logging
from collections import deque
from teether.cfg.bb import BB
from teether.cfg.instruction import Instruction
from teether.cfg.opcodes import opcodes
class ArgumentTooShort(Exception):
pass
def disass(code, i=0):
assert isinstance(code, bytes)
while i < len(code):
loc = i
o... |
463026 | from enum import Enum
from typing import Any, Dict, Optional
from eth2._utils.bls import bls
from eth2._utils.bls.backends import MilagroBackend
from eth2.beacon.tools.fixtures.test_part import TestPart
from eth2.configs import Eth2Config
from .test_handler import Input, Output, TestHandler
class BLSSetting(Enum):
... |
463048 | import numpy as np
import numpy.testing as npt
from stumpy import scrump, stump, config
from stumpy.scrump import prescrump
import pytest
import naive
test_data = [
(
np.array([9, 8100, -60, 7], dtype=np.float64),
np.array([584, -11, 23, 79, 1001, 0, -19], dtype=np.float64),
),
(
n... |
463071 | from NIENV import *
# GENERAL
# self.input(index) <- access to input data
# self.outputs[index].set_val(val) <- set output data port value
# self.main_widget <- access to main widget
# self.exec_output(index) <- executes an execution output
# EDITING
# self.create_... |
463081 | import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.font_manager
matplotlib.font_manager._rebuild()
import matplotlib.pyplot as plt
import copy
import pickle
import pdb
from matplotlib import rc
# rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
filehan... |
463094 | import numpy as np
import cv2
def blend_map(img, map, factor, colormap=cv2.COLORMAP_JET):
"""
Function to blend an image and a probability map.
:param img: The image
:param map: The map
:param factor: factor * img + (1-factor) * map
:param colormap: a cv2 colormap.
:return: The blended im... |
463107 | import cloudsight
def call_vision_api(image_filename, api_keys):
api_key = api_keys['cloudsight']['api_key']
api_secret = api_keys['cloudsight']['api_secret']
# Via example found here:
# https://github.com/cloudsight/cloudsight-python
auth = cloudsight.SimpleAuth(api_key)
api = cloudsight.API... |
463110 | from pythonwarrior.abilities.base import AbilityBase
class DirectionOfStairs(AbilityBase):
def description(self):
return ("Returns the direction ('left', 'right', 'forward',"
"'backward') the stairs are from your location")
def perform(self):
return self._unit.position.relativ... |
463129 | import logging
from .mem import Ram, Registers, Uniques
from .arch import instantiate_architecture
logger = logging.getLogger(__name__)
class State(object):
def __init__(self, api_base):
self.api_base = api_base
self.arch = instantiate_architecture(self.api_base)
if self.arch is None:
... |
463161 | from office365.runtime.client_path import ClientPath
from office365.runtime.odata.odata_path_builder import ODataPathBuilder
class ServiceOperationPath(ClientPath):
""" Resource path to address Service Operations which
represents simple functions exposed by an OData service"""
def __init__(self, name, pa... |
463184 | width = int(input())
while width % 2 == 0:
text = input()
totalDots = chr(46) * (width - len(text))
halfDots = int(width / 2)
halfLen = len(text) / 2
firstDots = chr(46) * (halfDots - int(halfLen))
secondDots = chr(46) * (halfDots - int(halfLen))
if text == "END":
break
... |
463217 | from .modules import Transformer, TransformerEncoderLayer, TransformerDecoderLayer, ScaledDotProductAttention, \
MultiHeadAttention, PositionalEmbedding, PositionWise
|
463228 | import string
def key_generation(key):
# initializing all and generating key_matrix
main=string.ascii_lowercase.replace('j','.')
# convert all alphabets to lower
key=key.lower()
key_matrix=['' for i in range(5)]
# if we have spaces in key, those are ignored automatically
i=0;... |
463233 | import unittest
from py.game_logic.Research import Research
class Research_test(unittest.TestCase):
def test_add_and_check_researched_nodes(self):
res = Research()
node= 'advanced spam canning'
self.assertFalse(res.isUnlocked(node))
res.unlock(node)
self.assertTrue... |
463237 | from interpretador.interpretador import Interpretador
class ConfigurarInterpretador:
def __init__(self):
pass
def gerar_regex_compilado_interpretador(self, dicLetras:dict, dic_comandos:dict, idioma:str) -> tuple:
"""Compila todos os regex que o interpretador poderá usar
Args:
... |
463243 | from time import gmtime, strftime
import os
import reporter
def getTimeStamp():
return strftime("%Y/%m/%d | %H:%M:%S", gmtime())
def info(message, sendReport=False):
logAndWrite(getTimeStamp(), " | INFO | ", message)
if sendReport:
reporter.report('info', message)
def warn(message, sendReport=Fa... |
463279 | import errno
import json
import logging
import os
__all__ = ['get_config', 'get_default_config_filename', 'get_application_config', 'expand_env_vars']
logger = logging.getLogger(__name__)
def get_default_config_filename():
config_filename = os.path.join(os.path.abspath(os.getcwd()), "application.cfg")
retu... |
463308 | function diginto(thestruct, level)
if nargin < 2
level = 0;
end
fn = fieldnames(thestruct);
for n = 1:length(fn)
tabs = '';
for m = 1:level
tabs = [tabs ' '];
end
disp([tabs fn{n}])
fn2 = getfield(thestruct,fn{n});
if isstruct(fn2)
diginto(fn2, level+1);
end
end
end
|
463341 | import os,sys
import gzip
review_file = sys.argv[1]
output_path = sys.argv[2]
min_count = int(sys.argv[3])
output_path += 'min_count' + str(min_count) + '/'
if not os.path.exists(output_path):
os.makedirs(output_path)
#read all words, users, products
word_count_map = {}
user_set = set()
product_set = set()
with gzip... |
463345 | import tensorwatch as tw
import random, time
def static_hist():
w = tw.Watcher()
s = w.create_stream()
v = tw.Visualizer(s, vis_type='histogram', bins=6)
v.show()
for _ in range(100):
s.write(random.random()*10)
tw.plt_loop()
def dynamic_hist():
w = tw.Watcher()
s = w.creat... |
463351 | import torch
import torch.nn as nn
from models.word_model import CaptionModel
class Seq2SeqAttention(nn.Module):
def __init__(self, hs_enc, hs_dec, attn_size):
"""
Args:
hs_enc: encoder hidden size
hs_dec: decoder hidden size
attn_size: attention vector size
... |
463361 | from sdk import *
def delegate(node, account, amount):
newDelegation = NetWorkDelegate(account, amount, node + "/keystore/")
newDelegation.send_network_Delegate()
def check_rewards(result, balance, pending):
if balance != '':
balance = str(balance) + '0' * 18
if int(result['balance']) < ... |
463396 | import argparse
import logging
import sys
import Queue
from migrator.Migrator import Migrator
from migrator.ArtifactoryDockerAccess import ArtifactoryDockerAccess
from migrator.DockerRegistryAccess import DockerRegistryAccess
from migrator.QuayAccess import QuayAccess
from migrator.DTRAccess import DTRAccess
import os
... |
463410 | from torch.nn import Module
from getalp.wsd.torch_fix import *
import math
class PositionalEncoding(Module):
def __init__(self, input_embeddings_size, max_len=5000):
super().__init__()
pe = torch_zeros(max_len, input_embeddings_size) # max_len x input_embeddings_size
position = torch_ara... |
463445 | import sys
sys.path.append("../")
from settings import (NES_PALETTE_HEX, animation_settings)
from core import sprite
RiderRightStandard01 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
},
matrix = [
"x8w4x8",
"... |
463497 | from django.contrib import admin
from .models import Location, State, RegionalLead
class LocationAdmin(admin.ModelAdmin):
list_per_page = 10
list_display = (
'name',
'state')
search_fields = ('name',)
list_filter = (
'name',
'state')
class StateAdmin(admin.ModelAdmin... |
463500 | from os import getcwd
from sys import path
from cv2 import resize
from foo.pictureR import pictureFind
class Booty:
def __init__(self, cwd):
self.cwd = cwd
self.bootyPicPath = cwd + '/res/booty/pics'
self.bootyList = {'RMA70-12':pictureFind.picRead(self.bootyPicPath + '/RMA70-12.png'),
... |
463553 | from smp_manifold_learning.scripts.proj_ecmnn import eval_projection
import numpy as np
import argparse
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument("-d", "--dataset_option", default=1, type=int)
if __name__ == '__main__':
n_data_samples = 100
tolerance = 1e-1 # threshold for p... |
463558 | from __future__ import print_function
import numpy as np
import os
class NpzDataset(object):
'''
Write out NPZ datasets one file at a time, with information in filenames
for easy access and data aggregation.
This is a fairly slow way to do things but prevents a lot of the problems
with massive a... |
463584 | import importlib
from django.conf import settings
from auction.utils.loader import load_class
LOT_MODEL = getattr(settings, 'AUCTION_LOT_MODEL',
'auction.models.defaults.Lot')
Lot = load_class(LOT_MODEL, 'AUCTION_LOT_MODEL') |
463600 | import unittest
from six import StringIO
import sys
import re
import pandas as pd
from auditai import misc
def pass_fail_count(output):
pass_cnt = len(re.findall('pass', output))
fail_cnt = len(re.findall('fail', output))
return pass_cnt, fail_cnt
class TestMisc(unittest.TestCase):
def setUp(self):... |
463729 | import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
requirements = ["click", "fabric", "numpy", "pyYAML", "click-config-file"]
setup(
name="shepherd_herd",
version="0.2.6... |
463768 | from lie_logger.application import LoggerComponent
from mdstudio.runner import main
if __name__ == '__main__':
main(LoggerComponent)
|
463820 | from __future__ import print_function, unicode_literals
core_store_students_programs = False
core_store_students_programs_path = 'files_stored'
core_experiment_poll_time = 350 # seconds
# Ports
core_facade_port = 18341
core_facade_server_route = 'testing-route'
core_server_url = 'http://127.0.0.1:%s/... |
463830 | from typing import List
from calyx.py_ast import *
from dahlia_utils import *
from calyx.gen_exp import generate_exp_taylor_series_approximation
### Dahlia Implementations for Relay Call Nodes ###
# Context: While implementing a Relay frontend for
# Calyx, we decided it would be easier to implement
# the Relay calls... |
463835 | import autograd.numpy as np
import tensorflow as tf
import theano.tensor as T
import torch
from examples._tools import ExampleRunner
from numpy import linalg as la, random as rnd
import pymanopt
from pymanopt.manifolds import FixedRankEmbedded
from pymanopt.solvers import ConjugateGradient
SUPPORTED_BACKENDS = (
... |
463851 | import tensorflow as tf
from .op import linear, batch_norm, flatten
from .output import OutputType, Normalization
import numpy as np
from enum import Enum
import os
class Network(object):
def __init__(self, scope_name):
self.scope_name = scope_name
def build(self, input):
raise NotImplemented... |
463854 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.hvac_templates import HvactemplateSystemUnitaryHeatPumpAirToAir
log = logging.getLogger(__name__)
class TestHvactemplateSystemUnitaryHeatPumpAirToAir(unittest.TestCase):
de... |
463859 | from torch.nn import Module
from torch.autograd import Function
import torch.nn.functional as F
from torch.autograd import Variable
import math
import shapely
from shapely.geometry import Polygon, MultiPoint
import pixel_weights_cpu
import pixel_weights_cuda
import torch
import numpy as np
import cv2
class ... |
463860 | import os
import sublime
from PHPUnitKit.plugin import _get_php_executable
from PHPUnitKit.tests import unittest
class TestGetPHPExecutable(unittest.TestCase):
def setUp(self):
super().setUp()
self.versions_path = unittest.fixtures_path(os.path.join('get_php_executable', 'versions'))
def t... |
463952 | import unittest
import click
from biolinkml.generators import graphqlgen
from tests.test_scripts.environment import env
from tests.utils.clicktestcase import ClickTestCase
class GenGraphqlTestCase(ClickTestCase):
testdir = "gengraphql"
click_ep = graphqlgen.cli
prog_name = "gen-graphql"
env = env
... |
463963 | from houdini.data import AbstractDataCollection, db
class BuddyList(db.Model):
__tablename__ = 'buddy_list'
penguin_id = db.Column(db.ForeignKey('penguin.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True,
nullable=False)
buddy_id = db.Column(db.ForeignKey('penguin.... |
464003 | class JenkinsMetadata(object):
""" This class is the model of the Jenkins data relating to the build that ran the tests or collected the metrics.
This class is how the model is represented in the HTTP API """
def __init__(self, jenkins_job_id):
self.jenkins_job_id = jenkins_job_id
|
464009 | from django.test import TestCase
class SampleTest(TestCase):
def test_1_equals_1(self):
self.assertEquals(1, 1)
|
464013 | from opyoid.provider import Provider
from opyoid.utils import InjectedT
class FromInstanceProvider(Provider[InjectedT]):
def __init__(self, instance: InjectedT) -> None:
self._instance = instance
def get(self) -> InjectedT:
return self._instance
|
464040 | from threading import Thread
def my_function():
print("printing from thread")
if __name__ == "__main__":
threads = [Thread(target=my_function) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
|
464128 | import os
import mindmeld
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackContext,
)
import logging
import requests
from dotenv import load_dotenv
url = "http://localhost:7150/parse"
load_dotenv()
updater = Updater(token=os.getenv('BOT... |
464154 | import os
import json
import datetime
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.utils.safestring import mark_safe
from django.utils import timezone
from django.template.loader import render_to_string
from person.models import Person
from document.models import Doss... |
464181 | def test_enter(player, limo):
player.perform("enter limo")
assert player.saw("You enter a fancy limo")
assert player.saw("electric")
def test_enter_and_exit(player, limo):
player.perform("enter limo")
player.forget()
player.perform("go out")
assert player.saw("Antechamber")
|
464205 | from abc import ABC, abstractmethod
from typing import Optional, Tuple
import torch
from torch import Tensor, nn
from torch.distributions import Bernoulli, Categorical, Distribution, Normal
from torch.nn import functional as F
from ..prelude import Array, Index, Self
from ..utils import Device
class Policy(ABC):
... |
464211 | import torch.nn as nn
import torch.nn.functional as F
from sodium.utils import setup_logger
from sodium.base import BaseModel
logger = setup_logger(__name__)
class MNISTModel(BaseModel):
def __init__(self, dropout_value=0.08):
self.dropout_value = dropout_value # dropout value
super(MNISTMod... |
464236 | import cartography.intel.digitalocean.platform
import tests.data.digitalocean.platform
TEST_UPDATE_TAG = 123456789
def test_transform_and_load_account(neo4j_session):
account_res = tests.data.digitalocean.platform.ACCOUNT_RESPONSE
"""
Test that we can correctly transform and load DOAccount nodes to Neo4... |
464248 | from textwrap import dedent
from tests import check_as_expected
ROOT = 'superhelp.helpers.print_help.'
def test_misc():
test_conf = [
(
dedent("""\
pet = 'cat'
"""),
{
ROOT + 'print_overview': 0,
}
),
(
... |
464259 | from typing import List, Tuple, Union
import numpy as np
from ...utils.geometry import project_points_onto_plane
def displayed_plane_from_nd_line_segment(
start_point: np.ndarray,
end_point: np.ndarray,
dims_displayed: Union[List[int], np.ndarray],
) -> Tuple[np.ndarray, np.ndarray]:
"""Get the plan... |
464283 | import numpy as np
import neorl.benchmarks.cec17 as functions #import all cec17 functions
import neorl.benchmarks.classic as classics #import all classical functions
from neorl.benchmarks.classic import ackley, levy, bohachevsky #import specific functions
from neorl.benchmarks.cec17 import f3, f10, f21 #impo... |
464326 | import sublime
from .typing import Optional, Union
class ProgressReporter:
def __init__(self, title: str) -> None:
self.title = title
self._message = None # type: Optional[str]
self._percentage = None # type: Union[None, int, float]
def __del__(self) -> None:
pass
def ... |
464336 | import ctypes
from sys import platform as _platform_name
if _platform_name.startswith('win'):
time_t = ctypes.c_uint32
else:
time_t = ctypes.c_uint64
class DSPROJECT(ctypes.Structure):
_fields_ = [("dsapiVersionNo", ctypes.c_int),
("sessionId", ctypes.c_int),
("valueMark",... |
464346 | import os.path
import unittest
import nbformat
from nbparameterise import code, Parameter
samplenb = os.path.join(os.path.dirname(__file__), 'sample.ipynb')
class BasicTestCase(unittest.TestCase):
def setUp(self):
with open(samplenb) as f:
self.nb = nbformat.read(f, as_version=4)
sel... |
464347 | from jiraauth import jclient
import debugmode
"""
This script was used to copy target versions (customfield_10304)
into the fix version field. It's a decent example of how to
iterate over search results and update issues in the result set
"""
i = 0
maxResults=50
num = 50
while i < num:
num, results = jclient.sea... |
464400 | from datasets.base.factory import DatasetFactory
from datasets.base.video.dataset import VideoDataset
from datasets.types.specialized_dataset import SpecializedVideoDatasetType
from datasets.base.video.filter.func import apply_filters_on_video_dataset_
from datasets.MOT.dataset import MultipleObjectTrackingDataset_Memo... |
464412 | from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^(?P<appname>[^/]+)/$',
'oplog.views.api_oplogs', name='api_oplogs'),
]
|
464465 | from node import Node
from arrow import Arrow
from polygon import Polygon
class DownArrow(Arrow):
def __init__(self, position = (0, 0)):
Arrow.__init__(self, position, [Node(-0.4, 0.0), Node(0, 0.5), Node(0.4, 0.0)])
def tip(self):
return Node(*(self.position())) + self.nodes()[1]
def dir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.