id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1633651 | def has_context(txt, context_list):
if any(context in str(txt) for context in context_list):
return True
else:
return False
|
1633656 | import geohash
import json
coll = { "type": "FeatureCollection", "features": []}
h = geohash.encode(48.862004, 2.33734, precision=5)
cells = [h] + geohash.neighbors(h)
for cell in cells:
b = geohash.bbox(cell)
coordinates = []
coordinates.append( [ b['e'], b['s'] ])
coordinates.append( [ b['e'], b['n'] ])
co... |
1633678 | class MissingAttributeException(Exception):
pass
class UnknownMarketException(Exception):
pass
class UnknownPricesException(Exception):
pass
class WrongTypeAttributeException(Exception):
pass
|
1633682 | import asyncio
import logging
import sys
import asynctnt
logging.basicConfig(level=logging.DEBUG)
async def main():
c = asynctnt.Connection(
host='localhost',
port=3305,
connect_timeout=5,
request_timeout=5,
reconnect_timeout=1/3,
)
async with c:
while Tru... |
1633694 | from nose import tools
import numpy as np
from scipy import stats
from . import models
from .. import basis_functions
from .. import solvers
def analytic_solution(t, k0, alpha, delta, g, n, s, **params):
"""Analytic solution for model with Cobb-Douglas production."""
lmbda = (g + n + delta) * (1 - alpha)
... |
1633752 | import pytest
from zquantum.core.interfaces.backend_test import QuantumBackendTests
from zquantum.core.interfaces.mock_objects import MockQuantumBackend
@pytest.fixture
def backend():
return MockQuantumBackend()
class TestMockQuantumBackend(QuantumBackendTests):
pass
|
1633769 | import unittest
import pymysql.cursors
# Not a Python dev, this is probably pretty ugly
class TestDjConventions(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.conn = pymysql.connect(
host="localhost",
user="user",
password="password",
db="heli... |
1633790 | from __future__ import division
import sys
import random
import numpy as np
from scipy.stats import mannwhitneyu
import pandas as pd
import uuid
def load_list(infile):
X = []
with open(infile) as f:
for line in f:
X.append(line.rstrip())
return X
def calc_DE_mannwhitneyu(X, names1, nam... |
1633819 | class BaseExporter:
@staticmethod
def export(puzzle, include_blunder=True):
"""
The method responsible for exporting Puzzle object into desired form.
:return: string representation of Puzzle object
"""
pass
|
1633848 | import os
import random
from statistics import mean
import string
import uuid
import sys
import tracery
import spacy
import pyocr
import pyocr.builders
from PIL import Image, ImageDraw, ImageFilter
BOUND_PADDING = 50
BOX_PADDING = 50 # 10
WOBBLE_MAX = 2
nlp = spacy.load('en')
def draw_vertical_lines(draw, boxes, d... |
1633861 | import textwrap
import pytest
from _pytask.live import LiveExecution
from _pytask.live import LiveManager
from _pytask.nodes import PythonFunctionTask
from _pytask.report import ExecutionReport
from pytask import cli
@pytest.mark.end_to_end
@pytest.mark.parametrize("verbose", [False, True])
def test_verbose_mode_exe... |
1633880 | import sonnet as snt
import tensorflow as tf
# Types of RoI "pooling"
CROP = 'crop'
ROI_POOLING = 'roi_pooling'
class ROIPoolingLayer(snt.AbstractModule):
"""ROIPoolingLayer applies ROI Pooling (or tf.crop_and_resize).
RoI pooling or RoI extraction is used to extract fixed size features from a
variable ... |
1633887 | import ROOT
from ROOT import TGraphErrors
from array import array
from mva_tools.build_roc_simple import build_roc
if __name__ == "__main__":
path = "/Users/musthero/Documents/Yura/Applications/tmva_local/BDT_score_distributions_muons.root"
hsig_path = "histo_tmva_sig"
hbkg_path = "histo_tmva_bkg"
... |
1633973 | import turtle
def item(lenght, level, color):
if level <= 0:
return
for _ in range(5): # 5
turtle.color(colors[color])
turtle.forward(lenght)
item(lenght/4, level-1, color+1)
turtle.penup() # there is no need to draw again the same line (and i... |
1634018 | import numpy as np
gauss_len = 100
gaussian_amp = 0.2
def gauss(amplitude, mu, sigma, delf, length):
t = np.linspace(-length / 2, length / 2, length)
gauss_wave = amplitude * np.exp(-((t - mu) ** 2) / (2 * sigma ** 2))
# Detuning correction Eqn. (4) in Chen et al. PRL, 116, 020501 (2016)
ga... |
1634107 | import pickle
import six
import torch
from mmdet.models import ResNet
depth = 50
variant = 'd'
return_idx = [1, 2, 3]
dcn_v2_stages = [-1]
freeze_at = -1
freeze_norm = False
norm_decay = 0.
depth = 50
variant = 'd'
return_idx = [1, 2, 3]
dcn_v2_stages = [-1]
freeze_at = 2
freeze_norm = False
norm_decay = 0.
model ... |
1634130 | import asyncio
import random
import time
async def noop(ctx):
return 1
async def sleeper(ctx):
# 500 ms / 20 == avg 25 ms per job
await asyncio.sleep(random.random() / 20)
return 1
def sync_noop():
return 1
def sync_sleeper():
time.sleep(random.random() / 20)
return 1
|
1634158 | from enum import Enum
class WaterLoopComponent(object):
def __init__(self):
self._component_name = ''
self._component_template = None
self._function = WaterComponent.chiller
class WaterComponent(Enum):
chiller = 1
boiler = 2
condenser = 3
pump = 4
heatexchanger = 5
|
1634185 | class ImageCropper:
def __init__(self, face_cropper, face_coordinates):
self.face_cropper = face_cropper
self.face_coordinates = face_coordinates
def crop(self, img, output_path):
self.face_cropper.crop_image_into_face(img, self.face_coordinates, output_path)
|
1634198 | from collections import namedtuple, defaultdict
MenuItem = namedtuple("MenuItem", "section order label url")
def menu_order(item):
return item.order
class MenuRegistry(object):
def __init__(self):
self.callbacks = []
def register(self, func):
self.callbacks.append(func)
def get_me... |
1634241 | from __future__ import absolute_import, division, print_function
from cctbx import xray
from scitbx.math import tensor_rank_2_gradient_transform_matrix
from scitbx import matrix
from scitbx.array_family import flex
import cmath
import math
from six.moves import zip
def scatterer_as_list(self):
if (self.flags.use_u_i... |
1634247 | import logging
import copy as cp
from datetime import datetime
from typing import (
TypeVar,
Dict,
Any,
Optional,
Type,
Union,
ClassVar,
Sequence,
)
import attr
import marshmallow
from marshmallow import fields
from cattr.converters import Converter
from simple_smartsheet import confi... |
1634248 | import sqlalchemy as sa
from .reverter import Reverter
from .utils import get_versioning_manager, is_internal_column, parent_class
class VersionClassBase(object):
@property
def previous(self):
"""
Returns the previous version relative to this version in the version
history. If current... |
1634263 | import numpy as np
import copy
def calcbadness(xvals, validcolumns, stimix, results, sessionindicator):
"""
badness = calcbadness(xvals,validcolumns,stimix,results,sessionindicator)
Arguments:
__________
<xvals>:
is a list vector of vectors of run indices
<validcolumns>:
is a list... |
1634296 | import magma as m
import magma.testing
import shutil
import os
import fault
def test_log(capsys):
FF = m.define_from_verilog("""
module FF(input I, output reg O, input CLK, input CE);
always @(posedge CLK) begin
if (CE) O <= I;
end
endmodule
""", type_map={"CLK": m.In(m.Clock), "CE": m.In(m.Enable)})[0]
... |
1634345 | from pip._internal.req import parse_requirements
from setuptools import setup, find_packages
raw_requirements = parse_requirements("requirements/production.txt", session=False)
requirements = [str(ir.req) for ir in raw_requirements]
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name=... |
1634348 | from utils.misc import isnotebook
if isnotebook():
from tqdm import tqdm_notebook as tqdm
else:
from tqdm import tqdm
import numpy as np
import torch
from torch_geometric.data import Data
from torch_geometric.utils import remove_self_loops
from utils.load_dataset import load_data, load_zinc_data, load_ogb_data,... |
1634352 | from .context import assert_equal, x, y, _Add, _Mul, _Pow
import pytest
from sympy import Rational, Mod, sqrt, pi
def _Mod(*args):
return Mod(*args, evaluate=False)
def test_mod_usual():
assert_equal("128\\mod 3", _Mod(128, 3))
assert_equal("7\\mod 128", _Mod(7, 128))
assert_equal("5\\mod 10", _Mod(... |
1634378 | import base64
import math
import os
import uuid
from datetime import datetime
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models import Q
""" Project model."""
class Project(models.Model):
name = ... |
1634406 | import utils
import os
import unittest
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
utils.set_search_paths(TOPDIR)
import ihm.dataset
import ihm.location
import ihm.geometry
def _make_test_file(fname):
with open(fname, 'w') as fh:
fh.write('contents')
class Tests(unittest.Tes... |
1634426 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import arrow
import emission.net.usercache.formatters.common ... |
1634432 | from .Config import Config
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
class Ad(QtWidgets.QWidget):
def __init__(self, minimumSize, responsive=False):
super().__init__()
self.adView = AdView()
self.setLayout(QtWidgets.QHBoxLayout())
self.layout().addChildWidget(... |
1634555 | from typing import List
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str
items = [
{"name": "Foo", "description": "There comes my hero"},
{"name": "Red", "description": "It's my aeroplane"},
]
@app.get("/items/", respons... |
1634568 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
class ... |
1634570 | from django.shortcuts import get_object_or_404, render
from curate.models import Author
def author_embed(request, *args, **kwargs):
slug = kwargs.get('slug')
# Return a 404 if no Author matching that slug is found
get_object_or_404(Author, slug=slug)
# Else return the embed script
return render... |
1634600 | import os
import unittest
import json
from doc2json.s2orc import load_s2orc
JSON_INPUT_DATA = os.path.join('tests', 'pdf', 'N18-3011.json')
class TestS2ORC(unittest.TestCase):
def test_read_write(self):
"""
Check loading current s2orc files
:return:
"""
with open(JSON_IN... |
1634645 | from cstruct import CStructMeta, CStruct, BIG_ENDIAN
from typing import Optional, Any, Union, Dict
from .fields import eTRVField
from .utils import etrv_read_data, etrv_write_data
class eTRVProperty:
def __init__(self, data_struct, **init_kwargs):
self.data_struct = data_struct
self.init_kwargs =... |
1634688 | import datetime
from mongoengine import *
from flask_login import UserMixin
from .annotations import AnnotationModel
from .categories import CategoryModel
from .datasets import DatasetModel
from .images import ImageModel
class UserModel(DynamicDocument, UserMixin):
password = StringField(required=True)
use... |
1634705 | import pytest
from river.adapters.progression_counter import InMemoryProgressionCounter
from river.adapters.topics import InMemoryTopicsManager
from river.topicleaner.service import clean
pytestmark = pytest.mark.django_db
def test_done_batch_is_cleaned(batch_factory, resource_factory):
r1, r2 = resource_factor... |
1634706 | from trex_stl_lib.api import *
import argparse
# stream from pcap file. continues pps 10 in sec
# path_relative_to_profile = True
class STLS1(object):
def get_streams (self, direction, tunables, **kwargs):
parser = argparse.ArgumentParser(description='Argparser for {}'.format(os.path.basename(__file__))... |
1634728 | import torch
import torch.nn as nn
import torch.distributions as tdist
from iflow.densities import AngleNormal
class DynamicModel(nn.Module):
def __init__(self, dim, device=None, dt = 0.01, requires_grad=True):
super().__init__()
self.dim = dim
self.device = device
self.dt = dt
... |
1634736 | while True:
try:
a = int(input("enter your age :"))
if a > 18:
print("Adult")
elif 10 < a <= 18:
print("Teen")
elif a <= 10:
print("Child")
break
except ValueError:
print("enter valid age")
break
|
1634744 | while True:
num = int(input('Please enter an integer 0 through 9. '))
if num in range(0, 10):
print(num)
else:
print('That\'s not in range. ')
break
|
1634747 | from flask_jwt_extended import JWTManager
from app.dao.users_dao import get_user_by_id
from app.models import User
jwt = JWTManager()
@jwt.user_identity_loader
def transform_user_to_identity_for_jwt(user: User):
return {
'id': user.id,
'name': user.name,
'email_address': user.email_addre... |
1634763 | import torch.nn as nn
class IntermediateSequential(nn.Sequential):
def __init__(self, *args, return_intermediate=True):
super().__init__(*args)
self.return_intermediate = return_intermediate
def forward(self, input):
if not self.return_intermediate:
return super().forward(... |
1634785 | from typing import List
from geoalchemy2.shape import from_shape
from couchers.models import Cluster, ClusterRole, ClusterSubscription, Node, Page, PageType, PageVersion, Thread
DEFAULT_PAGE_CONTENT = "There is nothing here yet..."
DEFAULT_PAGE_TITLE_TEMPLATE = "Main page for the {name} {type}"
def create_node(ses... |
1634820 | import discord
from MuteAll import errors
async def do(ctx, task="mute", members=[]):
try:
for member in members:
match task:
case "mute":
await member.edit(mute=True)
case "unmute":
await member.edit(mute=False)
... |
1634837 | from functools import total_ordering
from operator import is_
import numpy as np
from typing import Callable, Iterable, List, Optional, Sequence, Tuple, Union
from numpy import random
from scipy.ndimage import rotate, map_coordinates, gaussian_filter
import h5py
from itertools import chain
from batchgenerators.augment... |
1634859 | import serial
import rospy
from constants import constants
import numpy as np
from std_srvs.srv import SetBool, SetBoolResponse
class NoopSerial(serial.Serial):
'''
Inherits from serial.Serial, doing nothing for each function.
Allows super classes to implement custom behavior for simulating
serial dev... |
1634873 | import os
import sys
sys.path.insert(0, os.path.dirname(os.path.realpath(__name__))+"/../sklite")
project = 'SkLite'
copyright = '2019, <NAME>'
author = '<NAME>'
release = '0.0.1'
extensions = [
'sphinx.ext.autodoc',
'numpydoc',
]
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', ... |
1634876 | from pyNastran.bdf.bdf import read_bdf
from pyNastran.op2.op2 import read_op2
bdf_filename = 'beam_modes.dat'
op2_filename = 'beam_modes_m2.op2'
#2) Open an op2
op2_model = read_op2(op2_filename)
print(op2_model.get_op2_stats())
subcase = 1
# 3a) Load grid point locations
model = read_bdf(bdf_filename)
# I'm assumi... |
1634882 | from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin, UserManager
from django.core.mail import send_mail
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from .validators import UsernameVa... |
1634904 | class Car():
"""Un simple intento de representar un auto"""
def __init__(self, manufacturer, model, year):
"""Inicializar atributos para describir un automóvil."""
self.manufacturer = manufacturer
self.model = model
self.year = year
self.odometer_reading = 0
... |
1634930 | from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from typing import Callable
from functools import wraps
class glpy:
"""Main class to initialize OpenGL and Glut functions
"""
def __init__(self, **kwargs):
"""initialize the class with the following parameters
Keyw... |
1634942 | import numpy as np
from somo.sm_manipulator_definition import SMManipulatorDefinition
from somo.sm_actuator_definition import SMActuatorDefinition
from somo.sm_link_definition import SMLinkDefinition
from somo.sm_joint_definition import SMJointDefinition
from somo.sm_continuum_manipulator import SMContinuumManipulator... |
1634946 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from torch.nn import init
import math
from net import MLP, StateTransition
class GNN(nn.Module):
def __init__(self, config, state_net=None, out_net=None):
super(GNN, self).__init__()
self.... |
1634979 | import pytest
from rig.bitfield import BitField
from nengo_spinnaker.utils import keyspaces
def test_get_derived_keyspaces():
"""Test creation of derived keyspaces."""
ks = BitField()
ks.add_field("index")
ks.add_field("spam")
# General usage
kss = keyspaces.get_derived_keyspaces(ks, (slice(5... |
1635027 | import matplotlib.pyplot as plt
# Measurements from block-size.data
bsize = [
('HS-b100',[
(15.680,11.21),
(28.095,11.75),
(52.799,12.84),
(54.457,22.74),
(54.378,26.32),
(53.818,40.95)
], '-o', 'coral'),
('HS-b400',[
(20.0,11.58),
(40.0,12.69... |
1635035 | import argparse
import logging
import timeit
import random
import cv2
from util.frame_convert import pretty_depth_cv
from robot.base import get_remote_robot
from learner.games import ObstacleAvoidanceGameEnvironment
def main(args):
print('preparing ...')
robot = get_remote_robot(args.agent, args.host, args.... |
1635040 | from datetime import datetime
from time import time
from typing import TYPE_CHECKING
import pytest
from grouper.entities.group import GroupJoinPolicy
from grouper.graph import NoSuchGroup, NoSuchUser
from grouper.plugin.base import BasePlugin
if TYPE_CHECKING:
from tests.setup import SetupTest
def build_test_g... |
1635052 | import os
import unittest
import sys
import tempfile
sys.path.append('../fightchurn')
sys.path.append('../datagen')
from fightchurn import run_churn_listing
from fightchurn.datagen import churndb
class TestFightChurnWIthData(unittest.TestCase):
def test_run_entire_book(self):
database=username=password='... |
1635086 | from eventsourcing.popo import (
Factory,
POPOAggregateRecorder,
POPOApplicationRecorder,
POPOProcessRecorder,
)
from eventsourcing.tests.base_aggregate_recorder_tests import (
AggregateRecorderTestCase,
)
from eventsourcing.tests.base_application_recorder_tests import (
ApplicationRecorderTestC... |
1635198 | from unittest import TestCase
from niaaml import ParameterDefinition, MinMax, OptimizationStats, get_bin_index
import numpy as np
import tempfile
class UtilitiesTestCase(TestCase):
def test_get_bin_index_works_fine(self):
self.assertEqual(get_bin_index(0.0, 4), 0)
self.assertEqual(get_bin_index(0.... |
1635258 | import unittest
from generativepy.nparray import make_nparray, make_nparray_frame
from generativepy.movie import save_frame
from image_test_helper import run_image_test
import numpy as np
"""
Test each function of the nparray module, with 1, 3 and 4 channel output
"""
def draw4(array, pixel_width, pixel_height, frame... |
1635272 | from io import BytesIO, SEEK_END
import attr
from PIL import Image
MAX_EDGE_PIXELS = 1024
QUALITY = 80
SUPPORTED_FORMATS = ('JPEG', 'PNG', 'GIF')
MAX_SIZE_IN_BYTES_AFTER_PROCESSING = 1024 * 1024
MIN_AREA_TRACKING_PIXEL = 10
@attr.s
class ImageProcessingResult:
size_in_bytes: int = attr.ib()
width: int = att... |
1635282 | import tensorflow as tf
from tensorflow.keras import layers, Sequential, Model
class BasicConv2D(layers.Layer):
def __init__(self, kernels, kernel_size=(3, 3), strides=1, padding='valid'):
super(BasicConv2D, self).__init__(self)
self.conv = layers.Conv2D(kernels,
... |
1635322 | from typing import Iterable, Mapping
from chaoslib import Configuration, Secrets
from logzero import logger
from chaosazure import init_compute_management_client
from chaosazure.common import cleanse
from chaosazure.common.compute import command
from chaosazure.vmss.fetcher import fetch_vmss, fetch_instances
from cha... |
1635332 | from asmdot import * # pylint: disable=W0614
from typing import Tuple
header = '''// Automatically generated file.
package {}
import (
\t"bytes"
\t"encoding/binary"
\t"errors"
\t"io"
)
// Bypass unused module error if we don't have assertions.
var _ = errors.New
var (
\tinterbuf = [8]byte{{}}
\tbyteOrder ... |
1635365 | import re
from unidecode import unidecode
from ..utils import squeeze, translation, check_str, check_empty
from .phonetic_algorithm import PhoneticAlgorithm
class Lein(PhoneticAlgorithm):
"""
The Lein name coding procedure.
[Reference]: http://naldc.nal.usda.gov/download/27833/PDF
"""
def __init... |
1635384 | from multiprocessing import Pool
import dataio as dio
import time
def get_model(seqLen=100, numBalls=2):
time.sleep(3)
ds = dio.DataSaver(wThick=30, isRect=True, mnSeqLen=seqLen, mxSeqLen=seqLen,
numBalls=numBalls, mnBallSz=25, mxBallSz=25)
ims = ds.fetch()
return ims
def run_parallel(numW=4, numJobs=10):
... |
1635447 | import os
import warnings
import sklearn.decomposition
import numpy as np
from .openl3_exceptions import OpenL3Error
with warnings.catch_warnings():
# Suppress TF and Keras warnings when importing
warnings.simplefilter("ignore")
import tensorflow as tf
import tensorflow.keras.backend as K
from tens... |
1635459 | from unittest import TestCase
from .common import link_test_file, html_lines
class LinkerTest(TestCase):
def test_link_install(self):
self.assertEqual(link_test_file('install.rst'), html_lines('Installation', [
'<h1>Installation</h1>',
]))
def test_link_tutorial(self):
se... |
1635473 | from abc import ABC, abstractmethod
from typing import Any, Awaitable, Callable, Dict, Optional, Type
AsyncFunc = Callable[..., Awaitable[Any]]
class ABCErrorHandler(ABC):
error_handlers: Dict[Type[BaseException], AsyncFunc]
undefined_error_handler: Optional[AsyncFunc]
@abstractmethod
def register_e... |
1635479 | import sys
from unittest.mock import call, create_autospec
import pytest
try:
from rich._win32_console import LegacyWindowsTerm, WindowsCoordinates
from rich._windows_renderer import legacy_windows_render
except:
# These modules can only be imported on Windows
pass
from rich.segment import ControlType... |
1635505 | from typing import List
from .docutils import LATEX_TAG_BEGIN_FORMAT, LATEX_TAG_END_FORMAT
from .snippetExceptions import SnippetException
class Snippet:
BEGIN_TEMPLATE = LATEX_TAG_BEGIN_FORMAT
END_TEMPLATE = LATEX_TAG_END_FORMAT
INDENT = " "
def __init__(self, name: str, tags=[]):
self.__n... |
1635621 | def rate_password(username, password):
lc = uc = num = spc = oth = usn = 0
for n in password:
if n.islower(): lc = 2
if n.isupper(): uc = 3
if n.isdigit(): num = 5
if n.isspace(): spc = 5
if not n.isalnum(): oth = 10
if password.find(username)> -1: usn = -15
... |
1635634 | import logging
logging.basicConfig(level=logging.DEBUG)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
fgp = __import__('FaST-GP')
ds = __import__('data_simulation')
def get_coords(index):
coords = pd.DataFrame(index=index)
coords['x'] = index.str.split('x').st... |
1635640 | from random import randint, seed
seed(10) # Set random seed to make examples reproducible
random_dictionary = {i: randint(1, 10) for i in range(5)}
print(random_dictionary) # {0: 10, 1: 1, 2: 7, 3: 8, 4: 10}
|
1635660 | from . import views
def register_in(router):
router.register(r'slurm-jobs', views.JobViewSet, basename='slurm-job')
|
1635718 | import taichi as ti
from utils.tools import Pair
from pcg_method import PCG_Solver
import numpy as np
@ti.data_oriented
class Thin_Flame:
def __init__(self , resolution = 512 ) :
shape = (resolution , resolution)
self._sd_cur = ti.var(dt = ti.f32 , shape= shape)
self._sd_nxt = ti.var(dt = ... |
1635723 | from mal import Anime
from bs4 import BeautifulSoup
import numpy
import requests
def animerec():
p = numpy.random.randint(16000,size=1)
id = int(p[0])
# for i in range(id,16000):
try:
anime = Anime(id)
title = str(anime.title)
titlef = title.replace(' ','_')
titlef = ti... |
1635739 | def extractBorahae7WordpressCom(item):
'''
Parser for 'borahae7.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Prophet', 'The Strongest Prophet Who Had Trained 100 Heroes i... |
1635755 | class Meta(type):
def __add__(self, x: str) -> str:
return 'a' + x
class C(metaclass=Meta):
...
print(C + 'x') # Okay
print(C + 1) # error: Unsupported operand types for + ("Type[C]" and "int")
|
1635809 | from numpy import sign
def comp_rot_dir(self):
"""Compute the rotation direction of the fundamental magnetic field induced by the winding
WARNING: rot_dir = -1 to have positive rotor rotating direction, i.e. rotor position moves towards positive angle
Parameters
----------
self : LamSlotMultiWind... |
1635830 | import numpy as np
import pytest
import random
import torch
import densetorch as dt
NUMBER_OF_PARAMETERS_WITH_21_CLASSES = {
"152": 61993301,
"101": 46349653,
"50": 27357525,
"mbv2": 3284565,
}
NUMBER_OF_ENCODER_DECODER_LAYERS = {
"152": (465, 28),
"101": (312, 28),
"50": (159, 28),
... |
1635843 | import numpy as np
from pyecsca.sca import (
align_correlation,
align_peaks,
align_sad,
align_dtw_scale,
align_dtw,
Trace,
InspectorTraceSet,
)
from .utils import Plottable, slow
class AlignTests(Plottable):
def test_align(self):
first_arr = np.array(
[10, 64, 120, ... |
1635845 | from matplotlib.testing import setup
import numpy as np
import numpy.testing as npt
import matplotlib.pyplot as plt
import matplotlib as mpl
import packaging.version
import pytest
import animatplot as amp
from tests.tools import animation_compare
from animatplot.blocks import Block, Title
setup()
class TestTitleB... |
1635876 | import FWCore.ParameterSet.Config as cms
from Configuration.ProcessModifiers.enableSonicTriton_cff import enableSonicTriton
# collect all SonicTriton-related process modifiers here
allSonicTriton = cms.ModifierChain(enableSonicTriton)
|
1635893 | class EditorAttribute(Attribute,_Attribute):
"""
Specifies the editor to use to change a property. This class cannot be inherited.
EditorAttribute()
EditorAttribute(typeName: str,baseTypeName: str)
EditorAttribute(typeName: str,baseType: Type)
EditorAttribute(type: Type,baseType: Type)
"""
... |
1635935 | import multiprocessing
from typing import Union, List, Tuple
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
from video_transforms import (GroupRandomHorizontalFlip, GroupOverSample,
... |
1636013 | import logging
import faiss
import torch
import torch.nn as nn
from sklearn.manifold import TSNE
def manifold_learning(x, nbit):
tsne = TSNE(nbit, init='pca', method='exact')
y = tsne.fit_transform(x)
return y
class IMHLoss(nn.Module):
def __init__(self, nbit, kmeans_iters=200, m=400, k=5, bandwidt... |
1636020 | import asyncio
import json
import logging
import os.path
import threading
from logging import Formatter
from time import sleep
from typing import Optional
from getmac import get_mac_address as gma
from sqlalchemy.exc import OperationalError
from tornado.platform.asyncio import AnyThreadEventLoopPolicy
from angrmanag... |
1636027 | from seabreeze.pyseabreeze.features._base import SeaBreezeFeature
# Definition
# ==========
#
# TODO: This feature needs to be implemented for pyseabreeze
#
class SeaBreezeWifiConfigurationFeature(SeaBreezeFeature):
identifier = "wifi_configuration"
def get_wifi_mode(self, interface_index):
raise Not... |
1636036 | from .base import ResourceBase
from .archive import Archive
from .multivector import Multivector
from .instance import Instance
from .rawdata import RawData
from .vector import Vector
from .bound_resource import BoundResource
|
1636087 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import List, Dict, Union
from yacs.config import CfgNode
from .jenson_shannon_divergence import jensen_shannon_divergence
from .build import LOSS_REGISTRY
class LabelSmoothingCrossEntropy(torch.nn.Module):
"""
Code copied from fa... |
1636115 | import numpy as np
class ReplayBuffer:
"""Experience Replay Buffer para DQNs."""
def __init__(self, max_length, observation_space):
"""Cria um Replay Buffer.
Parâmetros
----------
max_length: int
Tamanho máximo do Replay Buffer.
observation_space: int
... |
1636119 | import datetime
import pytest
from prisma import Client
# TODO: add tests for every database provider we support
@pytest.mark.asyncio
async def test_precision_loss(client: Client) -> None:
"""https://github.com/RobertCraigie/prisma-client-py/issues/129"""
date = datetime.datetime.utcnow()
post = await... |
1636127 | import warnings
from django.test import SimpleTestCase
from .models import Person
class HasAutoFieldTests(SimpleTestCase):
def test_get_warns(self):
with warnings.catch_warnings(record=True) as warns:
warnings.simplefilter('always')
Person._meta.has_auto_field
self.asser... |
1636129 | from io import BytesIO
import asyncio
import asyncpg
from fixtures.zenith_fixtures import ZenithEnv, Postgres
from fixtures.log_helper import log
from fixtures.benchmark_fixture import MetricReport, ZenithBenchmarker
pytest_plugins = ("fixtures.zenith_fixtures", "fixtures.benchmark_fixture")
async def repeat_bytes(b... |
1636181 | import subprocess as sub
#import sys
import argparse
import datasetConfig
parser = argparse.ArgumentParser('Tasas for CER')
parser.add_argument('epochs', type=int, help='how many epochs')
parser.add_argument('flag', type=str, help='si/no with/without testing')
#parser.add_argument('folder', type=str, help='pred_logs_l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.