id
stringlengths
3
8
content
stringlengths
100
981k
177975
from __future__ import absolute_import, print_function, division import warnings import numpy as np import astropy.units as u __all__ = ["_get_x_in_wavenumbers", "_test_valid_x_range"] def _get_x_in_wavenumbers(in_x): """ Convert input x to wavenumber given x has units. Otherwise, assume x is in wavene...
177979
from pathlib import Path from unittest import TestCase from unittest.mock import patch, Mock from requests.exceptions import HTTPError from requests import Session from test.test_account import TestAccount from gphotos.LocalData import LocalData import test.test_setup as ts photos_root = Path("photos") original_get =...
178008
class color(object): GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' RESET_ALL = '\033[0m'
178022
from secml.optim.optimizers.tests import COptimizerTestCases from secml.array import CArray from secml.optim.optimizers import COptimizerPGDLS from secml.optim.constraints import CConstraintBox, CConstraintL1 class TestCOptimizerPGDLSDiscrete(COptimizerTestCases): """Unittests for COptimizerPGDLS in discrete spa...
178042
import sys import os from platform import python_version # https://github.com/willmcgugan/rich from rich.console import Console from rich.theme import Theme import pydbhub.dbhub as dbhub if __name__ == '__main__': custom_theme = Theme({ "info": "green", "warning": "yellow", "error": "bold...
178058
from typing import List from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Response, status from app.api.dependencies import get_api_key, get_db from app.db.database import MSSQLConnection from app.schemas.security import SecurityLoginResponse, SecurityResponseBase from app.services.exceptio...
178068
import unittest from contextlib import contextmanager from numba import njit from numba.core import errors, cpu, utils, typing from numba.core.descriptors import TargetDescriptor from numba.core.dispatcher import TargetConfigurationStack from numba.core.retarget import BasicRetarget from numba.core.extending import ov...
178123
TEMPLATE = """ {name} ==== README """ def get_readme_template(name: str) -> str: return TEMPLATE.format(name=name)
178133
import ctypes import os from ctypes import wintypes from collections import namedtuple from PySide2.QtWidgets import QApplication def get_process_hwnds(): # https://stackoverflow.com/questions/37501191/how-to-get-windows-window-names-with-ctypes-in-python user32 = ctypes.WinDLL('user32', use_last_erro...
178141
import os import glob from unet3d.data import write_data_to_file, open_data_file from unet3d.generator import get_training_and_validation_generators from unet3d.model import siam3dunet_model from unet3d.model import testnet_model from unet3d.training import load_old_model, train_model from skimage.io import imsave, im...
178176
import pdb import sys class FixedPdb(pdb.Pdb): """ Since we re-direct stdout and stderr in other parts of the application, pdb can't interpret things like arrow keys and auto-complete correctly. This class fixes the issue by getting pdb to always use the default stdout and stderr. """ ...
178201
from django import template from ghoster import forms from django.contrib import admin from django.contrib.admin import helpers import pprint import copy import re register = template.Library() def __flatten(fields): """Returns a list which is a single level of flattening of the original list.""" flat = [...
178211
import numpy as np import tensorflow as tf OUTPUT_PATH = "../events/" def save(): input_node = tf.placeholder(shape=[None, 100, 100, 3], dtype=tf.float32) net = tf.layers.conv2d(input_node, 32, (3, 3), strides=(2, 2), padding='same', name='conv_1') net = tf.layers.conv2d(net, 32, (3, 3), strides=(1, 1), ...
178220
import requests def get_all_data(): root = "https://raw.githubusercontent.com/patidarparas13/Sentiment-Analyzer-Tool/master/Datasets/" data = requests.get(root + "imdb_labelled.txt").text.split("\n") data += requests.get(root + "amazon_cells_labelled.txt").text.split("\n") data += requests.get(root +...
178297
from credmark.cmf.model import Model @Model.describe( slug='contrib.neilz', display_name='An example of a contrib model', description="This model exists simply as an example of how and where to \ contribute a model to the Credmark framework", version='1.0', developer='neilz.eth', outpu...
178302
from .dataclasses import Skill, Card from .string_mgr import DictionaryAccess from typing import Callable, Union, Optional from collections import UserDict from .skill_cs_enums import ( ST, IMPLICIT_TARGET_SKILL_TYPES, PERCENT_VALUE_SKILL_TYPES, MIXED_VALUE_SKILL_TYPES, ) VALUE_PERCENT = 1 VALUE_MIXED...
178305
from Voicelab.pipeline.Node import Node from parselmouth.praat import call from Voicelab.toolkits.Voicelab.VoicelabNode import VoicelabNode from Voicelab.toolkits.Voicelab.MeasurePitchNode import measure_pitch from scipy import stats import statistics class MeasureFormantPositionsNode(VoicelabNode): def __init__(...
178308
from unittest.mock import patch, ANY import numpy as np import cv2 from tasks import ( _download_image, ascii, candy, mosaic, the_scream, udnie, celeba_distill, face_paint, paprika ) IMAGE_URL = "image_url" IMAGE_NAME = "image_name" IMAGE_PATH = "image_path" IMAGE_IPFS_URL = "pinata_hash_123" METADATA_IPFS_URL = ...
178386
from binascii import hexlify import enum import re from . import bech32 PREFIXES = [ "addr", "addr_test", "script", "stake", "stake_test" # -- * Hashes , "addr_vkh", "stake_vkh", "addr_shared_vkh", "stake_shared_vkh" # -- * Keys for 1852H , "addr_vk", ...
178430
import vertica_sdk import urllib.request import time class validate_url(vertica_sdk.ScalarFunction): """Validates HTTP requests. Returns the status code of a webpage. Pages that cannot be accessed return "Failed to load page." """ def __init__(self): pass def setup(self, server_...
178449
import functools from flask import abort, request from flask_stupe import marshmallow __all__ = [] if marshmallow: def _load_schema(schema, json): try: return schema.load(json) except marshmallow.exceptions.ValidationError as e: abort(400, e.messages) def schema_req...
178492
import collections.abc import enum import os from typing import ( TYPE_CHECKING, Annotated, Any, AsyncGenerator, Optional, Union, ) import aiohttp import inflection import numpy as np import pandas as pd import pydantic import structlog import uplink import uplink.converters from pandera.decora...
178510
from heapq import heappush ,heappop, heapify ,_heapify_max from typing import Union # Running scalar median # Ack: https://medium.com/mind-boggling-algorithms/streaming-algorithms-running-median-of-an-array-using-two-heaps-cd1b61b3c034 def med(s,x:Union[float,int]=None)->dict: """ Running median :param x...
178535
from dynamicserialize.dstypes.com.raytheon.uf.common.datastorage.records import AbstractDataRecord class ByteDataRecord(AbstractDataRecord): def __init__(self): super(ByteDataRecord, self).__init__() self.byteData = None def getByteData(self): return self.byteData def setByteDat...
178582
import torch from torch import nn import numpy as np from collections import OrderedDict from torch.utils.data import DataLoader from torch.utils.data import Sampler from contextlib import nullcontext import yaml from yaml import SafeLoader as yaml_Loader, SafeDumper as yaml_Dumper import os,sys from tqdm import tqdm...
178584
from .plates import ( get_plate_class, Plate96, Plate384, Plate1536, Plate2x4, Plate4ti0960, Plate4ti0130, PlateLabcyteEchoLp0200Ldv, PlateLabcyteEchoP05525Pp, Trough8x1 )
178588
import numpy as np from scipy import ndimage ''' See paper: Sensors 2018, 18(4), 1055; https://doi.org/10.3390/s18041055 "Divide and Conquer-Based 1D CNN Human Activity Recognition Using Test Data Sharpening" by <NAME> & <NAME> This code loads and sharpens UCI HAR Dataset data. UCI HAR Dataset data can be download...
178597
from subdaap.models import Server from daapserver.utils import generate_persistent_id from daapserver import provider import logging # Logger instance logger = logging.getLogger(__name__) class Provider(provider.Provider): # SubSonic has support for artwork. supports_artwork = True # Persistent IDs a...
178704
from paver.easy import sh import time import yaml from tests.util import clean, invoke_drkns def test_check(): clean() output = invoke_drkns('nominalcase', 'check') assert (len(output) == 0) def test_list(): clean() output = invoke_drkns('nominalcase', 'list') assert(len(output) > 6) a...
178828
import pytest import numpy as np from synthpop.census_helpers import Census from synthpop import categorizer as cat import os @pytest.fixture def c(): return Census('bfa6b4e541243011fab6307a31aed9e91015ba90') @pytest.fixture def acs_data(c): population = ['B01001_001E'] sex = ['B01001_002E', 'B01001_026...
178849
from .Exceptions import BFSyntaxError, BFSemanticError from .Token import Token from .General import is_token_literal class Parser: """ Used to easily iterate tokens """ def __init__(self, tokens): self.tokens = tokens self.current_token_index = 0 # parsing tokens def current_...
178881
from __future__ import absolute_import from __future__ import print_function from __future__ import division from . import verilog __intrinsics__ = ('set_header', 'get_header', 'set_global_offset', 'set_global_addrs', 'set_global_addr_map', 'write_global_addr_map', 'load_global_ad...
178908
from sys import stdin f, = map(float, stdin.readline().strip().split()) print "%.3lf" % (5*(f-32)/9)
178912
for __ in range(int(input())): N,A,B,C = map(int,input().split( )) if A+C >= N and B>=N: print("YES") else: print("NO")
178958
import os from cupy.testing._pytest_impl import is_available, check_available if is_available(): import pytest _gpu_limit = int(os.getenv('CUPY_TEST_GPU_LIMIT', '-1')) def gpu(*args, **kwargs): return pytest.mark.gpu(*args, **kwargs) def cudnn(*args, **kwargs): return pytest.mark....
178974
import abc class AbstractRateCounter(metaclass=abc.ABCMeta): @abc.abstractmethod def get(self, scope): raise NotImplementedError() @abc.abstractmethod def increment(self, scope, delta): raise NotImplementedError() @abc.abstractmethod def increment_and_get(self, scope, delta):...
178992
from nnet.models.srl import * from nnet.run.runner import * from nnet.ml.voc import * from nnet.run.srl.run import * from nnet.run.srl.util import * from nnet.run.srl.decoder import * from functools import partial from nnet.run.srl.read_dependency import get_adj import nnet.run.srl.conll09_evaluation.eval def make_l...
179112
from __future__ import absolute_import from __future__ import division from __future__ import print_function from atvgnet import *
179150
import unittest import parameterized import numpy as np from rlutil.envs.tabular_cy import q_iteration, tabular_env from rlutil.envs.tabular import q_iteration as q_iteration_py class QIterationTest(unittest.TestCase): def setUp(self): self.env = tabular_env.CliffwalkEnv(num_states=3, transition_noise=0.01) ...
179236
from cartoframes.viz import popup_element from cartoframes.viz.popup import Popup from cartoframes.viz.popup_list import PopupList popup_list = PopupList({ 'click': [popup_element('value_1'), popup_element('value_2')], 'hover': [popup_element('value_1'), popup_element('value_3')] }) class TestPopupList(object): ...
179269
from ._version import __version__ from ._rwlock import RWLock as RWLock from ._streams import ( BufferedReceiveStream as BufferedReceiveStream, TextReceiveStream as TextReceiveStream, ) from ._multi_cancel import MultiCancelScope as MultiCancelScope from ._service_nursery import open_service_nursery as open_se...
179291
import numpy as np raw = np.load('data/training_data_bounty_attack_mobilenet.npy') converted_data = [] for data in raw: # data[0] if data[1] == [0,0,0,0]: data[1] = [0,0,0,0,1] else: data[1].append(0) if data[2] == [0,0]: data[2] = [0,0,1] else: data[2].append(0) ...
179299
from direct.distributed.DistributedCartesianGridAI import DistributedCartesianGridAI from direct.directnotify import DirectNotifyGlobal from pirates.world.DistributedGameAreaAI import DistributedGameAreaAI from pirates.world.InteriorAreaBuilderAI import InteriorAreaBuilderAI from pirates.world.WorldGlobals import * cl...
179320
from dataclasses import dataclass, InitVar from typing import Any @dataclass(unsafe_hash=True) class CoaxialControlIOStatus: speaker: bool = False white_light: bool = False api_response: InitVar[Any] = None def __post_init__(self, api_response): if api_response is not None: self.s...
179419
import tensorflow as tf from keras import backend as K from tensorflow.keras.models import Model from tensorflow.keras.layers import Conv3D, MaxPooling3D, UpSampling3D, concatenate, Activation from tensorflow.keras.optimizers import Adam K.set_image_data_format("channels_last") # Set the image shape to have the channel...
179456
from django.dispatch import Signal """ When an xform is received, either from posting or when finished playing. """ xform_received = Signal(providing_args=["form"]) """ When a form is finished playing (via the SMS apis) """ sms_form_complete = Signal(providing_args=["session_id", "form"])
179533
import torch import torch.nn as nn #from torch.autograd import Function def lovasz_grad(gt_sorted): """ Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper """ p = len(gt_sorted) gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union...
179614
from typing import List from unittest import mock from uuid import UUID import pytest from sqlalchemy.orm.exc import NoResultFound from orchestrator.db import ResourceTypeTable, SubscriptionTable, WorkflowTable, db, transactional from orchestrator.targets import Target def test_transactional(): def insert_wf(st...
179636
import torch import torch.nn as nn import torch.nn.functional as F from layers import GraphConvolution from ...modules.prediction.classification.link_prediction.ConcatFeedForwardNNLayer import ( ConcatFeedForwardNNLayer, ) from ...modules.prediction.classification.link_prediction.ElementSumLayer import ElementSum...
179651
from PyQt5.QtWidgets import * from PyQt5.QtGui import QIcon, QPalette, QColor, QPixmap from PyQt5.QtCore import * class view_case_ui(QMainWindow): def __init__( self, problem_path, parent=None ): super(view_case_ui, self).__init__(parent) self.button_mode = 1 self.problem_path = problem_path self...
179690
from Geometry.MTDGeometryBuilder.mtdParameters_cfi import mtdParameters from Configuration.ProcessModifiers.dd4hep_cff import dd4hep dd4hep.toModify(mtdParameters, fromDD4hep = True)
179750
import copy import unittest import os import shutil from matador.config import load_custom_settings, set_settings from matador.config.config import DEFAULT_SETTINGS DUMMY_SETTINGS = { "mongo": {"host": "blah", "port": 666}, "plotting": {"style": "matador"}, "this_is_a_test": {True: "it is"}, "run3": { ...
179771
from django.test import TestCase from django.core.urlresolvers import reverse from classifieds.tests.test_views import FancyTestCase class TestAdBrowsing(FancyTestCase): fixtures = ['users', 'categories', 'ads'] def setUp(self): self.client.login(username='user', password='<PASSWORD>') def test...
179817
import talib._ta_lib as _ta_lib from ._ta_lib import __TA_FUNCTION_NAMES__ for func_name in __TA_FUNCTION_NAMES__: globals()[func_name] = getattr(_ta_lib, "stream_%s" % func_name)
179903
import torch.nn as nn import torch import math class NoSkipBertSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.drop...
179911
import asyncio from zeroservices.backend.mongodb import MongoDBCollection from . import _BaseCollectionTestCase from ..utils import TestCase, _create_test_resource_service, _async_test try: from unittest.mock import Mock except ImportError: from mock import Mock class MongoDBCollectionTestCase(_BaseCollect...
179916
import tensorflow as tf def get_vectors_norm(vectors): transposed = tf.transpose(vectors) v_mag = tf.sqrt(tf.math.reduce_sum(transposed * transposed, axis=0)) return tf.transpose(tf.math.divide_no_nan(transposed, v_mag)) class InnerAngleRepresentation: def __call__(self, p1s: tf.Tensor, p2s: tf.Tens...
179918
import sys import contextlib import functools import ir_measures from ir_measures import providers, measures, Metric from ir_measures.providers.base import Any, Choices, NOT_PROVIDED class TrectoolsProvider(providers.Provider): """ trectools https://github.com/joaopalotti/trectools :: @inproceeding...
180002
from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify, make_response from app.users.models import Users, UsersSchema from werkzeug.security import generate_password_hash, check_password_hash from flask_restful import Resource, Api import flask_restful import jwt from jwt import ...
180034
import jax from evosax import Strategies from evosax.problems import ClassicFitness def test_strategy_ask(strategy_name): # Loop over all strategies and test ask API rng = jax.random.PRNGKey(0) popsize = 20 strategy = Strategies[strategy_name](popsize=popsize, num_dims=2) params = strategy.default...
180043
from abc import ABCMeta, abstractmethod class WordVectorWrapper: __metaclass__ = ABCMeta def __init__(self, w2v_model): self.w2v_model = w2v_model self.vocab = self.get_vocab() self.word_vector_shape = self.get_word_vector_shape() @abstractmethod def get_vocab(self): ...
180046
import json from datetime import date, datetime import requests from .utilities import test_utility def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError ("Type %s not serializabl...
180059
import pytest from regcore_read.views import search_utils def inner_fn(request, search_args): # We'd generally return a Response here, but we're mocking return search_args @pytest.mark.parametrize('page_size', ('-10', '0', '200', 'abcd', '---')) def test_invalid_page_size(page_size, rf): """Invalid pag...
180084
import modelindex import pytest from modelindex import Metadata from modelindex.models.Collection import Collection from modelindex.models.CollectionList import CollectionList from modelindex.models.Model import Model from modelindex.models.ModelList import ModelList from modelindex.models.Result import Result from mod...
180109
class PrefixStorage(object): """Storage for store information about prefixes. >>> s = PrefixStorage() First we save information for some prefixes: >>> s["123"] = "123 domain" >>> s["12"] = "12 domain" Then we can retrieve prefix information by full key (longest prefix always win): >...
180146
from django.conf.urls import url from django.views.i18n import JavaScriptCatalog from finder import views urlpatterns = [ url(r'^jsi18n/$', JavaScriptCatalog.as_view(packages=['finder']), name='javascript-catalog'), url(r'^setlang/$', views.set_language, name='set_language'), url(r'^api/$', views.api, nam...
180154
import rm64 encoders = rm64.encoders for encoder in encoders: encoder["case"] = "mixedcase"
180162
import torch mapping = {} def register(name): def _thunk(func): mapping[name] = func return func return _thunk @register("rmsprop") def rmsprop(): return torch.optim.RMSprop @register("adam") def adam(): return torch.optim.Adam def get_optimizer_func(name): """ If you wa...
180177
import numpy as np import torch from ..callback.progressbar import ProgressBar from ..common.tools import restore_checkpoint,model_device from ..common.tools import summary from ..common.tools import seed_everything from ..common.tools import AverageMeter from torch.nn.utils import clip_grad_norm_ from pybert.train.met...
180217
import taco.common.exceptions class SQSWrapperException(taco.common.exceptions.DataDictException): pass class SQSClientException(SQSWrapperException): def __init__(self, message='SQS client error', data_dict=None, exc=None): super().__init__(message, data_dict=data_dict, exc=exc) class SendMessag...
180228
import ujson class TestAccount: def test_get_account_without_auth(self, test_server): res = test_server.get("/account") assert res.status_code == 401 def test_get_info(self, test_server, create_account_jwt): res = test_server.get( "/account", headers={"Authorization": f"Be...
180243
import json import time from pybbn.graph.dag import Bbn from pybbn.pptc.inferencecontroller import InferenceController def do_it(join_tree): InferenceController.reapply(join_tree, {0: [0.5, 0.5]}) with open('singly-bbn.json', 'r') as f: s = time.time() bbn = Bbn.from_dict(json.loads(f.read())) e = ...
180249
from .changesets import _ChangesetContext from .meta import ConfigManagerSettings from .persistence import ConfigPersistenceAdapter, YamlReaderWriter, JsonReaderWriter, ConfigParserReaderWriter from .schema_parser import parse_config_schema from .sections import Section from .utils import _get_persistence_adapter_for ...
180307
import os import argparse import socket from id_driver import IDDriver print("NAAL_FPGA board start") parser = argparse.ArgumentParser( description='Generic script for running the ID Extractor on the ' + 'FPGA board.') # Socket communication arguments parser.add_argument( '--host_ip', type=str, default='...
180318
from collections import defaultdict from math import exp, ceil from typing import List from jchord.midi import MidiNote # Notes separated by less than this much belong to one chord MIN_SEP_INTERVAL = 0.1 # Bucket size for the KDE algorithm KDE_BUCKETS_PER_SECOND = 1 / MIN_SEP_INTERVAL def kernel_defau...
180322
import logging from functools import partial import cv2 import os import json from collections import defaultdict import numpy as np import pandas as pd import torch from tensorboardX import SummaryWriter from torch.utils.data import DataLoader from evaluation.inception import InceptionScore from sg2im.data.dataset_par...
180361
from .warmup import WarmupLRScheduler class Linear(WarmupLRScheduler): r""" After a warmup period during which learning rate increases linearly between 0 and the start_lr, The decay period performs :math:`\text{lr}=\text{start_lr}\times \dfrac{\text{end_iter}-\text{num_iter}}{\text{end_iter}-\text...
180410
from inspect import getfile, getsourcelines from sys import stderr from types import FunctionType def print_function_context(f: FunctionType) -> None: name, file, (source, source_line_number) = f.__name__, getfile(f), getsourcelines(f) print(f"Function '{name}' located in {file} at line {source_line_number}"...
180450
import os import time import pickle import random import numpy as np from PIL import Image import torchvision.transforms as transforms from utils import cv_utils from data.dataset import DatasetBase class AusDataset(DatasetBase): def __init__(self, opt, is_for_train): super(AusDataset, self).__init__(opt,...
180510
import matplotlib.pyplot as plt import numpy as np import torch import cv2 import os def find_card(I): # 识别出车牌区域并返回该区域的图像 [y, x, z] = I.shape # y取值范围分析 Blue_y = np.zeros((y, 1)) for i in range(y): for j in range(x): # 蓝色rgb范围 temp = I[i, j, :] if (I[i, j...
180600
t=int(input()) for i in range(t): s=int(input()) m=s%12 if m==1: print(s+11,'WS') elif m==2: print(s+9,'MS') elif m==3: print(s+7,'AS') elif m==4: print(s+5,'AS') elif m==5: print(s+3,'MS') elif m==6: print(s+1,'WS') elif m==7: ...
180609
import numpy as np from ..base import Parameter from .optimizer import BaseOptimizer from benderopt.utils import logb from .random import RandomOptimizer class ParzenEstimator(BaseOptimizer): """ Parzen Estimator This estimator is largely inspired from TPE and hyperopt. https://papers.nips.cc/paper/4443-...
180635
import codecs from os import path from ncbi_genome_download.summary import SummaryReader def open_testfile(fname): return codecs.open(path.join(path.dirname(__file__), fname), 'r', 'utf-8') def test_bacteria_ascii(): ascii_file = open_testfile('partial_summary.txt') reader = SummaryReader(ascii_file) ...
180675
import re import tiles # REGEXs for global/clock signals # Globals including spine inputs, TAP_DRIVE inputs and TAP_DRIVE outputs global_spine_tap_re = re.compile(r'R\d+C\d+_[HV]P[TLBR]X(\d){2}00') # CMUX outputs global_cmux_out_re = re.compile(r'R\d+C\d+_[UL][LR]PCLK\d+') # CMUX inputs global_cmux_in_re = re.compile...
180710
from django.test import TestCase from django.urls import reverse class FilebrowserAnonymousTestCase(TestCase): def test_browse(self): url = reverse("fb_browse") response = self.client.get(url) self.assertEqual(302, response.status_code) self.assertEqual("/admin/login/?next=" + url,...
180744
from base import View, TemplateView, RedirectView from dates import (ArchiveIndexView, YearArchiveView, MonthArchiveView, WeekArchiveView, DayArchiveView, TodayArchiveView, DateDetailView) from detail import DetailView from edit import FormView, ...
180766
from collections import namedtuple from collections import defaultdict from biicode.common.model.brl.cell_name import CellName from biicode.common.model.symbolic.block_version import BlockVersion from biicode.common.utils.serializer import DictDeserializer, SetDeserializer from biicode.common.model.brl.block_cell_name...
180776
import os import csv from src import * def exists_song(csv_letter, artist_url, song_url): """ Checks if a song exists in a given CSV given the artist and song url. :param csv_letter: CSV letter in order to identify which CSV to get. :param artist_url: Artist AZLyrics URL. :param song_url: Song AZ...
180793
import math import torch from HyperSphere.BO.utils.normal_cdf import norm_cdf def norm_pdf(x, mu=0.0, var=1.0): return torch.exp(-0.5 * (x-mu) ** 2 / var)/(2 * math.pi * var)**0.5 def expected_improvement(mean, var, reference): std = torch.sqrt(var) standardized = (-mean + reference) / std return (std * norm_...
180803
from infraboxcli.dashboard import local_config from infraboxcli.log import logger def list_remotes(args): if args.verbose: remotes = local_config.get_all_remotes() msg = '\n: '.join(remotes) logger.info('Remotes:') logger.log(msg, print_header=False)
180825
from Queue import Queue def evaluate_rpn(tokens): stk = [] while not tokens.empty(): token = tokens.get() if is_operand(token): stk.append(token) else: val0, val1 = stk.pop(), stk.pop() num = eval(val1 + token + val0) stk.append(str(num...
180968
from django.contrib import admin from . models import AsnListModel, AsnDetailModel admin.site.register(AsnListModel) admin.site.register(AsnDetailModel)
180981
from distutils.version import LooseVersion import numpy as np from numpy.testing import assert_allclose, assert_array_equal import pytest import scipy.spatial.distance import tensorflow as tf from .. import losses def test_dice(): x = np.zeros(4) y = np.zeros(4) out = losses.dice(x, y, axis=None).numpy(...
181063
from matplotlib import pyplot as plt from vis_utils.vis_utils import draw_bounding_box_on_image from PIL import Image def vis_datum_mask(dataset): datum = dataset.random_datum() fig = plt.figure() fig.add_subplot(1, 2, 1) plt.axis('off') plt.imshow(datum.image) fig.add_subplot(1, 2, 2) plt...
181100
class A: def spam(self): print('A.spam') class B(A): def spam(self): print('B.spam') super().spam() # Call parent spam() class C: def __init__(self): self.x = 0 class D(C): def __init__(self): super().__init__() self.y = 1 d = D() print(d.y) class Bas...
181143
import unittest from checkov.common.models.enums import CheckResult from checkov.terraform.checks.resource.aws.RedshiftClusterKMSKey import check import hcl2 class TestRedshiftClusterKMSKey(unittest.TestCase): def test_failure(self): hcl_res = hcl2.loads(""" resource "aws_redshift_cluste...
181144
import os class CFFile(object): def __init__(self, path, size): self.path = path self.tell_pos = 0 self.size = size self.gen_file() def gen_file(self): with open(self.path, 'w') as f: f.seek(self.size - 1) f.write('\x00') def write(self, da...
181183
from os.path import join, isfile, expanduser from os import listdir from simple_NER.settings import RESOURES_DIR def resolve_resource_file(res_name, lang="en-us"): """Convert a resource into an absolute filename. Resource names are in the form: 'filename.ext' or 'path/filename.ext' The system wil lo...
181218
import time import numpy as np import torch from torch.autograd import Variable from torch.nn import Parameter from torch.utils.data.sampler import SubsetRandomSampler from data_loader import libsvm_dataset from thrift_ps.ps_service import ParameterServer from thrift_ps.client import ps_client from thrift.transport...
181220
import pytest from butterfree.clients import SparkClient from butterfree.hooks.schema_compatibility import SparkTableSchemaCompatibilityHook class TestSparkTableSchemaCompatibilityHook: @pytest.mark.parametrize( "table, database, target_table_expression", [("table", "database", "`database`.`table...