id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9961457 | import numpy as np
import pylab
import sys, pickle, cPickle, gzip
sys.path.append('/Users/gregv/deepcloud/discrete_sieve')
import sieve
import vis_sieve
def entropy(x):
n_samples = len(x)
ps = np.bincount(x).astype(float) / n_samples
return np.sum(np.where(ps > 0, -ps * np.log2(ps), 0))
def save_digit(z, filen... |
9961507 | def DeslocaASCII(texto):
novoTexto = ''
for letra in texto:
numero = ord(letra)
novoTexto += chr(numero + (-23 if numero > 87 else 3))
return novoTexto
print(DeslocaASCII('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
#https://pt.stackoverflow.com/q/253730/101
|
9961515 | import os
from util import *
import abc
import yaml
from eval_engines.ngspice.TwoStageComplete import TwoStageMeasManager
import importlib
class NgspiceEvaluationCore(object):
def __init__(self, design_specs_fname):
self.design_specs_fname = design_specs_fname
with open(design_specs_fname, 'r') as ... |
9961516 | from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen
from akivymd.uix.behaviors.addwidget import AKAddWidgetAnimationBehavior
from kivymd.uix.list import MDList, OneLineListItem
Builder.load_string(
"""
<AddWidgetBehavior>:
name: 'AddWidgetBehavior'
BoxLayout:
orientatio... |
9961530 | from aiozk import WatchEvent
from aiozk.exc import NoNode
from .base_watcher import BaseWatcher
class DataWatcher(BaseWatcher):
watched_events = [WatchEvent.DATA_CHANGED, WatchEvent.DELETED]
def __init__(self, *args, wait_for_create=False, **kwargs):
super().__init__(*args, **kwargs)
if wa... |
9961543 | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.di... |
9961575 | from time import sleep as delay
from cloudstackAPI import (
listSystemVms,
listZones,
listTemplates
)
from cloudstackTestCase import cloudstackTestCase
class TestSetupSuccess(cloudstackTestCase):
"""
Test to verify if the cloudstack is ready to launch tests upon
1. Verify that system VMs are ... |
9961580 | import pytest
from sidekick import Record, Maybe, Nothing, Union, Case, to_maybe, Ok, Err
from sidekick.types.union import SingletonMeta, SingletonMixin
UnionMeta = type(Union)
class TestCreateUnionType:
def test_case_constructor(self):
assert issubclass(Case("foo"), Record)
assert issubclass(Ca... |
9961632 | for row in range(7):
for col in range(6):
if col==0 or (col==4 and (row!=1 and row!=2))or ((row==0 or row==6)and (col>0 and col<4))or (row==3 and (col==3 or col==5)):
print("*",end="")
else:
print(end=" ")
print()
|
9961679 | from setuptools import setup, find_packages
with open("README.rst", "r", encoding='utf-8') as fh:
long_description = fh.read()
setup(name = 'ChiantiPy',
description = 'a Python interface to the CHIANTI atomic database for astrophysical spectroscopy',
long_description = long_description,
# long_descr... |
9961685 | import torch
import numpy as np
import os
import inspect
from pickle import load, dump
def generate_samples(generator, gen_input):
out = generator.forward(gen_input)
out = out.cpu().data.numpy()
return out
def save_pkl(fname, obj):
with open(fname, 'wb') as f:
dump(obj, f)
def load_pkl(fna... |
9961709 | from unittest.mock import MagicMock
from ib_async.instrument import Instrument
from ib_async.functionality.executions import ExecutionsMixin
from ib_async.functionality.orders import OrdersMixin
from ib_async.protocol import Incoming, Outgoing, ProtocolVersion
from .utils import FunctionalityTestHelper
class MixinF... |
9961738 | import socket
import datetime
from future.utils import iteritems
from pandaharvester.harvesterconfig import harvester_config
from pandaharvester.harvestercore import core_utils
from pandaharvester.harvestercore.db_proxy_pool import DBProxyPool as DBProxy
from pandaharvester.harvesterbody.agent_base import AgentBase
fro... |
9961762 | h = 1
n = 2
h_lista = []
n_lista = []
print("H = 1 +", end = "")
while n <= 10 -1:
print(" ",h, "/", n, " + ", end="")
h_lista.append(h)
n_lista.append(n)
n += 1
print(h, "/", n, " => ", sum(h_lista), "/", sum(n_lista), " => ", round(sum(h_lista) / sum(n_lista)), 2)
|
9961799 | import sqlite3
import pytest
from pydapper import connect
from pydapper import using
from pydapper.sqlite import Sqlite3Commands
from tests.suites.commands import ExecuteScalarTestSuite
from tests.suites.commands import ExecuteTestSuite
from tests.suites.commands import QueryFirstOrDefaultTestSuite
from tests.suites.... |
9961815 | from tests.utils import _TestBase
class TestNonSCM(_TestBase):
def test_thLib(self):
url = self.converter.get_vcs("thLib")
self.assertInsensitiveEqual(url, "http://work.thaslwanter.at/thlib/html/")
def test_PyRSS2Gen(self):
url = self.converter.get_vcs("PyRSS2Gen")
self.assert... |
9961883 | import numpy as np
import gc
import os
import numpy as np
from GenNet_utils.hase.hdgwas.hdregression import HASE, A_covariates, A_tests, B_covariates, C_matrix, A_inverse, B4
from GenNet_utils.hase.hdgwas.tools import study_indexes, Timer, merge_genotype
def haseregression(phen, gen, cov, mapper, Analyser, maf, int... |
9961890 | import arcpy
import os
import time
from arcpy.mp import *
# from arcpy.mapping import *
def delineate_catchment(in_dem, in_sink, out_catchment):
arcpy.CheckOutExtension("Spatial")
workspace = os.path.split(out_catchment)[0]
arcpy.env.workspace = workspace
arcpy.env.overwriteOutput = True
... |
9961895 | from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QFileDialog
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import sys
class CustomLabel(QLabel):
def __init__(self, parent=None):
super(CustomLabel, self).__init__(parent)
self.setMouseTracking(True)
def mousePressEvent(s... |
9961907 | import unittest
from cactus.util.setproctitle import setproctitle
class TestSetProcTitle(unittest.TestCase):
def test_does_not_crash(self):
setproctitle("cactus test title")
|
9961919 | import unittest
import os
from pycountry import countries as pycountries
import pandas as pd
from unittest import mock
from nesta.packages.meetup.country_groups import MeetupCountryGroups
from nesta.packages.meetup.country_groups import get_coordinate_data
from nesta.packages.meetup.country_groups import assert_iso2_k... |
9961935 | import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import cv2
import os
from tensorflow.keras.preprocessing.image import ImageDataGenerator,array_to_img,img_to_array
from google.colab import drive
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras... |
9961946 | import datetime
from timeit import default_timer as timer
from dataSet.reader import *
from dataSet.transform import *
from models.model import *
import torch
import torch.nn as nn
import time
from utils.file import *
from utils.metric import *
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
size = 96
d, WIDTH... |
9961948 | from app.thirdparty.oneforall.config import settings
from app.thirdparty.oneforall.common.query import Query
class VirusTotalAPI(Query):
def __init__(self, domain):
Query.__init__(self)
self.domain = domain
self.module = 'Intelligence'
self.source = 'VirusTotalAPIQuery'
sel... |
9961953 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from onnx.backend.base import BackendRep, namedtupledict
import tensorflow as tf
class TensorflowRep(BackendRep):
def __init__(self, predict_net, input_dict, uninitial... |
9962039 | def runUserScript(func, params, paramTypes):
if (len(params) != len(paramTypes)):
onParameterError()
newParams = []
for i, val in enumerate(params):
newParams.append(parseParameter(i, paramTypes[i], val))
func(*newParams)
class Node:
def __init__(self, val, left, right,... |
9962079 | import pytesseract
from PIL import Image
def recognition_card(img):
image = Image.fromarray(img)
tessdata_dir_config = '--psm 7 --oem 1'
result = pytesseract.image_to_string(image, lang='eng', config=tessdata_dir_config)
return result
|
9962103 | import io
import typing
import qtrio.examples.readme.console
def test_normal_usage():
input_file = io.StringIO("Ms. Console\n")
output_file = io.StringIO()
qtrio.examples.readme.console.main(input_file=input_file, output_file=output_file)
assert (
output_file.getvalue()
== "What is ... |
9962107 | import unittest
def run_tests(test_class):
suite = unittest.TestLoader().loadTestsFromTestCase(test_class)
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
return result
class Test3(unittest.TestCase):
ALL_SURVIVOR = [(7, 3), (11, 9), (1, 300), (14, 2), (100, 1)]
RESU... |
9962139 | from __future__ import division
from math import radians, sin, cos
import util
class Triangle(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def box(self):
ax, ay, az = self.a
bx, by, bz = self.b
cx, cy, cz = self.c
x1 = min(min... |
9962155 | from neon import NervanaObject
import numpy as np
from util import util
from neon.transforms import Softmax
EPS = np.finfo(np.float32).tiny
class MBoxLoss(NervanaObject):
def __init__(self, num_classes=21, share_location=True,
clip=False, background_label_id=0,
use_difficult=Tru... |
9962156 | import sys,os
encoding = sys.getfilesystemencoding()
path = os.path.dirname(unicode(__file__, encoding))
parentdir = os.path.dirname(path)
if parentdir not in sys.path:
sys.path.insert(0,parentdir)
|
9962192 | from typing import List, Optional
from .config import T5Configuration
from ...core import Model, Layer, Context, Tensor, Device
from ...core.allocators.cuda import CUDAAllocator
from ...layers import LayerList, EncoderBlock, DecoderBlockWithCrossAttention
from ...layers import Embedding, Layernorm, PositionEmbedding
f... |
9962199 | import json
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import regularizers
# import tensorflow_probability as tfp
import random
# look up indices (to use for names)
def index_dict(l):
return {l[j]: j for j in range(len(l))}
... |
9962236 | from mock import patch
from aplatam.post_process import *
from shapely.geometry import box, mapping
def test_apply_buffer():
boxes = [box(0, 0, 1, 1), box(2, 3, 2, 4)]
boxes_with_props = [ShapeWithProps(b, {}) for b in boxes]
new_boxes_with_props = apply_buffer(boxes_with_props, 3)
assert all(a.props... |
9962242 | from roboticstoolbox.robot.Robot import Robot
from roboticstoolbox.robot.Link import Link
from roboticstoolbox.robot.DHRobot import SerialLink, DHRobot
from roboticstoolbox.robot.DHLink import (
DHLink,
RevoluteDH,
PrismaticDH,
RevoluteMDH,
PrismaticMDH,
)
from roboticstoolbox.robot.ERobot import ER... |
9962262 | from .models import Post
from .serializer import PostSerializer
from rest_framework import generics
class PostList(generics.ListCreateAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Post.objects.all()
seria... |
9962321 | from dynaconf import Dynaconf
settingsenv = Dynaconf(environments=True)
settings = Dynaconf(TEST_KEY="test_value", ANOTHER_KEY="another_value")
|
9962345 | import os
import sys
import logging
import subprocess
from contextlib import closing
import xml.etree.ElementTree
from collections import defaultdict
import HTSeq
import do
import mapper
from argparse import ArgumentParser
'''
HOWTO:
python counter.py --inp SRRXXXXX --out SRRXXXX_counts
TODOs:
* detect if pair... |
9962372 | from test_project.testapp.models import Movie
from rest_framework.serializers import ModelSerializer
class MovieSerializer(ModelSerializer):
class Meta:
model = Movie
fields = ["id", "title", "rating", "genre"]
|
9962392 | from project.langs.forth.forthimpl import create_forth, forth_compile, launch_repl
forth = create_forth()
|
9962429 | import socket
import struct
import hashlib
from functools import partial
from py_mysql_binlogserver._tutorial.learn_packet1_greeting import get_greeting
def dump_packet(packet, title=None):
"""
Dumps a packet to the console
"""
title = title or "Packet Dump"
offset = 0
dump = title + '\n'
... |
9962455 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.plant import PlantLoop
log = logging.getLogger(__name__)
class TestPlantLoop(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def t... |
9962462 | from __future__ import print_function, division
import matplotlib
import logging
from sys import stdout
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer
from neuralnilm.net import BidirectionalRecurrentLayer
from la... |
9962491 | from setuptools import setup
from distutils.core import Extension
def install_requires():
"""Generate list with dependency requirements"""
deps = []
with open("requirements.txt", "r") as f:
for line in f:
deps.append(line[:-1])
return deps
def long_description():
with open(... |
9962506 | import pykd
import re
LOG_FILE = open(r'C:\local\tmp\ttt-common-step-monitor.txt', 'w')
def pykdLog2File(logObj, fileObj):
for line in str(logObj).split('\n'):
fileObj.write(line+'\n')
def pykdLog(log):
print(log)
pykdLog2File(log, LOG_FILE)
pykd.dbgCommand(r'bd *')
# 54C1D40000025
# 54C49C00000... |
9962514 | import curses as c
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
c.initscr()
win = c.newwin(20, 60, 0, 0)
win.keypad(1)
c.noecho()
c.curs_set(0)
win.border(0)
win.nodelay(1)
snake = [[4, 10], [4, 9], [4, 8]]
food = [10, 20]
win.addch(food[0], food[1], 'O')
c.endwin()
key = KEY_RIGHT # default key
# AS... |
9962559 | import argparse
import json
import os
from pprint import pprint
import numpy as np
import torch
from PIL import Image
from torch.autograd import Variable
from torch.utils import data
from torchvision.transforms import Compose, Normalize, ToTensor
from tqdm import tqdm
from argmyparse import add_additional_params_to_ar... |
9962603 | class Solution:
def distinctSubseqII(self, S: str) -> int:
end = [0] * 26
for c in S:
end[ord(c) - ord('a')] = sum(end) + 1
return sum(end) % (10**9 + 7)
class Solution:
def distinctSubseqII(self, S: str) -> int:
res, end = 0, collections.Counter()
for c in ... |
9962641 | import json
import os
import pandas as pd
PATH = os.path.dirname(os.path.realpath(__file__)) + "/json_data/"
DATABASE = PATH + "../predictor_prod.db"
with open(PATH + "preguntas.json") as f:
PREGUNTAS = []
# create the dict structure for the questions constant
file_questions = json.load(f)
index = 1
... |
9962675 | from .devtools import remote_debug, response_parser
from .database import database_admin, database_writer
from . import html_parser, links_parser, external_links, html_validator, http_headers_analyzer
from .blacklist import blacklist_checker
from pagewalker.config import config
class Analyzer(object):
def __init_... |
9962677 | from __future__ import absolute_import
import logging
import raven
from huskar_api import settings
from huskar_api.switch import (
switch, SWITCH_ENABLE_SENTRY_MESSAGE, SWITCH_ENABLE_SENTRY_EXCEPTION)
logger = logging.getLogger(__name__)
raven_client = raven.Client(
dsn=settings.SENTRY_DSN) if settings.SE... |
9962685 | from trade_stat_logger.logger import SimpleLogger
from trade_stat_logger._position import _Position
|
9962699 | import jinja2
from nose.tools import eq_, ok_
from mock import ANY, patch
from affiliates.base.tests import NewsItemFactory, NewsItemTranslationFactory, TestCase
class NewsItemTests(TestCase):
def setUp(self):
patcher = patch('affiliates.base.models.bleach')
self.addCleanup(patcher.stop)
... |
9962785 | from collections import abc
import torch
from torch._six import string_classes
from torch.nn.parallel.scatter_gather import gather
from torchdistill.common.module_util import check_if_wrapped, get_module
def get_device_index(data):
if isinstance(data, torch.Tensor):
device = data.device
return '... |
9962787 | from sqlalchemy import Column, Integer, String, func, Boolean
from app import db
class CnesEquipment(db.Model):
__tablename__ = 'cnes_equipment'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
microregion = Colu... |
9962820 | import asyncio
from aiochatbase import Chatbase
API_KEY = 'paste-your-api-key-token-here'
PLATFORM = 'Telegram'
loop = asyncio.get_event_loop()
cb = Chatbase(api_key=API_KEY, platform=PLATFORM, loop=loop)
async def send_event():
any_dict = {
'property 1 (int)': 1,
'property 2 (str)': 'two',
... |
9962824 | from __future__ import annotations
from typing import Any, Callable, Generator
from .base import Pipeline, PipelineExecutor
GeneratorPipeline = Generator[Any, None, None]
class GeneratorPipelineExecutor(PipelineExecutor[GeneratorPipeline]):
"""An executor which returns a Generator.
The Generator yeilds `fu... |
9962836 | import copy
import logging
import os
import pathlib
import pickle
import numpy as np
from sklearn import linear_model
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import SGDRegressor
from sklearn.multioutput import MultiOutputRegressor
from sklearn.svm import SVR
from base import B... |
9962853 | import sys
import typing as t
from mailers.config import EmailURL
from mailers.transports.base import Transport
from mailers.transports.stream import StreamTransport
class ConsoleTransport(StreamTransport):
def __init__(self, stream: t.Literal['stdout', 'stderr'] = 'stderr') -> None:
assert stream in ['s... |
9962884 | from pygsti.models import qutrit
from ..util import BaseCase
class QutritConstructionTester(BaseCase):
def test_ideal_qutrit(self):
mdl_post = qutrit.create_qutrit_model(error_scale=0.0, similarity=False, seed=1234, basis='qt')
mdl_sim = qutrit.create_qutrit_model(error_scale=0.0, similarity=True,... |
9962904 | import re
from rest_framework import serializers
from labels.utils import search_text_for
from .models import Pack, PackIcon
class PackSerializer(serializers.ModelSerializer):
"""Packs's serializer"""
class Meta:
model = Pack
class PackIconSerializer(serializers.ModelSerializer):
"""PackIco... |
9962931 | import numpy as np
import torch
def torch_segment_axis(
x,
length,
shift,
axis=-1,
end='cut', # in ['pad', 'cut', None]
pad_mode='constant',
pad_value=0,
):
"""Generate a new array that chops the given array along the given axis
into overlapping frame... |
9962986 | import paddle
import paddle.nn as nn
import paddle.nn.functional as F
__all__ = ['forward_hook', 'Clone', 'Add', 'Cat', 'ReLU', 'Dropout', 'BatchNorm2D', 'Linear', 'MaxPool2D',
'AdaptiveAvgPool2D', 'AvgPool2D', 'Conv2D', 'Sequential', 'safe_divide']
ZERO_TENSOR = paddle.to_tensor(0.)
def safe_divide(a, ... |
9962991 | import imp
import os
import logging
import ConfigParser
from config_helper import get_boolean_or_default
plugin_logger = logging.getLogger('pluginloader::')
class PluginLoader:
def __init__(self, allowed_plugins=[]):
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read('config.in... |
9963018 | import functools
import importlib
import logging
import pkgutil
import sys
from .hooks import post_import, pre_import
from . import reflectutils
# This blacklist stinks. But there is a node inside sympy that causes the
# whole exploration to just hang unless you CTRL-C. This is pretty heavy
# handed...
# TODO(tarak):... |
9963021 | from django.db.models import Prefetch
from django.test import TestCase
from django.urls import reverse
from rest_framework import status, serializers
from rest_framework.permissions import BasePermission
from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer
from rest_framework.settings import api_sett... |
9963068 | class assetManagerPanel( nukescripts.PythonPanel ):
def __init__(self):
nukescripts.PythonPanel.__init__(self, 'Project Management Panel', 'assetpanel')
# Create all fields
self.prod = nuke.Enumeration_Knob('prod', 'Production Company', [])
self.prodNew = nuke.String_Knob('pro... |
9963121 | import os
import sys
# zentral path
BASE_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), "../../"))
sys.path.insert(0, BASE_DIR)
|
9963125 | class Ring(object):
def start(self, xpos, ypos):
self.x = xpos # x-coordinate
self.y = ypos # y-coordinate
self.diameter = 1 # Diameter of the ring
self.on = False # Turns the display on and off
self.on = True
def grow(self):
if self.on:
self.dia... |
9963135 | from errator import narrate, get_narration, set_narration_options
import timeit
import platform
def f1(borkfunc, catchfunc):
if borkfunc == 1:
raise Exception("bork1")
else:
try:
f2(borkfunc, catchfunc)
except Exception:
if catchfunc == 1:
_ = ge... |
9963160 | from causallearn.utils.KCI.Kernel import Kernel
class PolynomialKernel(Kernel):
def __init__(self, degree=2, const=1.0):
Kernel.__init__(self)
self.degree = degree
self.const = const
def kernel(self, X, Y=None):
"""
Computes the polynomial kernel k(x,y)=(c+<x,y>)^degre... |
9963224 | import torch
import torch.nn as nn
import torch.nn.functional as F
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, dropout, depth=1):
super(MLP, self).__init__()
modules = [nn.Dropout(dropout)]
last_dim = input_dim
for i in range(depth-1):
m... |
9963226 | from externals.moduleman.plugin import moduleman_plugin
import urllib
import base64 as mybase64
import re
import binascii
import random
import hashlib
import cgi
class pencoder_multiple:
text="internal multiple encoder"
def __init__(self, l):
self.l = l
def encode(self, string):
for i in reversed(self... |
9963228 | from azureml.api.schema.dataTypes import DataTypes
from azureml.api.schema.sampleDefinition import SampleDefinition
from azureml.api.realtime.services import generate_schema
from azureml.logging import get_azureml_logger
from azure.storage.blob import BlockBlobService, PublicAccess, ContentSettings
import numpy as n... |
9963268 | from __future__ import print_function
import argparse
import os
import random
import numpy as np
import torch
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from dataset.dataset import RIODatasetSceneGraph, collate_fn_vaegan_points
from model.VAE import VAE
from model.atlasnet import AE_At... |
9963280 | from matplotlib.collections import LineCollection
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import argparse
import os
import re
def plot(f_name, acc_names=None):
df = pd.read_csv(f_name)
if acc_names is None:
n_accs = max(map(int, filter(lambda i:i!='',
... |
9963295 | from omtk.modules import rigFaceAvarGrps
from omtk.modules import rigFaceAvar
from omtk.libs import libRigging
import pymel.core as pymel
from maya import cmds
class CtrlNose(rigFaceAvar.CtrlFaceMicro):
pass
class FaceNose(rigFaceAvarGrps.AvarGrpOnSurface):
"""
The Nose is composed of two zones. The uppe... |
9963332 | from sklearn_explain.tests.skl_datasets import skl_datasets_test as skltest
skltest.test_class_dataset_and_model("BinaryClass_500" , "GaussianNB_6")
|
9963365 | from magma import *
from magma.passes.clock import drive_undriven_other_clock_types_in_inst
from mantle import Mux
from .register import _RegisterName, Register
__all__ = ['DefinePIPO', 'PIPO']
def DefinePIPO(n, init=0, has_ce=False, has_reset=False):
"""
Generate Parallel-In, Parallel-Out shift register.
... |
9963368 | import threading
import sys
import importlib, traceback
EQPY_ABORT = "EQPY_ABORT"
try:
import queue as q
except ImportError:
# queue is Queue in python 2
import Queue as q
input_q = q.Queue()
output_q = q.Queue()
p1 = None
p2 = None
aborted = False
wait_info = None
class WaitInfo:
def __init__(sel... |
9963376 | from allennlp_models.lm.modules.seq2seq_encoders.bidirectional_lm_transformer import (
BidirectionalLanguageModelTransformer,
)
|
9963464 | import pytest
from unittest.mock import MagicMock, mock_open
from collections import namedtuple
@pytest.fixture()
def mock_object(monkeypatch):
def create_mock_object(object_path, **kwargs):
mo = MagicMock(**kwargs)
monkeypatch.setattr(object_path, mo)
return mo
return create_mock_obj... |
9963565 | from typing import Any, Dict, List, Optional
from pydantic import BaseModel, constr
from .mindmeld import DialogueState, Params
class InvokePayload(BaseModel):
signature: str
message: str
class SkillInvokeRequest(DialogueState):
challenge: constr(min_length=64, max_length=64) # type: ignore
# TODO:... |
9963602 | from openmdao.api import ImplicitComponent
import numpy as np
from scipy.interpolate import Akima1DInterpolator as Akima
""" Create tables for table lookup functions """
# Small engines polytripic efficiency values
Wc_SE = np.array([0, 0.205, 0.63, 1.0, 1.5, 2., 2.5, 3., 4., 5., 30., 200])
# TG... |
9963646 | from app.models.apply import ExtensionApply11Model, ExtensionApply12Model, GoingoutApplyModel, StayApplyModel
from app.models.point import PointHistoryModel
from tests.v2.views import TCBase
class TestApplyStatus(TCBase):
"""
신청 정보 확인을 테스트합니다.
"""
def __init__(self, *args, **kwargs):
super(T... |
9963679 | from PIL import Image
from os.path import getsize
from tkinter.filedialog import askopenfilename, asksaveasfilename
def compress():
file_path = askopenfilename(title="select image ")
img = Image.open(file_path)
print(f"Original size of image was : {getsize(file_path)} Bytes")
height, width = img.siz... |
9963684 | import abc
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
@dataclass
class NewsInterface:
title: str
description: str
url: str
source: Optional[str]
author: Optional[str]
thumbnail_url: Optional[str]
def __repr__(self):
return f'<NewsIn... |
9963687 | import os
import urllib
import torch
from torch.utils import model_zoo
class CheckpointIO(object):
def __init__(self, checkpoint_dir='./chkpts', **kwargs):
self.module_dict = kwargs
self.checkpoint_dir = checkpoint_dir
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpo... |
9963694 | from svregion import *
class TigraContig:
def __init__(self, name="", sequence=None):
if sequence is not None:
self.sequence = sequence
self.parse_name(name)
def parse_name(self, name):
name_fields = name.strip().split()
name_split = name_fields[0].split(".")
... |
9963741 | import pytest
from tests.conftest import BASE_URL
from trustar import IndicatorType, NumberedPage, Indicator, Tag
URL_ENDPOINT = BASE_URL + "/indicators"
URL_ENDPOINT_WHITELIST = BASE_URL + "/whitelist"
@pytest.fixture
def indicators(current_time_millis, milliseconds_in_a_day):
return [Indicator(value="1.5.8.7"... |
9963745 | for row in range(6):
for col in range(6):
if col==0 or col==5 or (row==col and (col>0 and col<5)):
print("*",end="")
else:
print(end=" ")
print()
|
9963764 | import pyaf.Bench.TS_datasets as tsds
import pyaf.Bench.YahooStocks as ys
tester7 = ys.cYahoo_Tester(tsds.load_yahoo_stock_prices("cac40") , "YAHOO_STOCKS");
#tester7.testAllSignals(12);
tester7.testSignals("ML.PA" , 12);
# tester7.run_multiprocessed(18);
|
9963785 | from bdutils import *
def bdassert(expr):
strpos = str(get_cur_script().pos)
set_stmt('''if true then
dim _v = {expr}
if ! _v then
throw new runtime_exception(\'\'\'Assertion failed! Position: {strpos}\'\'\')
end
end
'''.format(expr=expr,strpos=strpos)) |
9963787 | from pythonwarrior.units.base import UnitBase
class Golem(UnitBase):
def __init__(self):
super(Golem, self).__init__()
self.turn = None
self.max_health = None
def play_turn(self, turn):
if self.turn:
self.turn(turn)
@property
def character(self):
r... |
9963797 | from __future__ import print_function
from collections import defaultdict
from pcmdi_metrics.driver.pmp_parser import PMPParser
import copy
import collections
import datetime
import glob
import os
import sys
import pcmdi_metrics
import re
def AddParserArgument():
P = PMPParser() # Includes all default options
... |
9963798 | from Orange.base import Learner, Model
from orangecontrib.recommendation.utils import format_data
from abc import ABCMeta, abstractmethod
import numpy as np
__all__ = ["LearnerRecommendation", "ModelRecommendation"]
class ModelRecommendation(Model, metaclass=ABCMeta):
def __init__(self):
self.shape = (... |
9963849 | import oauthlib
from oauthlib.uri_validate import is_absolute_uri
from tests.unittest import TestCase
class UriValidateTest(TestCase):
def test_is_absolute_uri(self):
self.assertIsNotNone(is_absolute_uri('schema://example.com/path'))
self.assertIsNotNone(is_absolute_uri('https://example.com/pat... |
9963858 | from .geom import geom
from ..utils import is_date
class geom_text(geom):
"""
Same as geom_point but text instead of points
Parameters
----------
x:
x values for (x, y) coordinates
y:
y values for (x, y) coordinates
color:
color of points
alpha:
transpa... |
9963864 | from securityheaders.models import SecurityHeader
from securityheaders.models.annotations import *
@description('Deprecated header for a Content-Security-Policy.')
@headername('x-content-security-policy')
@headerref('http://www.w3.org/TR/CSP/')
class XContentSecurityPolicy(SecurityHeader):
directive = None
de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.