id
stringlengths
3
8
content
stringlengths
100
981k
3203576
import os import pandas as pd if __name__ == '__main__': org_path = os.path.join('../../databox/select_50k', 'org_format_data') id = [] dataset_mark = [] rxn_smiles = [] for dataset in ['train', 'val', 'test']: df = pd.read_csv(os.path.join(org_path, '{}.csv'.format(dataset))) id ...
3203606
import json from copy import deepcopy import kafka from mindsdb.integrations.base import StreamIntegration import mindsdb.interfaces.storage.db as db from mindsdb_streams import KafkaStream, StreamController, StreamLearningController class KafkaConnectionChecker: def __init__(self, **params): self.conne...
3203637
from ctypes import * from ctype_primitive import * class CtypePrimitiveArrayReader: def __init__(self, binary, ctype, array_size): if ctype == CtypePrimtiveType.uint8: size = 1 elif ctype == CtypePrimtiveType.uint16: size = 2 elif ctype == CtypePrimtiveType.uint32: ...
3203653
import ast from tests.bdd.steps.common import when_or_given @when_or_given("we set {name} {attr} to {other_name} {other_attr}") def step_impl(context, name, attr, other_name, other_attr): set_to = getattr(context.entities[other_name], other_attr) setattr(context.entities[name], attr, set_to) @when_or_given(...
3203668
import os.path import mapnik symbolizer = mapnik.PolygonSymbolizer(mapnik.Color("darkgreen")) rule = mapnik.Rule() rule.symbols.append(symbolizer) style = mapnik.Style() style.rules.append(rule) layer = mapnik.Layer("mapLayer") layer.datasource = mapnik.Shapefile(file="TM_WORLD_BORDERS-0.3.shp") layer.styles.append...
3203676
import os import collections import itertools from . import helpers __all__ = ('Display',) class Graphic: _Visual = collections.namedtuple('Visual', 'dirty ready clean') __slots__ = ('_io', '_cursor', '_visuals', '_origin', '_width') def __init__(self, io, cursor): self._io = io sel...
3203683
import argparse from graph4nlp.pytorch.modules.config import get_basic_args from graph4nlp.pytorch.modules.utils.config_utils import get_yaml_config, update_values def get_args(): parser = argparse.ArgumentParser() parser.add_argument( "--dataset_yaml", type=str, default="examples/pyt...
3203720
import math import torch import torch.nn as nn # from https://pytorch.org/tutorials/beginner/transformer_tutorial.html class TrigonometricPositionalEncoding(nn.Module): """ This trigonometric positional embedding was taken from: Title: Sequence-to-Sequence Modeling with nn.Transformer and TorchTex...
3203788
import moderngl.experimental as mgl import gltraces ctx = mgl.create_context(standalone=True, debug=True) mglprocs = mgl.glprocs(ctx) gltraces.glprocs[:] = mglprocs mglprocs[:] = gltraces.gltraces prog = ctx.program( vertex_shader=''' #version 130 in vec2 in_vert; out vec2 v_vert; ...
3203795
import shap from stratx.ice import friedman_partial_dependence from stratx import plot_stratpd from articles.pd.support import synthetic_interaction_data import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.patches as mpatches from sklearn.ensemble import RandomForestRegressor np.r...
3203823
import atexit from math import atan2, degrees, sqrt from os import path from threading import Event, Thread from time import sleep, strftime, time from warnings import catch_warnings, filterwarnings import numpy as np # Enables "add_subplot(projection='3d')" from mpl_toolkits import mplot3d # noqa: F401, lgtm[py/unu...
3203832
import tensorflow as tf from tensorflow.contrib import slim from tensorflow import keras FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_integer('image_height', 28, 'the height of image') tf.app.flags.DEFINE_integer('image_width', 28, 'the width of image') tf.app.flags.DEFINE_integer('batch_size', 128, 'Number of image...
3203887
class Operation(object): # no doc @staticmethod def AddToPourUnit(inputPour,objectsToBeAdded): """ AddToPourUnit(inputPour: PourObject,objectsToBeAdded: List[ModelObject]) -> bool """ pass @staticmethod def CreateBasePoint(basePoint): """ CreateBasePoint(basePoint: BasePoint) -> bool """ pass @s...
3203900
import sys, warnings warnings.filterwarnings("ignore") from random import shuffle, sample import pickle as pk import gc import numpy as np import pandas as pd import scipy.io from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Reshape from keras.layers.recurrent import LSTM fr...
3203918
class Lock: """ synchronous lock that does not block""" def __init__(self): self._locked = False def acquire(self): if self._locked: return False else: self._locked = True return True def locked(self): return self._locked def re...
3203937
import threading import time from math import pi, sqrt from timer import Timer from pid import PID class MotionController: def __init__(self, odometer, motors, timeStep = .02): self.timeStep = timeStep self.odometer = odometer self.odometer.timeStep = self.timeStep self.motors = m...
3203980
import numpy as np from chesscog.core.registry import Registry def test_register_function_using_decorator(): registry = Registry() @registry.register def my_func(): pass assert "my_func" in registry assert registry["my_func"] == my_func def test_register_class_using_decorator(): r...
3203990
from django.dispatch import receiver from baserow.core.trash.signals import permanently_deleted from baserow_premium.row_comments.models import RowComment @receiver(permanently_deleted, sender="row", dispatch_uid="row_comment_cleanup") def permanently_deleted(sender, **kwargs): table_id = kwargs["parent_id"] ...
3204012
from __future__ import print_function import os import cv2 import json import lmdb import numpy as np from matplotlib import pyplot class USCISI_CMD_API( object ) : """ Simple API for reading the USCISI CMD dataset This API simply loads and parses CMD samples from LMDB # Example: ```python ...
3204020
import torch.nn.functional as F from util.util import compute_tensor_iu def get_new_iou_hook(values, size): return 'iou/new_iou_%s'%size, values['iou/new_i_%s'%size]/values['iou/new_u_%s'%size] def get_orig_iou_hook(values): return 'iou/orig_iou', values['iou/orig_i']/values['iou/orig_u'] def get_iou_gain(v...
3204057
class Calculadora(object): """docstring for Calculadora""" memoria = 10 def set_memoria(self, memoria): self.memoria = memoria def suma(self,a, b): return a + b def resta(self, a, b): return a - b def multiplicacion(self, a, b): return a * b def division(...
3204118
import numpy as np from math import factorial, sqrt, cos, sin fact = lambda x: factorial(int(x)) def choose(n, k): return fact(n)/fact(k)/fact(n-k) def dmat_entry(j,m_,m,beta): #real valued. implemented according to wikipedia partA = sqrt(fact(j+m_)*fact(j-m_)*fact(j+m)*fact(j-m)) partB = 0. for s ...
3204125
from sqlalchemy import Column, Float, String, Integer, ForeignKey, create_engine, inspect from sqlalchemy.engine import Engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from utils.constants import WEBTEXT_DB Base = declarative_base() Session = sessio...
3204155
from collections import defaultdict from copy import deepcopy from enum import Enum from pybbn.graph.edge import JtEdge from pybbn.graph.graph import Ug from pybbn.graph.node import SepSet, Clique, BbnNode from pybbn.graph.potential import Potential, PotentialEntry, PotentialUtil from pybbn.graph.variable import Varia...
3204162
import csv import yaml OUTPUT_COLUMNS = [ 'type', 'name', 'url', 'thomasID', 'jurisdiction', ] def load_committees(kind): if kind not in ['current', 'historical']: raise Exception('Committee type must be either current or historical') inpath = 'data/congress-legislators/committe...
3204210
import os import sys import enum import textwrap from cryptography.fernet import Fernet import environ from environ._environ_config import _env_to_bool def split_by_comma(value): return tuple(e.strip() for e in value.split(",")) @environ.config(prefix="") class NoeConfig: debug = environ.bool_var( d...
3204243
import argparse import copy import glob import json import os from .core import GTAB dir_path = os.path.dirname(os.path.abspath(__file__)) # --- UTILITY METHODS --- class GroupedAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): group, dest = self.dest.split('.'...
3204276
CUTTER = 1096005 sm.setSpeakerID(CUTTER) if sm.sendAskAccept("You're back! Great. I got the Ignition Device all hooked up, so we can get back to civilization. Nothing left to do here, right? Let's roll!"): sm.startQuest(parentID) sm.warp(912060200, 0) else: sm.sendNext("You're not done here? What could you...
3204295
from .generic_type import GenericType class ActivityType(GenericType): @property def _configuration_keys(self): return [ "defaultTaskHeartbeatTimeout", "defaultTaskScheduleToCloseTimeout", "defaultTaskScheduleToStartTimeout", "defaultTaskStartToCloseTime...
3204327
from cadCAD.configuration import Experiment from cadCAD.configuration.utils import config_sim from .state_variables import initial_state from .partial_state_update_block import partial_state_update_block from .sys_params import params sim_config = config_sim ( { 'N': 1, # number of monte carlo runs ...
3204331
import timeboard as tb import datetime import pytest import pandas as pd class TestVersion(object): def test_version(self): version = tb.read_from('VERSION.txt') assert version == tb.__version__ class TestTBConstructor(object): def test_tb_constructor_trivial(self): clnd = tb.Timeboa...
3204333
import pygame class Controller: def __init__(self, number): self.number = number self.joystick = None if number <= pygame.joystick.get_count()-1: self.joystick = pygame.joystick.Joystick(number) self.joystick.init() self.name = self.joystick.get_name() ...
3204356
class node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.start=None def display(head): if head==None: print('list is empty') else: temp=head while temp: print(temp.data) temp=temp...
3204362
from distutils.core import setup, Extension import os os.system("sudo apt-get install python-dev") os.system("sudo apt-get install libseccomp-dev") os.system("gcc ExactRunner/runner.c -o runner -lseccomp -DEXACT_MOD") setup ( name='ExTJudger', version='1.0 Exbeta', packages=['ExTJudger'], package_dir={'ExTJudger'...
3204382
import argparse def parse_args(args): """ Parse the arguments. """ parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.') subparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type') subparsers.required =...
3204387
import pygame init_posn = (20,450) time_to_observe = 1000 name = "level1" def walls_init(walls, screen,color): for wall in walls: pygame.draw.rect(screen, color, wall,0) pygame.display.flip() def wall_to_rect(walls): rects = [] for wall in walls: rects.append(pygame.Rect(wall)) r...
3204391
import os import argparse import xmltodict import json import requests from concurrent.futures import ThreadPoolExecutor MAX_WORKERS = 10 ENDPOINT = 'https://explorecourses.stanford.edu/' DEPARMENTS_ENDPOINT = ENDPOINT + '?view=xml-20140630' COURSE_ENDPOINT = (ENDPOINT + 'search?view=xml-20140630&academicYear=' ...
3204403
import collections import errno import functools import select import socket '''Asynchronous socket service inspired by the basic design of Boost ASIO. This service currently supports TCP sockets only, and supports asynchronous versions of common client operations (connect, read, write) and server operations (accept...
3204417
def export_sdfg(sdfg, name=None): if name is None: name = sdfg.name else: name = sdfg.name + "_" + name out_file_json = "gen/json/" + name + ".json" out_file_sdfg = "gen/sdfg/" + name + ".sdfg" sdfg.save(filename=out_file_json) sdfg.save(filename=out_file_sdfg)
3204419
import thread, redis from kafka import SimpleProducer, KafkaClient from flask import Flask, session from flask.ext.session import Session from query_subscriber import QuerySubscriber from views import attach_views from datetime import datetime def highlight(word): return("<span style=\"background-color: #FFFF00\">...
3204426
from mock import patch from ....testcases import DustyTestCase from dusty.compiler.port_spec import (_docker_compose_port_spec, _nginx_port_spec, _hosts_file_port_spec, get_port_spec_document, ReusedHostFullAddress, ReusedStreamHostPort) clas...
3204427
import itertools from permuta import Perm class Bijections: """A collection of known bijections.""" # pylint: disable=too-few-public-methods @staticmethod def simion_and_schmidt(perm: Perm, inverse: bool = False) -> Perm: """The bijection from `Restricted permutations` by <NAME> and <NAME> ...
3204430
from django.core.management.base import BaseCommand, CommandError from django.core.urlresolvers import reverse from boto1.models import Image, Hit from optparse import make_option import urlparse import boto import boto.mturk import boto.mturk.connection _mturk_connexion = None def get_connection(): global _mturk...
3204444
from .geom import geom class geom_line(geom): """ Line chart Parameters ---------- x: x values for (x, y) coordinates y: y values for (x, y) coordinates color: color of line alpha: transparency of color linetype: type of the line ('solid', 'd...
3204463
import os import numpy as np import tensorflow as tf import gpflow from GPcounts import branchingKernel from GPcounts import NegativeBinomialLikelihood from sklearn.cluster import KMeans import scipy.stats as ss from pathlib import Path import pandas as pd from gpflow.utilities import set_trainable from tqdm import tq...
3204507
import random import argparse import sys import os import json import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))) from common.pytorch.ner.model import Tagger def lines(path): w...
3204524
from contextlib import contextmanager, ExitStack from itertools import chain from ..errors import * from .state import State from .core import Context, Object, BoundObject, Scope, Type from .stats import Stats from .util import inScope, checkCompatibility from .links import Link # Python Predefines ForwardObject = N...
3204567
from __future__ import print_function from __future__ import division import os, sys sys.path.insert(0, r'../') import time import argparse from optimise import TRAIN, TUNE, hyperoptTUNE, skoptTUNE parser = argparse.ArgumentParser() # Pick a data set and a LSTM model parser.add_argument('--data', type=str, default='...
3204597
from torch import nn from typing import Callable def activate_train_mode_for_dropout_layers(model: Callable) -> Callable: model.eval() # type: ignore n_dropout_layers = 0 for module in model.modules(): # type: ignore if isinstance(module, nn.Dropout): module.train() n_dr...
3204600
from __future__ import print_function, division import torch import os from os.path import exists, join, basename from skimage import io import pandas as pd import numpy as np from torch.utils.data import Dataset from geotnf.transformation import GeometricTnf from torch.autograd import Variable from geotnf.transformati...
3204603
import click from globus_cli.login_manager import LoginManager from globus_cli.parsing import command, endpoint_id_arg from globus_cli.termio import FORMAT_TEXT_RAW, formatted_print @command( "delete", short_help="Delete an access control rule", adoc_examples="""[source,bash] ---- $ ep_id=ddb59aef-6d04-1...
3204627
from django.urls import path from . import views urlpatterns = [ path("<str:regno>.json", views.get_charity, {"filetype": "json"}), path("<str:regno>.html", views.get_charity, {"filetype": "html"}), path("<str:regno>", views.get_charity, {"filetype": "html"}, name="charity_html"), path( "<str:...
3204707
import numpy as np def distance(face_list,face_targets): face_list = np.array(face_list) face_targets = np.array(face_targets) row_num_face_list = face_list.shape[0] row_num_face_targets = face_targets.shape[0] col_num_face_targets = face_targets.shape[1] face_targets_for_minus = np.repeat(face...
3204724
import numpy as np from ..base import BaseSKI from tods.detection_algorithm.PyodCBLOF import CBLOFPrimitive class CBLOFSKI(BaseSKI): def __init__(self, **hyperparams): super().__init__(primitive=CBLOFPrimitive, **hyperparams) self.fit_available = True self.predict_available = True self.produce_available = Fa...
3204743
import asyncio import sys sys.path.append('..') from concurrent.futures import ThreadPoolExecutor from skymusic.command_line_player import CommandLinePlayer #A method declared with async def ... must be called with await, or run in an asyncio executor async def ainput(prompt: str = ""): #with ThreadPoolExecutor...
3204752
import os import pytest import caproto as ca from caproto._headers import MessageHeader def test_broadcast_auto_address_list(): pytest.importorskip('netifaces') env = os.environ.copy() try: os.environ['EPICS_CA_ADDR_LIST'] = '' os.environ['EPICS_CA_AUTO_ADDR_LIST'] = 'YES' expect...
3204755
import json import logging import requests from django.conf import settings from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.geos import GEOSGeometry, Point from django.core.exceptions import MultipleObjectsReturned from django.db import transaction from django.db.models import Q fro...
3204767
class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: for i in range(len(str1), 0, -1): s = str1[:i] if str1.replace(s, "") == "" and str2.replace(s, "") == "": return s return ""
3204798
import xmltodict class MavenMetadata: def __init__(self, latest_version): self.latest_version = latest_version @classmethod def parse(cls, xml): data = xmltodict.parse(xml) metadata = data['metadata'] return cls( latest_version=cls.__extract_latest_version(met...
3204833
from ssz_typing import (uint64, Bytes4, Bytes8, Bytes32, Bytes48, Bytes96) ### Types class Slot(uint64): pass class Epoch(uint64): pass class CommitteeIndex(uint64): pass class ValidatorIndex(uint64): pass class Gwei(uint64): pass class Root(Bytes32): pass class Version(Bytes4): pass ...
3204898
from data_mapper.errors import PropertyNotResolved from data_mapper.properties.integer import IntegerProperty from data_mapper.tests.test_utils import PropertyTestCase class IntegerPropertyTests(PropertyTestCase): def test__int(self): self.prop_test( prop=IntegerProperty('x'), data...
3204925
from nose.tools import eq_ import appvalidator.testcases.markup.markuptester as markuptester from ..helper import TestCase from js_helper import silent, TestCase as JSTestCase class TestCSPTags(TestCase): def analyze(self, snippet, app_type="web"): self.setup_err() self.err.save_resource("app_t...
3205018
K = [ [376., 0., 376.], [0., 376., 240.], [0., 0., 1.] ] resolution = (752, 480) left_topic='/gi/simulation/left/image_raw' right_topic='/gi/simulation/right/image_raw' object_position_topic='/track_rect_pub' init_rect_img_topic = '/gi/simulation/left/image_raw'
3205021
import numpy as np def slope_and_intercept(point1, point2): m = (point1[1] - point2[1]) * 1.0 / (point1[0] - point2[0]) c = point1[1] - m * point1[0] return m, c def find_intersection(m1, c1, m2, c2): x = (c2 - c1) * 1.0 / (m1 - m2) y = m1 * x + c1 return np.array([x, y]) def find_polar(po...
3205034
from sklearn.base import BaseEstimator from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils import check_random_state from sklearn.random_projection import GaussianRandomProjection from random_output_trees.transformer import FixedStateTransformer...
3205040
import torch import time import torch.nn.functional as F import pytorch_lightning as pl from torch.optim.lr_scheduler import LambdaLR from geofree.main import instantiate_from_config class WarpTransformer(pl.LightningModule): """This one relies on WarpGPT, where the warper handles the warping to support warp...
3205042
import logging __version__ = "0.1" logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.NullHandler())
3205095
import json from lemon.const import MIME_TYPES, CHARSETS from lemon.request import HttpHeaders class Response: def __init__( self, status: int = 200, headers: HttpHeaders = None, body: str = None, content_type: str = MIME_TYPES.APPLICATION_JSON, charset: str = CHARSETS.UTF8, ...
3205118
from .mock import Mock from .lldb import LLDB from .gdb import GDB from .go import Go from .php import PHP from .python import Python from .ruby import Ruby from .node import Node from .chrome import Chrome from .firefox import Firefox
3205152
import base64 import io import json import posixpath from datetime import timedelta from typing import Any, BinaryIO, Dict, Optional from google.cloud import storage # type: ignore from google.oauth2 import service_account # type: ignore from giftless.storage import ExternalStorage, StreamingStorage from .exc impo...
3205173
from numba import jit import numpy as np import re from multiprocessing import Pool from math import ceil @jit def BaseToNum(chr_seq): chr_seq = re.sub(r'A', '1', chr_seq) chr_seq = re.sub(r'C', '2', chr_seq) chr_seq = re.sub(r'G', '3', chr_seq) chr_seq = re.sub(r'T', '4', chr_seq) return chr_seq ...
3205184
import ast AST_NODE_DISPATCHER = {} def add_generator(node_class_str=None): def decorator(func): from sherlock.codelib.generator import CodeGenerator global AST_NODE_DISPATCHER if node_class_str is not None and hasattr(ast, node_class_str): AST_NODE_DISPATCHER[getattr(ast, nod...
3205198
import drawBot drawBot.size(200, 200) for i in range(14): f = i / 14.0 drawBot.fill(1-f, 1 - f, 0) drawBot.oval(10, 10, 50, 50) drawBot.translate(10, 10)
3205211
import sublime, sublime_plugin gte_st3 = int(sublime.version()) >= 3000 if gte_st3: from .config import * else: from config import * class HiveAddContextUrlBaseCommand(sublime_plugin.TextCommand): def run(self, edit, event=None): conf = sublime.load_settings(CONFIG_BASE_NAME) url = self.f...
3205232
import numpy as np def one_hot(indices, depth, dtype): """Simple implementation of tensorflow.one_hot function. Ref: https://www.tensorflow.org/api_docs/python/tf/one_hot Args: indices (np.array) depth (int) Returns: output (np.array): one-hot tensor ...
3205238
import asyncio import logging import pytest from aiormq import DeliveryError import subsystem from behaviour import EmptyBehav @pytest.mark.asyncio class TestPubSub: async def test_subscribe_wildcard_topic(self, pubsub_behav): # given # when messages are published to wildcard topic awai...
3205252
from jikji import getview, addpage for i in range(1, 5) : addpage(view='myview.myview', params=(i,))
3205318
import math import time blip = Voice(10, 0, 80, 0, 0, 0, 0, 100) picker = Buffer(68, 68) sliders = [ ["R", 15, rgb(15, 0, 0)], ["G", 6, rgb(0, 15, 0)], ["B", 9, rgb(0, 0, 15)] ] # selected colour coordinates sx = 32 sy = 32 def colour_from_xy(x, y): # convert an x, y coordinate (0..63, 0..63) into...
3205340
from __future__ import print_function import sys ### # given two 4 col mtx files, takes a subset of file 2 where each # entity pair is contained in file 1 ### fname1 = sys.argv[1] fname2 = sys.argv[2] output = sys.argv[3] # get number of fields in first line of first file, then # expect every line in both files to...
3205369
import collections def completely_empty(val): if type(val) == str: if val == '': return True else: return False if type(val) == list: if len(val) == 0: return True else: return all([completely_empty(i) for i in val]) if type...
3205399
from mtalg.__about__ import (__title__, __version__, __about__, __email__, __authors__, __url__) from mtalg.alg import add, sub, div, mul, pow, std import mtalg.random from mtalg.tools.__set_threads import set_num_threads from mtalg.tools.__get_threads import ge...
3205426
import re from kaa.filetype.default import defaultmode from kaa.syntax_highlight import * JavaScriptThemes = { 'basic': [], } KEYWORDS = ["break", "case", "catch", "continue", "debugger", "default", "delete", "do", "else", "finally", "for", "function", "if", "in", "instanceof", "new", "re...
3205440
from chatterbot import ChatBot import spacy import json nlp = spacy.load("en_core_web_sm") bot = ChatBot('bot', storage_adapter='chatterbot.storage.SQLStorageAdapter', input_adapter = 'chatterbot.input.TerminalAdapter', output_adapter = 'chatterbot.output.TerminalAdapter') from c...
3205486
import unittest from openmdao.main.api import Component, Assembly, set_as_top from openmdao.main.datatypes.api import Float class C1Base(Component): fin = Float(iotype='in') fpass = Float(iotype='out') class C1(C1Base): def execute(self): self.fpass = 2*self.fin class C2(Component): f...
3205540
import tea ''' Want to see if Wrestling is correlated with greater athlete Weight than Swimming, and if Female athletes have a lower Weight than Male athletes. ''' data_path = "./athlete_events_cleaned_weight.csv" variables = [ { 'name': 'ID', 'data type': 'ratio' }, { 'name': '...
3205579
from __future__ import print_function, absolute_import, division import boto3 import json import logging class AwsSQSPlugin(object): def __init__(self, unwanted_resources, problematic_resources, dry_run, queue_account=None, queue_name=None, queue_region=None,): self.queue_account = queu...
3205589
import json import pytest import six from mock import Mock, patch from nefertari import json_httpexceptions as jsonex from nefertari.renderers import _JSONEncoder class TestJSONHTTPExceptionsModule(object): def test_includeme(self): config = Mock() jsonex.includeme(config) config.add_vi...
3205649
from website.app import create_app import website.config as config import os config_object = eval(os.environ['FLASK_APP_CONFIG']) app = create_app(config_object) if __name__ == "__main__": app.run()
3205658
from co2tools.stl.builder import Builder def solidify(yaml_data, execute_action=None, execute_group=None, execute_file=None, base_folder=None, engine=None): if execute_action is not None: if execute_action != 'solidify': return solid_data = yaml_data['solidify'] source_folder = solid_d...
3205768
REGISTER_VERIFICATION_URL = '/verify-account/' REGISTER_EMAIL_VERIFICATION_URL = '/verify-email/' RESET_PASSWORD_VERIFICATION_URL = '/reset-password/' VERIFICATION_FROM_EMAIL = '<EMAIL>' USERNAME = 'testusername' USERNAME2 = 'testusername2' USER_PASSWORD = '<PASSWORD>'
3205824
from random import randint, choice from pathlib import Path from typing import Tuple from PIL import Image, UnidentifiedImageError import torch from torch.utils.data import Dataset from torchvision.transforms import transforms from transformers import AutoTokenizer from preprocess import remove_style, remove_...
3205830
from homeassistant.components.switch import SwitchEntity from .core.const import DOMAIN from .core.entity import XEntity from .core.ewelink import XRegistry, SIGNAL_ADD_ENTITIES PARALLEL_UPDATES = 0 # fix entity_platform parallel_updates Semaphore async def async_setup_entry(hass, config_entry, add_entities): ...
3205881
from .metrics import ( compute_visual_query_metrics, SuccessMetrics, TrackingMetrics, TemporalDetection, SpatioTemporalDetection, ) __all__ = [ "SuccessMetrics", "TrackingMetrics", "TemporalDetection", "SpatioTemporalDetection", "compute_visual_query_metrics", ]
3205892
import boto3 import sys import traceback import re from collections import defaultdict from datetime import datetime from itertools import islice from tilequeue.tile import coord_marshall_int from tilequeue.tile import create_coord from time import time from botocore.credentials import RefreshableCredentials from botoc...
3205904
import numpy as np from abc import ABCMeta, abstractmethod import math from ..Utils import transformations as T import tf.broadcaster import rospy from visualization_msgs.msg import Marker from geometry_msgs.msg import PoseStamped keyboard_pos_goal = [0,0,0] keyboard_quat_goal = [1,0,0,0] def keyboard_goal_cb(data): ...
3205910
import torch.nn as nn from models.feature_extractors import ConcatCompareCombinedFeaturesExtractor, DotProductCombinedFeaturesExtractor class CombineSiameseHead(nn.Module): def __init__(self, input_dim, fc_dims=None, siamese_head_type="concat"): super().__init__() self.__verify_siamese_head_type...
3205938
def errorInOuter(): y = 1 del y print(y) def inner(): return y def errorInInner(): def inner(): return y y = 1 del y inner() ___assertRaises(UnboundLocalError, errorInOuter) ___assertRaises(NameError, errorInInner)
3205956
import paddle import paddle.nn as nn import paddle.nn.functional as F class VFE_Clas(nn.Layer): def __init__(self, num_classes=16, max_points=1024): super(VFE_Clas, self).__init__() self.vfe = VFE(max_points=max_points) self.fc = self.fc = nn.Sequential( nn.Linear(max_points, 51...
3205958
import description as desc from . import arm_semas def get_arg_types(decl): return [ arg.strip().split(' ')[0] for arg in decl[decl.index('(')+1:decl.index(')')].split(',')] def get_output_type(decl): return decl.split(' ')[0] def create_description(intrin, sema): xs, y, out_ty, decl = sema ctype...
3205964
import fbuild.builders.c.gcc.darwin as darwin import fbuild.builders.c.gcc.iphone as iphone # ------------------------------------------------------------------------------ def static(ctx, exe=None, *args, **kwargs): if exe is None: exe = iphone._iphone_devroot(False) / 'usr/bin/g++' return iphone._b...