id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4868935 | import json
import os
from Qt import Qt, QtCore, QtGui, QtWidgets
import asset_browser.icons.icons
THUMB_SIZE = 55
ITEM_SIZE = 80
FONT_SIZE = 7
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
ICON_PATH = os.path.join(FILE_DIR, "icons")
class Thumb(QtWidgets.QLabel):
def __init__(self, part_id=None, *arg... |
4868948 | import numpy as np
import pandas as pd
def assert_dicts_equal(expected, actual):
assert(set(expected.keys()) == set(actual.keys()))
for key, expected_val in expected.iteritems():
if isinstance(expected_val, pd.DataFrame):
assert(np.all(actual[key].shape == expected_val.shape))
... |
4868964 | from __future__ import print_function
import argparse
import os
import sys
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from sklearn.linear_model impo... |
4868999 | from __future__ import absolute_import, division, print_function
import numpy as np
def flux_to_mag(flux, zeropoint_mag=0.0, from_unit=None):
if from_unit=='nMgy':
zeropoint_mag = 22.5
return zeropoint_mag - 2.5*np.log10(flux)
def mag_to_flux(mag, zeropoint_mag=0.0, to_unit=None):
if to_unit=='nMg... |
4869049 | import os
import yaml
import argparse
def str2bool(v):
if v.lower() == 'true':
return True
else:
return False
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--type', required=True, choices=["cls", "shitu"])
parser.add_argument('--batch_size', type=int, ... |
4869092 | from hypothesis import given
from hypothesis.strategies import integers
from pymonet.utils import curry
@given(integers())
def test_curry_1_argument(integer1):
@curry
def fn(arg1):
return arg1
assert fn(integer1) == fn(integer1)
@given(integers(), integers())
def test_curry_2_arguments(intege... |
4869129 | from src.Base import BaseClass
from utils.Utility import LOGGER,Log
import time
class Censys(BaseClass):
def __init__(self):
super().__init__()
self.URL="https://www.censys.io/api/v1/search/certificates"
self.API_KEY=self.get_credentials()["CENSYS_API_KEY"]
self.SECRET=self... |
4869132 | import os
from setuptools import setup
setup(name='maproxy',
version = "0.0.12",
author = "<NAME>",
author_email = "<EMAIL>",
description = ("My first attempt to create a simple and awesome "
"TCP proxy using Tornado"),
# For now, let's just build a module, not a package... |
4869142 | import os
from ..capabilities import parse_capabilities, wms_capabilities_url
from mapproxy.test.http import assert_query_eq
def test_wms_capabilities_url():
assert_query_eq(wms_capabilities_url('http://foo/'),
'http://foo/?REQUEST=GetCapabilities&SERVICE=WMS&VERSION=1.1.1')
assert_query_eq(wms_capab... |
4869167 | class AbstractLogger:
"""Abstract logger"""
def log(self, *args, **kwargs) -> None:
raise NotImplementedError
def log_dict(self, *args, **kwargs) -> None:
raise NotImplementedError
def dispose(self) -> None:
raise NotImplementedError
|
4869170 | import streamlit as st
try:
from keywords import *
except:
from .keywords import *
def file_upload_from_lines(lines):
"""Parses the line into a dictionary of values of interest.
:param lines: list of lines
:type lines: list
:return: Returns a dict of the parsed values for the file upload.
... |
4869189 | from commercetools.platform import models
def test_product_discount_get_by_id(old_client):
product_discount = old_client.product_discounts.create(
models.ProductDiscountDraft(
name=models.LocalizedString(nl="test-discount"),
predicate="",
value=models.ProductDiscountVal... |
4869192 | import requests
from pyOutlook.internal.utils import check_response
__all__ = ['Folder']
class Folder(object):
"""An object representing a Folder in the OutlookAccount provided.
Attributes:
account: The :class:`OutlookAccount <pyOutlook.core.main.OutlookAccount>` this folder should be associated wi... |
4869201 | import math
t = int(input())
for i in range(1,t+1):
a,b = map(int, input().strip().split())
s = []
if (a!=b):
for x in range(a,a+2):
first = math.ceil((b-x)/2)
part = math.ceil((x-a)/2)
sum = (first+part)
s.append(sum)
print(max(s))
else:
... |
4869214 | import argparse
import logging
from functools import partial
import tensorflow as tf
from segmentation import dataset
from segmentation.model import build_model
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
tf.logging.set_verbosity(tf.logging.INFO)
def train_data_generat... |
4869227 | import mock
import numpy as np
import tempfile
import pytest
import struct
from nengo_spinnaker.operators.value_source import (
SystemRegion, get_transform_keys)
def test_get_transform_keys():
"""Check that the keys required to transmit data are correctly extracted.
"""
# Create a transform with an e... |
4869231 | from sympy import Matrix, S, latex
from sympy.abc import x, y, z
from lmi_sdp.lm import lm_sym_expanded
from lmi_sdp.lmi import ShapeError, NonSymmetricMatrixError, LMI_PSD, \
LMI_NSD, LMI_PD, LMI_ND, init_lmi_latex_printing
def test_LMI_PSD():
m = Matrix([[x, y], [y, z+1]])
lmi = LMI_PSD(m)
assert lm... |
4869239 | import sark
from oregami.reg_utils import logger, is_func, UsageBits
from oregami.reg_insn import RegInstruction
from oregami.reg_utils import AskStr, conf, RegName
# TODOS:
# - if blocks may be consecutive, do only one rename - Done.
# - Add functionality to define as type for all references - Done.
# - If register ... |
4869367 | def test_multicamera_invalid_input_single_detectionresult(checkerboard_frames):
import pytest
import zivid.calibration
frame = checkerboard_frames[0]
detection_result = zivid.calibration.detect_feature_points(frame.point_cloud())
with pytest.raises(TypeError):
# Will fail because a list of... |
4869395 | import math
import shutil
import matplotlib as mpl
from annogesiclib.gff3 import Gff3Parser
from annogesiclib.helper import Helper
import numpy as np
mpl.use('Agg')
import matplotlib.pyplot as plt
plt.style.use('ggplot')
def plot(utr, utr_pri, utr_sec, filename, source, utr_type, base_5utr):
'''plot the distribut... |
4869406 | from setuptools import setup
from flask_skeleton import __version__
with open('README.md', 'r') as f:
readme = f.read()
setup(
name='flask-skeleton',
author='enwawerueli',
author_email='<EMAIL>',
version=__version__,
description='Quick start a flask app',
long_description=readme,
long... |
4869414 | from TronGisPy.Raster import Raster
from TronGisPy.Normalizer import Normalizer
from TronGisPy.SplittedImage import SplittedImage
from TronGisPy.io import remove_shp, create_temp_dir_when_not_exists
from TronGisPy.io import get_raster_info, get_raster_data, get_raster_extent, update_raster_info
from TronGisPy.io impor... |
4869461 | import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import torch
from torch.utils.data import DataLoader
from locs.utils.flags import build_flags
import locs.models.model_builder as model_builder
from locs.datasets.small_synth_d... |
4869480 | GenericMapping = {
'properties': {
'id': {'type': 'keyword'},
'event_id': {'type': 'keyword'},
'type': {'type': 'keyword'},
'name': {'type': 'text'},
'keyword': {
'type': 'keyword',
'normalizer': 'lowercase'
},
'body': {
'ty... |
4869492 | from typing import List
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
sum = 0
for i in nums:
sum += i
mem = []
for i in range(len(nums)):
mem.append([0] * len(nums))
return 2 * self.find_max(0, len(nums) - 1, nums, mem) >= sum... |
4869515 | from pycroft.lib.user import move, move_out, move_in
from pycroft.model import session
from pycroft.model.user import RoomHistoryEntry
from tests import FactoryDataTestBase, ConfigFactory, UserFactory
from tests.factories import AddressFactory, RoomFactory
class UserRoomHistoryTestCase(FactoryDataTestBase):
def c... |
4869539 | import numpy as np
from sklearn.utils.validation import check_random_state
from rampwf.utils.importing import import_module_from_source
from gym.envs.mujoco import InvertedPendulumEnv
reward_module = import_module_from_source(
'reward_function.py', 'reward_function')
reward_func = reward_module.reward_func
clas... |
4869573 | import argparse
import os
import random
from tensorboardX import SummaryWriter
import torch
from config import TrainConfig as C
from dataset.MSVD import MSVD
from eval import evaluate
from models.decoder import Decoder
from models.local_reconstructor import LocalReconstructor
from models.global_reconstructor import G... |
4869593 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
import tensorflow as tf
import graphs
import itertools
import utils
from hook import EvaluateHook, LoggerHook
import random
import os
from adversarial_attacking import generate_ne... |
4869597 | from centroidtracker.centroidtracker import CentroidTracker
from imutils.video import VideoStream
import numpy as np
import argparse
import imutils
import time
import cv2 as cv
import argparse
import os
def main():
parser = argparse.ArgumentParser(description='Track objects')
parser.add_argument('--sourceFile', re... |
4869601 | import os
from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
class AptGet(Backend):
"""
Gets update count for Debian based distributions.
This mimics the Arch Linux `checkupdates` script
but with apt-get and written in python.
"""
@property
def ... |
4869688 | import typer
from .crypto import app as crypto_app
from .nlp import app as nlp_app
from .project import app as project_app
from .remote import remote as remote_app
from .skill import app as skill_app
app = typer.Typer()
app.add_typer(skill_app, name="skills")
app.add_typer(crypto_app, name="crypto")
app.add_typer(nl... |
4869699 | from enum import Enum
class Frequency(Enum):
"""Represents the frequency options for the
`PortfolioAnalysis` service.
### Usage
----
>>> from ibc.enums import Frequency
>>> Frequency.Daily.value
"""
Daily = 'D'
Monthly = 'M'
Quarterly = 'Q'
class MarketDataFields(En... |
4869724 | from collections import namedtuple
class gfycat(object):
"""
A very simple module that allows you to
1. upload a gif to gfycat from a remote location
2. upload a gif to gfycat from local machine
3. query the upload url
4. query an existing gfycat link
5. query if a link is already exist
... |
4869753 | import matplotlib
matplotlib.use('TKAgg')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import animation
import random
import math
import pickle
from args import FLAGS
fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-25, 12... |
4869757 | from zen.util.benchmark import Benchmark, main
import networkx as nx
import zen as zn
import igraph as ig
import tempfile
import os
class NonRandomGraphBenchmark(Benchmark):
def __init__(self):
Benchmark.__init__(self,'Loading Edgelist Data')
self.NUM_NODES = 1000
def setup(self):
# make a temporary... |
4869765 | import torch
from ...ops.iou3d_nms import iou3d_nms_utils
def class_agnostic_nms(box_scores, box_preds, nms_config, score_thresh=None):
src_box_scores = box_scores
if score_thresh is not None:
scores_mask = (box_scores >= score_thresh)
box_scores = box_scores[scores_mask]
box_preds = b... |
4869787 | import configparser
import aioredis
from aiogram import Bot, Dispatcher, executor, types
import bot_common
config = configparser.ConfigParser()
config.read('bot.ini')
TOKEN = config["bot"]["tg_token"]
issues_link = "https://github.com/AvaCity/avacity-2.0/issues"
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
async def ... |
4869818 | import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import sys
engine = pyttsx3.init('sapi5')
voice = engine.getProperty('voices')
#print(voice[1].id)
engine.setProperty('voice',voice[1].id )
def speak(audio):
engine.say(audio)
engine.ru... |
4869850 | import logging
from timebudget import timebudget
from jyotisha.panchaanga.temporal import Anga, AngaType
from jyotisha.panchaanga.temporal.festival import FestivalInstance
from jyotisha.panchaanga.temporal.festival.applier import FestivalAssigner
from jyotisha.panchaanga.temporal.festival.rules import RulesRepo
cla... |
4869859 | import LibCall
from .module import Module
from .. import functional as F
class _NormBase(Module):
def __init__(
self,
num_features,
eps=1e-5,
momentum=0.1,
affine=True,
track_running_stats=True,
):
super(_NormBase, self).__init__()
self.num_featu... |
4869879 | import argparse
import os.path
import re
# Argument parser initialization
parser = argparse.ArgumentParser();
parser.add_argument("-w1", "--word1",
help="First word of wordpair to add.", type=str)
parser.add_argument("-w2", "--word2",
help="Second word of wordpair to ad... |
4869946 | import sys
import math
import numpy as np
from scipy.spatial import cKDTree
from psutil import virtual_memory
from laserchicken import utils, kd_tree
from laserchicken.volume_specification import Sphere, InfiniteCylinder, Cell, Cube
from laserchicken.keys import point
def frange(x_value, y_value, jump):
while x_... |
4869960 | from typing import Optional, TYPE_CHECKING
import numpy as np
from .helper import _uri_to_blob, _to_datauri, _is_datauri
if TYPE_CHECKING:
from ...typing import T
class ConvertMixin:
"""Provide helper functions for :class:`Document` to support conversion between :attr:`.tensor`, :attr:`.text`
and :attr... |
4869965 | import asyncio
import logging
import contextlib
async def coro1():
while True:
for i in range(100000):
await asyncio.sleep(0.1)
print('coro1')
async def coro2():
for i in range(25):
await asyncio.sleep(0.5)
print(i)
logging.getLogger('asyncio').setLevel('CRITICAL')... |
4869976 | from typing import Callable, Optional
import pytest
from botx import Collector, Depends, Message
def build_botx_handler(name: Optional[str] = None) -> Callable[[], None]:
def factory(_message: Message):
"""Just do nothing."""
factory.__name__ = name or factory.__name__
return factory
@pytest.... |
4869985 | import albumentations as A
import kornia.augmentation as K
################################################ albumentations_list ###############################
def albumentations_list(MAGN: int = 4):
"""
Returns standard list of albumentations transforms, each of mangitude `MAGN`.
Args:
MAGN ... |
4870015 | import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
class UnoCpi(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path='C:\TESTI... |
4870044 | from polyphony import testbench
def list29(p, xs, ys):
if p:
d = xs
else:
d = ys
return d[0]
@testbench
def test():
assert 1 == list29(True, [1], [2])
#assert 2 == list29(False, [1], [2])
test()
|
4870050 | from substance import (Command, Engine)
from substance.constants import Syncher
class Sync(Command):
def getShellOptions(self, optparser):
optparser.add_option(
"-u", "--up", dest="up", help="Synchronize UP to the engine only.", default=False, action="store_true")
optparser.add_option(... |
4870091 | class Solution:
def intervalIntersection(self, A: 'List[Interval]', B: 'List[Interval]') -> 'List[Interval]':
ret = []
i, j, m, n = 0, 0, len(A), len(B)
while i < m and j < n:
if A[i].start > B[j].end:
j += 1
elif A[i].end < B[j].start:
... |
4870164 | import boto3
def handler(event, context):
fileUUID = event.get("fileUUID")
transcribe = boto3.client("transcribe")
response = transcribe.get_transcription_job(TranscriptionJobName=fileUUID)
status = response.get("TranscriptionJob").get("TranscriptionJobStatus")
print("Status for job " + fileUUID... |
4870166 | from __future__ import print_function
from __future__ import division
import sys, os
import numpy as np
"""
Illuminance Module:
- Module containing algorithmic approaches that quantify based on amount of "light hitting the surface of a target object".
"""
currentMillis = lambda: int(round(time.time() * 1000)... |
4870211 | from .base import REGISTERED_ENVS, MujocoEnv
ALL_ENVS = REGISTERED_ENVS.keys()
from .sawyer_lift_vj import SawyerLift_vj |
4870212 | import gl
gl.resetdefaults()
gl.meshload('lh.pial')
gl.overlayload('boggle.lh.annot')
#make contour at border of atlas
gl.contour(0)
#reduce atlas salience:
gl.atlassaturationalpha(0.2, 0.5)
gl.overlayload('motor_4t95vol.nii.gz')
gl.overlayminmax(gl.overlaycount(),-2,-3)
#hide statistical map:
gl.overlayopac... |
4870218 | from holiday import *
import utils
import report_card
import datetime
import pytz
import csv
import cPickle as pickle
import datetime
import ephem # run `pip install pyephem`
import os
import collections
import string
import time
import cPickle as pickle
import numpy as np
import pytz
import datetim... |
4870285 | import array
import cv2
# import sensor_msgs.msg
import math
import copy
import numpy
def mkmat(rows, cols, L):
mat = numpy.matrix(L, dtype='float64')
mat.resize((rows,cols))
return mat
class PinholeCameraModel:
"""
A pinhole camera is an idealized monocular camera.
"""
def __init__(sel... |
4870296 | import pytest
from mlflow.utils import gorilla
class Delegator:
def __init__(self, delegated_fn):
self.delegated_fn = delegated_fn
def __get__(self, instance, owner):
return self.delegated_fn
def delegate(delegated_fn):
return lambda fn: Delegator(delegated_fn)
def gen_class_A_B():
... |
4870337 | import os
from pydantic import BaseModel
# Needed because pydantic gets in the way of generating good docs
_generating_documentation = bool(os.environ.get("GENERATING_DOCUMENTATION"))
if _generating_documentation:
BaseModel = object
class Model(BaseModel):
class Config:
extra = "forbid"
|
4870354 | import pytest
import pendulum
import base64
import json
import raymon
from raymon.auth import load_credentials_file
from raymon.auth.m2m import (
save_m2m_config,
verify_m2m,
load_m2m_credentials,
)
from raymon.auth.user import (
save_user_config,
load_user_credentials,
verify_user,
token_... |
4870355 | import ThreeD60
import visualization
from torch.utils.data import DataLoader
if __name__ == "__main__":
datasets = ThreeD60.get_datasets(".//splits//eccv18//caffe_train_allmods_abs.txt", \
datasets=["suncg", "m3d", "s2d3d"],
placements=[ThreeD60.Placements.CENTER, ThreeD60.Placements.RIGHT... |
4870372 | from transmute_core.function.signature import Argument, NoDefault
from transmute_core.http_parameters import get_swagger_parameters
from transmute_core import default_context
from transmute_core.http_parameters import Parameters, Param, ParamSet
def test_swagger_parameters():
parameters = Parameters(
quer... |
4870377 | from multiprocessing.connection import Listener
from pykd import *
import os
import re
import string
import sys
import threading
import time
poll_time = .25
conn = None
base = module.begin(getModulesList()[0])
bps = { }
ip = None
def start(pipe):
global conn
listener = Listener('\\\\.\\pipe\\' + pipe, backlo... |
4870401 | from six import iteritems
from pyjo.exceptions import FieldTypeError
from pyjo.fields.field import Field
class MapField(Field):
def __init__(self, inner_field, **kwargs):
"""
:type inner_field: T
:rtype: dict[str, T]
"""
super(MapField, self).__init__(type=dict, **kwargs)
... |
4870450 | from functools import reduce
res = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
assert res == 1 + 2 + 3 + 4 + 5
res = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5], 10)
assert res == 10 + 1 + 2 + 3 + 4 + 5
|
4870514 | import RPi.GPIO as GPIO
from time import sleep
from ISStreamer.Streamer import Streamer
# Tell the Pi we're going to use it's numbering system
GPIO.setmode(GPIO.BCM)
# Pin that D1 is connected to
PIN=23
# Specify our pin as input
GPIO.setup(PIN,GPIO.IN)
# Initial State bucket name (displayed)
BUCKET_NAME = ":wave: M... |
4870577 | import csv
import optparse
import os
import textwrap
import sys
from .. import BadReportStatus
from .. import DuplicateReport
from .. import NoSuchReport
from .. import create_report
from .. import delete_report
from .. import initialize_gcloud
from .. import update_report
class InvalidCommandLine(ValueError):
... |
4870582 | import requests
import zipfile
import os
from tqdm import tqdm
import argparse
from SEVN_gym.data import DATA_PATH
ZENODO_URL = 'https://zenodo.org/record/3526490/files/'
def download_file(url, filename):
"""
Helper method handling downloading large files from `url` to `filename`.
"""
chunkSize = 10... |
4870583 | class Node(object):
def __init__(self, v, l=None, r=None):
self.value = v
self.left = l
self.right = r
def lca(r, a, b):
"""
lca returns the least common ancestor of a and b in the tree rooted at r.
"""
pa = path_to(r, a)
pb = path_to(r, b)
if pa is None or pb is No... |
4870585 | global leftController
global rightController
if starting:
leftController = OSVR.leftController()
rightController = OSVR.rightController()
hydra[0].enabled = True
hydra[0].isDocked = False
hydra[0].side = 'L'
hydra[1].enabled = True
hydra[1].isDocked = False
hydra[1].side = 'R'
def update():
global leftCon... |
4870597 | from restfulpy.orm.metadata import FieldInfo
def test_to_json_fieldinfo():
age = FieldInfo(
type_=(str, 400),
pattern=('\\d+', 400),
max_length=(2, 400),
min_length=(1, 400),
minimum=(1, 400),
maximum=(99, 400),
readonly=(True, 400),
protected=(True,... |
4870627 | from django.apps import AppConfig
class AnnotationsConfig(AppConfig):
name = 'oldp.apps.annotations'
|
4870644 | from brain_img_processor import BrainData, isolate_brain, segment, denoise, normalize_255, equalize
import numpy as np
import matplotlib.pyplot as plt #library to view images
from scipy import ndimage as ndi
def get_slices(brain_data):
brain = brain_data
hide_image_num = -1000
#retrieve all top down im... |
4870694 | from typing import Dict, List, Any
import json
import logging
from allennlp.data import Dataset
from overrides import overrides
from allennlp.common import Params
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.fields import ... |
4870729 | from flask import Flask, request, jsonify
from pymongo import MongoClient
app = Flask(__name__)
def get_db():
client = MongoClient('mongodb://db:27017/', connect=False)
return client.application_database
@app.route("/ping")
def ping():
return "pong"
# to check DB connection:
@app.route("/users", meth... |
4870762 | import synapse.exc as s_exc
import synapse.common as s_common
import synapse.tests.utils as s_test
class StormWhoisTest(s_test.SynTest):
async def test_storm_whois_guid(self):
async with self.getTestCore() as core:
# IP netblock record
props = {
'net4': '10.0.0.0/2... |
4870764 | from django.db import models
from typing import List, Optional
import inspect
import strawberry
from .. import hooks, utils
from ...resolvers import django_resolver
from .arguments import resolve_type_args
def get_object_resolver(*args, types=None):
model, object_type = resolve_type_args(args, types=types, single... |
4870780 | class CuboidParams():
def __init__(self):
# TODO: put all the relevant parameters at this single place here!
# PARAMS FOR THE APROACH PRIMITIVE
self.approach_grasp_xy = [0.1, 0.1, 0.09, 0.036195386201143265]
self.approach_grasp_h = [0.1, 0.0, 0.0, 0.0]
self.approach_duration... |
4870782 | from pylearn2.datasets.preprocessing import ZCA
from pylearn2.utils import serial
from black_box_dataset import BlackBoxDataset
extra = BlackBoxDataset('extra')
zca = ZCA(filter_bias=.1)
zca.fit(extra.X)
serial.save('zca.pkl', zca)
|
4870790 | import torch
from nequip.data import AtomicDataDict
from nequip.nn.embedding import OneHotAtomEncoding
from nequip.nn import SequentialGraphNetwork, SaveForOutput, AtomwiseLinear
def test_basic():
sgn = SequentialGraphNetwork.from_parameters(
shared_params={"num_types": 4},
layers={
"... |
4870797 | from tool.runners.python import SubmissionPy
class WenceslasSubmission(SubmissionPy):
def run(self, s):
# :param s: input in string format
# :return: solution flag
# Your code goes here
serial_numbers = s.splitlines()
for id, sn1 in enumerate(serial_numbers):
... |
4870901 | import os
filepath = os.path.dirname(__file__)
impeller = os.path.join(filepath, 'impeller.igs')
sample = os.path.join(filepath, 'sample.igs')
|
4870943 | import pytest
from py_algorithms.lists import new_singly_linked_node
from py_algorithms.lists import Node
from py_algorithms.lists.merge_two_sorted import MergeTwoSorted
@pytest.fixture
def set_nodes(xs: Node, upto: int):
i = 1
while i < upto:
xs.next = new_singly_linked_node(xs.data + 1)
xs ... |
4870976 | from unittest import mock
from dassana.common.aws_client import LambdaTestContext
import pytest
@pytest.fixture()
def example():
return
@pytest.fixture()
def ec2_instance_without_role(ec2_client, networking):
sg_resp = ec2_client.create_security_group(GroupName='foobar', VpcId=networking.get('vpc').get('id... |
4870999 | from .base import BaseModel
from .attachments import Photo
from enum import Enum, IntEnum
import typing
# https://vk.com/dev/objects/app
class ApplicationType(Enum):
app = "social app"
game = "game"
site = "site"
standalone = "standalone"
class LeaderBoardType(IntEnum):
not_supported = 0
... |
4871012 | from PuppeteerLibrary.ikeywords.base_async_keywords import BaseAsyncKeywords
from abc import ABC, abstractmethod
class iAlertAsync(BaseAsyncKeywords, ABC):
@abstractmethod
async def handle_alert(self, action, prompt_text=''):
pass
|
4871061 | import sys
import os
from argparse import ArgumentParser
import glob
import shutil
import json
import logging
import copy
import numpy as np
from sa_coco_converters.converters import Converter
ALLOWED_TASK_TYPES = [
'panoptic_segmentation', 'instance_segmentation', 'keypoint_detection',
'object_detection'
]
A... |
4871086 | from pseudo.middlewares.middleware import Middleware
from pseudo.pseudo_tree import Node
class AugAssignmentMiddleware(Middleware):
'''
changes `%<x> = %<x> op %<value>` to `%<x> += %<value>` nodes
`
'''
@classmethod
def process(cls, tree):
return cls().transform(tree)
def transf... |
4871105 | import cv2 as cv2
import pytesseract
import os,json
import numpy as np
from PIL import Image
import sys
from sys import argv
import couchdb
# couchdb_address = 'http://openwhisk:openwhisk@10.2.64.8:5984/'
# db = couchdb.Server(couchdb_address)
def get_string(img_path):
# Read image with opencv
img = cv2.imrea... |
4871123 | import pytorch_lightning as pl
from pytorch_lightning.metrics.functional.classification import iou
from torch.utils.tensorboard import SummaryWriter
import torch
from data_utils.data_map import labels, content, color_map
from data_utils.ioueval import iouEval
from data_utils.collations import *
from numpy import inf, p... |
4871162 | from dataclasses import dataclass
from datetime import datetime
from math import isinf
from typing import Dict, List
from slack_sdk import WebClient
from pytz import UTC
from hunter.data_selector import DataSelector
from hunter.series import ChangePointGroup, AnalyzedSeries
@dataclass
class NotificationError(Except... |
4871164 | class Book(object):
def __init__(self, title):
self._title = title
self._authors = []
self._identifier = []
self._publication_year = 0
self._publisher = "None"
def add_identifier(self, id):
self._identifier.append(id)
def add_author(self, author):
self._authors.append(a... |
4871171 | import hashlib
f = open("signtest-FFFFFFFF.bin", "rb")
f_out = open("signtest-gen.bin", "wb")
f_raw = open("raw_resources_a_mod.image", "rb")
h = hashlib.sha256()
h.update(f_raw.read())
f_raw.close()
f_out.write(f.read(0xc40))
f_out.write(h.digest()) # modified partition hash (A)
f.seek(0xC60)
f_out.write(f.read()) ... |
4871183 | from utils.header import MagicField, Field
from load_command import LoadCommandCommand, LoadCommandHeader
class DysymtabCommand(LoadCommandHeader):
ENDIAN = None
FIELDS = (
MagicField('cmd', 'I', {LoadCommandCommand.COMMANDS['LC_DYSYMTAB']: 'LC_DYSYMTAB'}),
Field('cmdsize', 'I'),
Field... |
4871191 | import pyttsx3 # pip install pyttsx3
import datetime
import speech_recognition as sr # pip install SpeechRecognition
import wikipedia # pip install wikipedia
from googlesearch import search # pip install google
import webbrowser
import os
import ctypes
import random
from bs4 import BeautifulSoup as soup
from urllib... |
4871192 | import re
import requests
from datetime import datetime
print('''
اداة بسيطه لاستخراج ( sessionid )
بدون برامج ( الرجاء عدم وضع التحقق في حسابك )
''')
link = 'https://www.instagram.com/accounts/login/'
login_url = 'https://www.instagram.com/accounts/login/ajax/'
time = int(datetime.now().timestamp())
user = inpu... |
4871234 | FIXEXP = True # Flag to fix underexposition
MINFACE = 8 # Minimum face size ratio; too low and we get false positives
INCREMENT = 0.06
GAMMA_THRES = 0.001
GAMMA = 0.90
FACE_RATIO = 6 # Face / padding ratio
QUESTION_OVERWRITE = "Overwrite image files?"
# File types supported by OpenCV
CV2_FILETYPES = [
".bmp",
... |
4871237 | import torch
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
class ModelTrainer:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@staticmethod
def train(model, criterion, optimizer, trainloader, epochs=5):
criterion = criterion.to(Model... |
4871316 | import pytest
from zmon_worker_monitor.zmon_worker.tasks.main import jsonpath_flat_filter
@pytest.fixture(params=[
(
{
'obj': {'result': {'status': 'SUCCESS', 'count': 10}},
'path': '*.status'
},
{'result.status': 'SUCCESS'}
),
(
{
'obj'... |
4871347 | class MyClass:
"""
MyClass Description
"""
x = 1
class MyClass1(Parent1):
"""
MyClass1 Description
Inheritance
-----------
Parent1: Parent1 Description
"""
y = 1
class MyClass2(Parent1, Parent2):
"""
MyClass... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.