id
stringlengths
3
8
content
stringlengths
100
981k
1735731
import ctypes class disable_file_system_redirection: _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection def __enter__(self): self.old_value = ctypes.c_long() self.success = self._disable(ctypes.byref(self.old_value...
1735749
import unittest import checksieve class TestError(unittest.TestCase): def test_error(self): sieve = ''' require "ihave"; addheader "X-Hello" "World"; if ihave "index" { deleteheader :index 1 "X-Hello"; } else { error "Abort!"; } ''' ...
1735768
import sensor, image, time, machine, pyb, nn barCol = 0 def DrawPgsBar(img, barLen, loopCnt, startTick, width=5): global barCol lnLen = (barLen * (loopCnt - (time.ticks() - startTick))) // loopCnt if (barCol & 0x80) == 0: c = barCol & 0x7F else: c = 128 - (barCol & 0x7F) img.draw_re...
1735775
import pdf_reports.tools as tools import pandas dataframe = pandas.DataFrame.from_records( { "Name": ["Anna", "Bob", "Claire", "Denis"], "Age": [12, 22, 33, 44], "Height (cm)": [140, 175, 173, 185], }, columns=["Name", "Age", "Height (cm)"], ) def test_tr_modifier(): html = to...
1735784
from typing import Text, Dict, List, Type from rasa.core.channels.channel import ( # noqa: F401 InputChannel, OutputChannel, UserMessage, CollectingOutputChannel, ) # this prevents IDE's from optimizing the imports - we need to import the # above first, otherwise we will run into import cycles from r...
1735795
from itertools import product import os import tempfile import warnings import holoviews import pytest from fragile.dataviz.plot_saver import PlotSaver from tests import IN_CI from tests.dataviz.test_swarm_viz import swarm_dict, swarm_names, backends @pytest.fixture(params=tuple(product(swarm_names, backends)), sco...
1735809
import os import requests import logging from tornado import template import verifier logger = logging.getLogger(__name__) DOMAIN_NAME = 'torweather.org' API_KEY = os.environ.get('MAILGUN_KEY') EMAIL_DOWN_SUBJECT = '[Tor Weather] Node Down!' EMAIL_DOWN_BODY = ''' It appears that the Tor node {{nickname}} (fingerprin...
1735813
from django.db import connection from django.contrib.gis.gdal import GDAL_VERSION from django.contrib.gis.tests.utils import mysql, no_mysql, oracle, postgis, spatialite from django.utils import unittest test_srs = ({'srid' : 4326, 'auth_name' : ('EPSG', True), 'auth_srid' : 4326, ...
1735843
import abc import logging from fnmatch import fnmatch from operator import attrgetter from .collections import FolderCollection, SyncCompleted from .queryset import SingleFolderQuerySet, SHALLOW as SHALLOW_FOLDERS, DEEP as DEEP_FOLDERS from ..errors import ErrorAccessDenied, ErrorFolderNotFound, ErrorCannotEmptyFolder...
1735853
import numpy as np import theano import theano.tensor as T from theano.tensor.signal import pool from theano.tensor.nnet import conv2d import theano.tensor.nnet.lrn as LRN from theano.sandbox.mkl.mkl_conv import AbstractConvGroup import warnings warnings.filterwarnings("ignore") rng = np.random.RandomState(23455) #...
1735913
import os import glob import time import tensorflow as tf import numpy as np import tensorflow.contrib.slim as slim import subprocess from datetime import datetime from tensorflow.python.ops import control_flow_ops from modules.videosr_ops import * class EASYFLOW(object): def __init__(self): self.num_fram...
1735914
import pandas as pd import numpy as np from matplotlib import pyplot as plt # Series Problem s1 = pd.Series(-3, index=range(2, 11, 2)) s2 = pd.Series({'Bill':31, 'Sarah':28, 'Jane':34, 'Joe':26}) # Random Walk Problem # five random walks of length 100 plotted together N = 100 for i in xrange(5): s1 = np.zeros(N) ...
1735916
import torch def l2_loss(input, target): """ very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter """ pos_inds = torch.nonzero(target > 0.0).squeeze(1) if pos_inds.shape[0] > 0: cond = torch.abs(input[pos_inds] - target[pos_inds]) loss = 0.5 * cond...
1735940
import numpy as np from sherlockpipe.scoring.SignalSelector import SignalSelector, SignalSelection class BasicSignalSelector(SignalSelector): """ Selects the signal with best SNR """ def __init__(self): super().__init__() def select(self, transit_results, snr_min, detrend_method, wl): ...
1735950
import ray from ray.job_config import JobConfig from ray import serve from ray.serve.config import ReplicaConfig, DeploymentConfig from ray.serve.utils import msgpack_serialize from ray.serve.generated.serve_pb2 import JAVA, RequestMetadata, RequestWrapper from ray.tests.conftest import shutdown_only # noqa: F401 de...
1735964
from poop.hfdp.decorator.pizza.cheese import Cheese from poop.hfdp.decorator.pizza.olives import Olives from poop.hfdp.decorator.pizza.thickcrust_pizza import ThickcrustPizza from poop.hfdp.decorator.pizza.thincrust_pizza import ThincrustPizza def main() -> None: # cria uma pizza pizza = ThincrustPizza() ...
1735973
import sys import os import torch import torch.distributed as dist import torch.nn as nn from torch.utils.data import DataLoader import torch.multiprocessing as mp from torch.nn.parallel import DataParallel from datetime import datetime from pepper_variant.modules.python.models.dataloader_predict import SequenceDatase...
1735974
import torch.nn as nn class SequentialFlow(nn.Module): """A generalized nn.Sequential container for normalizing flows. """ def __init__(self, layersList): super(SequentialFlow, self).__init__() self.chain = nn.ModuleList(layersList) def forward(self, x, logpx=None, reverse=False, ind...
1735977
import numpy as np import os import plac import time from tensorflow.keras.optimizers import Nadam from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard from tensorflow.keras.layers import Input from tensorflow.keras import backend as K from model import MobileDetectNetModel from gene...
1735999
import pytest import openeo.internal.graphbuilder_040 @pytest.fixture(params=["0.4.0", "1.0.0"]) def api_version(request): return request.param def reset_graphbuilder(): # Reset 0.4.0 style graph builder openeo.internal.graphbuilder_040.GraphBuilder.id_counter = {} @pytest.fixture(autouse=True) def a...
1736042
from .base import BaseModule class Public(BaseModule): def get_shop_by_partner(self, **kwargs): """ :param kwargs :return """ return self.client.execute("public/get_shop_by_partner", "GET", kwargs)
1736087
description = 'PUMA triple-axis setup with FRM2-Detector' includes = ['pumabase', 'seccoll', 'collimation', 'ios', 'hv', 'notifiers', 'detector',] group = 'basic' devices = dict( det = device('nicos.devices.generic.Detector', # description = 'Puma detector device (5 counters)', descri...
1736098
import torch import torch.nn as nn import torch.nn.functional as F class _ASPPModule(nn.Module): def __init__(self, inplanes, planes, kernel_size, padding, dilation, BatchNorm): super(_ASPPModule, self).__init__() self.atrous_conv = nn.Conv2d(inplanes, planes, kernel_size=kernel_size, ...
1736108
import numpy as np import matplotlib.pyplot as plt import os import pydicom as pyd from glob import glob from keras.preprocessing.image import ImageDataGenerator from keras.utils import to_categorical import bisect import random import math from Augmentor import * def import_dicom_data(path): data_path = path + '/...
1736155
import os import io from . import _common from ._common import as_file, files from .abc import ResourceReader from contextlib import suppress from importlib.abc import ResourceLoader from importlib.machinery import ModuleSpec from io import BytesIO, TextIOWrapper from pathlib import Path from types import ModuleType f...
1736173
import logging import urllib.parse from datetime import datetime from algo import constants as co from algo.asset import Algo from algo.config_algo import localconfig from algo.handle_akita import handle_akita_swap_transaction, is_akita_swap_transaction from algo.handle_algodex import handle_algodex_transaction, is_al...
1736187
import unittest import os from modules.DatabaseModule.DBManager import DBManager from opentera.config.ConfigManager import ConfigManager from tests.opentera.db.models.BaseModelsTest import BaseModelsTest class TeraServiceProjectTest(BaseModelsTest): filename = os.path.join(os.path.dirname(__file__), 'TeraServi...
1736234
import math import random import pygame from utils.colors import WHITE from utils.parameters import WIDTH_UNIT, WINDOW_HEIGHT, WINDOW_WIDTH, \ LEFT, RIGHT, NOTHING, NO, YES, MEASURE_LEFT, MEASURE_RIGHT from utils.score import Score from utils.sound import Sound class Ball(pygame.sprite.Sprite): def __init__...
1736262
import sublime class GitGutterShowDiff(object): region_names = ('deleted_top', 'deleted_bottom', 'deleted_dual', 'inserted', 'changed', 'untracked', 'ignored') def __init__(self, git_handler, status_bar): """Initialize GitGutterShowDiff object.""" self.git_handler = git_ha...
1736267
import atexit from celery.app.control import flatten_reply from celery.app import Celery from celery.exceptions import TimeoutError from celery.utils.imports import qualname from itertools import count import os import signal import socket import sys from time import time import traceback def _get_current_app(config_...
1736298
import os, glob, config, logging from wxStocks_modules.wxStocks_classes import SpreadsheetCell as Cell ''' Here, you must use the class "Cell" to refer to a cell you want processed. This allows the program to process your data in to function wxPython code. The class Cell has the following default keyword arguments: my...
1736342
import os import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging from slicer.util import VTKObservationMixin # from Resources import HomeResourcesResources class Home(ScriptedLoadableModule): """Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/b...
1736346
from finrl_meta.data_processors.processor_alpaca import AlpacaProcessor as Alpaca from finrl_meta.data_processors.processor_wrds import WrdsProcessor as Wrds from finrl_meta.data_processors.processor_yahoofinance import YahooFinanceProcessor as YahooFinance from finrl_meta.data_processors.processor_binance import Binan...
1736375
import sys import os from capture.captive_browser import CaptiveBrowser def test_auto_resize(): browser = CaptiveBrowser(headless=False, browser="firefox") browser.navigate("https://coronavirus.dc.gov/page/coronavirus-data") browser.screenshot("c:\\temp\\test.png", full_page=True) if __name__ == "__main...
1736399
from typing import Any from typing import Dict from typing import Optional from typing import Sequence import warnings from optuna._experimental import experimental from optuna.distributions import BaseDistribution from optuna.samplers import BaseSampler from optuna.study import Study from optuna.trial import FrozenTr...
1736488
import gym from gym import spaces from gym.utils import seeding def cmp(a, b): return int((a > b)) - int((a < b)) # 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10 deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def draw_card(np_random): return np_random.choice(deck) def draw_hand(np_random): re...
1736516
from .hover.processor import HoverNetPostProcessor from .cellpose.processor import CellposePostProcessor from .drfns.processor import DRFNSPostProcessor from .dcan.processor import DCANPostProcessor from .dran.processor import DRANPostProcessor from .basic.processor import BasicPostProcessor from .thresholding import ...
1736518
from .api import * # noqa from .api import __all__ as api_exports # Delegate to API export __all__ = api_exports # Package metadata __author__ = '<NAME>' __license__ = 'MIT' # Current version __version__ = '1.0.2'
1736519
import numpy as np from frameworks.CPLELearning import CPLELearningModel from frameworks.SelfLearning import SelfLearningModel from methods.scikitWQDA import WQDA from examples.plotutils import evaluate_and_plot # number of data points N = 60 supevised_data_points = 4 # generate data meandistance = 1 s = np.random....
1736547
from astroid import MANAGER, arguments, nodes, inference_tip, UseInferenceDefault def infer_namespace(node, context=None): callsite = arguments.CallSite.from_call(node, context=context) if not callsite.keyword_arguments: # Cannot make sense of it. raise UseInferenceDefault() class_node = ...
1736549
import logging from re import compile from django.conf import settings from django.http import HttpResponseRedirect from django.utils.http import is_safe_url log = logging.getLogger(__name__) EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip("/"))] + [ compile(expr) for expr in getattr(settings, "LOGIN_EXEMPT_URL...
1736551
from pirates.minigame import DistributedLock from direct.interval.IntervalGlobal import * class DistributedLockDoor(DistributedLock.DistributedLock): def __init__(self, cr): DistributedLock.DistributedLock.__init__(self, cr) self.isDoor = 1 def loadModel(self): self.table = loader.loa...
1736588
from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): return LaunchDescription([ Node( node_name='rplidar_composition', package='rplidar_ros', node_executable='rplidar_composition', output='screen', ...
1736591
import logging from time import sleep, time import numpy as np import pybullet as p from transforms3d import euler log = logging.getLogger(__name__) from igibson.external.pybullet_tools.utils import ( control_joints, get_base_values, get_joint_positions, get_max_limits, get_min_limits, get_s...
1736592
import logging from enum import Enum from typing import Any, Dict, List, Optional, Union from ... import Logger from .base import BaseValidator from .exceptions import SchemaValidationError RULES_KEY = "rules" FEATURE_DEFAULT_VAL_KEY = "default" CONDITIONS_KEY = "conditions" RULE_MATCH_VALUE = "when_match" CONDITION_...
1736597
from django.core.management.base import BaseCommand import intake.services.bundles as BundlesService class Command(BaseCommand): help = 'Sends an email about unopened applications' def handle(self, *args, **options): BundlesService.count_unreads_and_send_notifications_to_orgs() self.stdout.w...
1736625
import math import StringIO import types __pychecker__ = 'no-returnvalues' WS = set([' ', '\t', '\r', '\n', '\x08', '\x0c']) DIGITS = set([str(i) for i in range(0, 10)]) NUMSTART = DIGITS.union(['.', '-', '+']) NUMCHARS = NUMSTART.union(['e', 'E']) ESC_MAP = {'n': '\n', 't': '\t', 'r': '\r', 'b': '\x08', 'f': '\x0c'} R...
1736631
import databases import ormar import sqlalchemy database = databases.Database("sqlite:///db.sqlite") metadata = sqlalchemy.MetaData() class ToDo(ormar.Model): class Meta: tablename = "todos" metadata = metadata database = database id: int = ormar.Integer(primary_key=True) text: s...
1736645
import os from unittest import mock from django.contrib.auth.models import Permission, User from django.shortcuts import get_object_or_404 from django.test.utils import override_settings from django.utils import translation from django.utils.translation import gettext as _ from django.conf import settings # Workarou...
1736662
import qfast def synthesize_for_qiskit ( utry, **kwargs ): return qfast.synthesize( utry, **kwargs )
1736672
from __future__ import absolute_import import os import os.path as osp from torch.utils.data import DataLoader, Dataset import numpy as np import random import math from PIL import Image class Preprocessor(Dataset): def __init__(self, dataset, root=None, transform=None, mutual=False, index=False, multi_transform=1...
1736720
import paddle import paddle.nn as nn __all__ = ['LinearBlock', 'MLP'] class LinearBlock(nn.Layer): """ Implementation of a linear block: linear-BatchNorm-ReLU Args: input_size(int): size of the input output_size(int): size of the output Examples: ..code-block:: python ...
1736732
from .. import Provider as AddressProvider class Provider(AddressProvider): city_formats = ('{{first_name}}',) city_prefixes = ('ք.',) city_suffixes = ('',) street_prefixes = ('փողոց', 'պողոտա') street_suffixes = ('',) village_prefixes = ('գ.',) address_formats = ( '{{city_prefix...
1736749
import subprocess class SubprocessUtils(object): ''' Provides subprocess-related functionality ''' @staticmethod def capture(command, suppress_stderr=False, **kwargs): ''' Executes a subprocess and captures its stdout output, allowing stderr output to be printed ''' stderr = subprocess.PIPE if suppress_...
1736802
import matplotlib.pyplot as plt import numpy as np def plot(): fig = plt.figure(1, figsize=(8, 5)) ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1, 5), ylim=(-4, 3)) t = np.arange(0.0, 5.0, 0.2) s = np.cos(2 * np.pi * t) ax.plot(t, s, color="blue") ax.annotate( "text", x...
1736811
import copy import pathlib import pickle import time from functools import partial, reduce import numpy as np from det3d.core.bbox import box_np_ops from det3d.core.sampler import preprocess as prep from det3d.utils.check import shape_mergeable class DataBaseSamplerV2: def __init__( self, db_info...
1736825
from __future__ import print_function from Components.Sources.Source import Source from Components.PluginComponent import plugins from Tools.Directories import resolveFilename, SCOPE_PLUGINS class ReadPluginList(Source): def __init__(self, session): Source.__init__(self) self.session = session def command(self...
1736839
import argparse, asyncio, json, os, cv2, platform, sys from time import sleep from aiohttp import web from av import VideoFrame from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack, RTCIceServer, RTCConfiguration from aiortc.contrib.media import MediaPlayer from aiohttp_basicauth import BasicA...
1736849
from pyrogram import Client, filters from pyrogram.types import Message from bot_errors_logger import logging_errors import constants import db from tr import tr import json import html from bot_custom_exceptions import google_api_error prefix = constants.prefix @Client.on_message(filters.command("start", prefix) & ...
1736894
from team29.analizer.abstract.expression import Expression, TYPE from team29.analizer.abstract import expression from team29.analizer.reports import Nodo from datetime import datetime from team29.analizer.statement.expressions.primitive import Primitive import pandas as pd class ExtractDate(Expression): def __ini...
1736900
import os from joblib import dump, load from ranking import MODELS_FOLDER def get_model_path(model_name: str) -> str: """ A helper function to retrieve the model path """ if model_name.endswith(".joblib"): return os.path.join(MODELS_FOLDER, model_name) else: return os.path.join(M...
1736915
import torch import matplotlib.pyplot as plt from pymatch.ReinforcementLearning.PolicyGradient import PolicyGradient from pymatch.ReinforcementLearning.Loss import REINFORCELoss from models.PG1 import Model from pymatch.ReinforcementLearning.TorchGym import TorchGym from my_utils import sliding_mean model = Model(4...
1736929
from __future__ import absolute_import from asyncio import Future, get_event_loop, iscoroutine, wait from promise import Promise try: from asyncio import ensure_future except ImportError: # ensure_future is only implemented in Python 3.4.4+ def ensure_future(coro_or_future, loop=None): """Wrap a ...
1736980
import os import torch import pytorch3d import pytorch3d.loss import numpy as np from scipy.spatial.transform import Rotation import pandas as pd import point_cloud_utils as pcu from tqdm.auto import tqdm from models.utils import * from .misc import BlackHole def load_xyz(xyz_dir): all_pcls = {} for fn in tqd...
1736992
from hashlib import md5 from urllib import urlencode from django import template register = template.Library() @register.simple_tag def get_gravatar(email, size=60, rating='g', default=None): """ Return url for a Gravatar. From Zinnia blog. """ url = 'https://secure.gravatar.com/avatar/{0}.jpg'.format( ...
1736997
import requests def main(): url = "http://0.0.0.0:8006/respond" input_data = {"sentences": ["i like <NAME>", "hey this is a white bear"]} result = requests.post(url, json=input_data) assert result.json() == [["<NAME>"], ["a white bear"]] print("Success!") if __name__ == "__main__": main()
1737037
import ray from ray.util.sgd.torch import TrainingOperator from ray.util.sgd import TorchTrainer from ray import tune import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data.dataloader import DataLoader import raydp from raydp.torch import TorchEstimator from raydp.utils import random_...
1737039
from pyuploadcare.client import Uploadcare from pyuploadcare.dj import conf as dj_conf def get_uploadcare_client(): config = { "public_key": dj_conf.pub_key, "secret_key": dj_conf.secret, "user_agent_extension": dj_conf.user_agent_extension, } if dj_conf.cdn_base: config["...
1737054
import random import time import matplotlib.pyplot as plt # ------------------------------------------------------------------------------ def objective_function(O): x = O[0] y = O[1] nonlinear_constraint = (x - 1) ** 3 - y + 1 linear_constraint = x + y - 2 if nonlinear_constraint > 0: penal...
1737092
import hail as hl from hail.typecheck import typecheck, sequenceof from hail.expr.expressions import expr_str, expr_call, expr_locus, expr_array from typing import List @typecheck(locus=expr_locus(), alleles=expr_array(expr_str), proband_call=expr_call, father_call=expr_call, ...
1737132
import pytest from sai import SaiObjType import topologies.dc_t1 @pytest.fixture(scope="module") def dc_t1_topology(npu): with topologies.dc_t1.config(npu) as result: yield result def test_basic_route(npu, dc_t1_topology): npu.create_route("172.16.31.10/8", npu.default_vrf_oid, dc_t1_topology["cpu_p...
1737136
import mmcv import numpy as np from numpy import random from mmdet.core import poly2bbox from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from pycocotools.coco import maskUtils import cv2 from functools import partial import copy def TuplePoly2Poly(poly): outpoly = [poly[0][0], poly[0][1], ...
1737139
from Pyro5.api import Proxy uri = input("enter the server uri: ").strip() if "\\x00" in uri: uri=uri.replace("\\x00", "\x00") print("(uri contains 0-byte)") with Proxy(uri) as p: response = p.message("Hello there!") print("Response was:", response)
1737163
from fontbakery.checkrunner import WARN from fontbakery.codetesting import (assert_results_contain, CheckTester, TEST_FILE, assert_PASS) from fontbakery.profiles import outline as outline_profile def test_check...
1737172
import numpy as np import numpy.testing as npt import unittest import sys import os import torch import torch.legacy.nn as nn from _test_utils import _INPUT_SHAPE sys.path.append( os.path.dirname(os.path.realpath(__file__)) + "/../torch2coreml/" ) class SingleLayerTest(unittest.TestCase): def setUp(self): ...
1737200
from django.shortcuts import render from rest_framework import exceptions from waffle import switch_is_active OPENAPI_PAGE = "openapi.html" def openapi(request): # serve swagger ui landing page if not switch_is_active("enable_swaggerui"): # response NOT FOUND raise exceptions.NotF...
1737218
from mosestokenizer import * import sys # this is a helper script for tokenization of parallel testset in format "english sentence ||| other language sentence" if len(sys.argv) != 3: print("COMMAND: tokenize.py input_file second_language") input_file = sys.argv[1] second_language = sys.argv[2] en_tokenize = M...
1737223
from unittest import mock from django.test import TestCase from elasticsearch.exceptions import TransportError from elasticsearch_django.management.commands import ( BaseSearchCommand, create_search_index, delete_search_index, prune_search_index, rebuild_search_index, update_search_index, ) ...
1737232
from requests import get def hackclub(highSchoolHackathons: list): url = 'https://hackathons.hackclub.com/api/events/upcoming' response = get(url) json_response = response.json() for i in json_response: hackathon = {} title = i["name"] link = i["website"] date = i...
1737251
from mysql.connector import connect import MySQLerrorTypes class easierMySQL(): def __init__(self,userName : str,passwrd : str,host : str, database : str): self.userName = userName self.passwrd = <PASSWORD> self.host = host self.database = database def create_Table(self,tableNa...
1737275
import binascii from dataclasses import dataclass from typing import List from typing import Union from codechain.crypto import blake128 as _blake128 from codechain.crypto import blake128_with_key as _blake128_with_key from codechain.crypto import blake160 as _blake160 from codechain.crypto import blake160_with_key as...
1737305
import collections import cv2 import numpy as np import matplotlib.pyplot as plt import gym def plot_learning_curve(x, scores, epsilons, filename, lines=None): fig=plt.figure() ax=fig.add_subplot(111, label="1") ax2=fig.add_subplot(111, label="2", frame_on=False) ax.plot(x, epsilons, color="C0") a...
1737434
import os def get_sha1_from_file(base_dir, relative_path): """ Try to read base_dir/relative_path. For git head, relative_path should be 'HEAD'. If it contains a sha1, return it. If it contains a ref, open base_dir/<ref> and return its contents. On error, return None """ try: head_...
1737436
import argparse import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' import pickle import numpy as np import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence from torchvision import transforms from data_loader import get_loader from model import EncoderCNN, DecoderRNN from build_vocab imp...
1737456
import numpy as np import scipy.io.wavfile as wav import librosa import os,sys,shutil,argparse,copy,pickle import math,scipy from faceformer import Faceformer from transformers import Wav2Vec2FeatureExtractor,Wav2Vec2Processor import torch import torch.nn as nn import torch.nn.functional as F import cv2 import tempfi...
1737468
from savu.plugins.plugin_tools import PluginTools class MaskInitialiserTools(PluginTools): """A plugin to initialise a binary mask for level sets and distance transform segmentations. Seeds are generated by providing coordinates of three points in 3D space (start-middle-finish) and connecting them with a cylinder ...
1737469
from contextlib import asynccontextmanager from logging import getLogger from os import environ import aiohttp import base64 from trustpilot import auth, utils logger = getLogger("trustpilot.async_client") class TrustpilotAsyncSession: __SUPPORTED_HTTP_METHODS = ["post", "get", "put", "delete"] def __init_...
1737505
import tensorflow as tf from phash.model import phash_avg_tf, phash_dct_tf, compare_hash from utils import * TYPE = "avg" if __name__ == '__main__': np.random.seed(0) import argparse parser = argparse.ArgumentParser() parser.add_argument('target_logo', type=str) parser.add_argument('output_dir'...
1737510
import numpy as np from scipy.spatial.qhull import ConvexHull, QhullError # this two functions are from # https://stackoverflow.com/questions/37117878/generating-a-filled-polygon-inside-a-numpy-array/37123933#37123933 def check(p1, p2, idxs): """ Uses the line defined by p1 and p2 to check array of input...
1737552
import os import warnings from bento.core.pkg_objects \ import \ Extension from bento.core.node \ import \ split_path def translate_name(name, ref_node, from_node): if from_node != ref_node: parent_pkg = ref_node.path_from(from_node).replace(os.sep, ".") return ".".join([p...
1737590
import sys from IPython.parallel import Client rc = Client() rc.block=True view = rc[:] view.run('communicator.py') view.execute('com = EngineCommunicator()') # gather the connection information into a dict ar = view.apply_async(lambda : com.info) peers = ar.get_dict() # this is a dict, keyed by engine ID, of the c...
1737603
from __future__ import unicode_literals import unittest from six import text_type from fs.mode import check_readable, check_writable, Mode class TestMode(unittest.TestCase): def test_checks(self): self.assertTrue(check_readable("r")) self.assertTrue(check_readable("r+")) self.assertTrue...
1737617
import os import argparse os.environ["OMP_NUM_THREADS"] = "1" import numpy as np import numpy.random as npr import mimo from mimo.distributions import NormalGamma from mimo.distributions import MatrixNormalWishart from mimo.distributions import GaussianWithNormalGamma from mimo.distributions import LinearGaussianWit...
1737750
from ..dataloader import load_batch from ..dataset_configs import FLYING_CHAIRS_DATASET_CONFIG from ..training_schedules import LONG_SCHEDULE from .flownet_sd import FlowNetSD # Create a new network net = FlowNetSD() # Load a batch of data input_a, input_b, flow = load_batch(FLYING_CHAIRS_DATASET_CONFIG, 'sample', ne...
1737804
from ansiblelater.standard import StandardBase class CheckYamlDocumentStart(StandardBase): sid = "LINT0004" description = "YAML should contain document start marker" version = "0.1" types = ["playbook", "task", "handler", "rolevars", "hostvars", "groupvars", "meta"] def check(self, candidate, se...
1737856
from tweedr.api.mappers import Mapper from tweedr.api.protocols import TweetDictProtocol import logging logger = logging.getLogger(__name__) # for the bloomfilter import tempfile import pybloomfilter # for simhashing from hashes.simhash import simhash class TextCounter(Mapper): INPUT = TweetDictProtocol OU...
1737882
from typing import ( Any, Dict, ) import logging from urllib.parse import urljoin import requests logger = logging.getLogger(__name__) class HttpClient: def __init__( self, base_url: str, api_token: str, timeout: float = None, verify_tls: bool = True, user...
1737886
from __future__ import print_function import sys import os import regreg.api as rr import numpy as np from selection.reduced_optimization.generative_model import generate_data, generate_data_random from selection.reduced_optimization.initial_soln import instance from selection.tests.instance import logistic_instance,...
1737904
import os import argparse from src.load_save_model import loadcaffemodel, saveonnxmodel from src.caffe2onnx import Caffe2Onnx def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('caffe_graph_path',help="caffe's prototxt file path",nargs='?',default="./caffemodel/test/test.prototxt") ...
1737909
from menpo.base import MenpoMissingDependencyError try: from .vlfeat import dsift, fast_dsift, vector_128_dsift, hellinger_vector_128_dsift except MenpoMissingDependencyError: pass # Remove from scope del MenpoMissingDependencyError