id
stringlengths
3
8
content
stringlengths
100
981k
9918625
import json import os from pprint import pprint import pytest from thumbtack import utils def test_find_library_support(test_client): """ GIVEN a Thumbtack Flask application client WHEN the '/supported' page is requested (GET) THEN check that the page shows which libraries it can check """ ...
9918626
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from le_utils.constants import format_presets from kolibri.core.content import hooks as content_hooks from kolibri.plugins import KolibriPluginBase from kolibri.plugins.hooks import register_hook cla...
9918692
MAX_STRLEN = 150 # default max length for char fields MAX_TXTLEN = 2000 # default max length for text fields
9918712
from unittest.mock import patch, Mock from opnsense_cli.commands.plugin.haproxy.lua import lua from opnsense_cli.tests.commands.base import CommandTestCase class TestHaproxyLuaCommands(CommandTestCase): def setUp(self): self._api_data_fixtures_reconfigure_OK = { "status": "ok" } ...
9918716
import pandas as pd from reamber.sm.lists.notes.SMHitList import SMHitList from tests.test.sm.test_fixture import sm_mapset def test_type(sm_mapset): assert isinstance(sm_mapset[0].hits, SMHitList) assert isinstance(sm_mapset[0].hits.df, pd.DataFrame) def test_df_names(sm_mapset): assert {'offset', 'col...
9918734
import os baseLoc = os.path.dirname(os.path.realpath(__file__)) + '/' from gimpfu import * import sys sys.path.extend([baseLoc + 'gimpenv/lib/python2.7', baseLoc + 'gimpenv/lib/python2.7/site-packages', baseLoc + 'gimpenv/lib/python2.7/site-packages/setuptools', baseLoc + 'face-parsing-PyTorch']) f...
9918738
import numpy as np v1 = 0 v2 = 1 if v1: totstring = "#include \"legquadrules.h\" \n#include <string.h> \n " for ii in xrange(2,200): name = "legrules/quad{0}.dat".format(ii) dat = np.loadtxt(name,skiprows=1,dtype=str) #print dat w = dat[:,1] p = dat[:,0] #w =...
9918752
description = 'Virtual STRESS-SPEC instrument' group = 'basic' includes = [ 'system', 'sampletable', 'monochromator', 'detector', 'primaryslit', 'slits', 'reactor' ] sysconfig = dict( datasinks = ['caresssink', 'yamlsink'], ) devices = dict( m1_foc = device('nicos.devices.generic.VirtualMotor', ...
9918835
from django.shortcuts import render # Create your views here. def single_view(request): u""" View for representing single timezone information """ return render(request, 'single.html') def manage_form(request): u""" View to manage TimeZones using ordinary add form """ if request.method == 'POST': ...
9918915
from datetime import datetime, timedelta from flask import current_app from sqlalchemy.sql import and_ from app.models import RoleToUser, User, Timeclock, Role, Shift2 from app.caches import CronTimeclockNotificationSmsCache # Margin of error. Allows one skipped cron. SEARCH_WINDOW_MINUTES = 2 def run_cron_timeclo...
9918926
from pydantic import BaseModel # ---------------- login schemas -------------------- # class Token(BaseModel): access_token: str token_type: str class TokenData(BaseModel): email: str = None expire: str = None issue_time: str = None # ---------------- login schemas -------------...
9918954
from sys import stderr import subprocess as sp import re class AdbWrapper(object): def __init__(self, adbbin='adb', devsel=(), debug=None): self.adbbin = adbbin self.devsel = tuple(devsel) self.debug = debug def get_version(self): try: s, output = sp.getstatusoutp...
9918993
import raccoon raccoon.go_up() raccoon.go_left(3) raccoon.go_right(6) raccoon.go_left(3) raccoon.go_up(2) raccoon.go_left(2) raccoon.go_right(4) raccoon.go_left(2) raccoon.go_up(2) raccoon.go_left() raccoon.go_right(2) raccoon.go_left() raccoon.go_up()
9919057
from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension setup( name='gauss_psf_cuda', ext_modules=[ CUDAExtension('gauss_psf_cuda', [ 'gauss_psf_cuda.cpp', 'gauss_psf_kernel.cu', ]), ], cmdclass={ 'build_ext': Buil...
9919099
import numpy as np #Inputs: #Opcion - 1 constraints # nc = 10 # y0 = np.ones ([nc,1]) # normalizacion # y = [y0] # alpha = np.array ([1.0]) #opcion - 2 constraints moneda # y1= np.array ([[0.0],[1.0] ]) # nc = len(y1) #cantidad de caras # y0 = np.ones ([nc,1]) # normalizacion # alpha = np.array ([1.0...
9919127
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import argparse import cv2 import numpy as np from glob import glob import matplotlib.pyplot as plt from copy import copy # config max_dim = 128 channel = 3 style_weight=5e-1 content_weight=1e4 total_variation_weight=30 epochs = 10 steps_per_epoch = 100 def load...
9919133
from transducer._util import UNSET, coroutine from transducer.infrastructure import Reduced from transducer.reducers import sending @coroutine def transduce(transducer, target=UNSET): reducer = transducer(sending()) accumulator = target if target is not UNSET else reducer.initial() try: while True:...
9919142
import language_tool_python def download_tool(): return language_tool_python.LanguageTool('ru') def find_mistakes(s, tool): return tool.check(s) def correct(s, matches): return language_tool_python.utils.correct(s, matches) def print_match(match): context = match.context + "\n\r" error_flag ...
9919155
import numpy as np import os.path as osp from ..registry import PIPELINES from edit.utils import imflip_, bboxflip_, img_shelter, flowflip_ @PIPELINES.register_module() class Corner_Shelter(object): def __init__(self, keys, shelter_ratio=0.1, black_ratio = 0.75): self.keys = keys self.shelter_rati...
9919167
from flask import Flask from flask import request from flask import jsonify from flask_cors import CORS import os import sys import pandas as pd import numpy as np import joblib import pickle sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from utils.preprocess_data import remove_time_sta...
9919198
import os import salt.modules.file as file_ import salt.modules.heat import salt.modules.win_file as win_file import salt.states.heat as heat import salt.utils.platform import salt.utils.win_dacl as dacl import tests.unit.modules.test_heat from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock ...
9919255
from django.conf.global_settings import DEFAULT_FROM_EMAIL from django.contrib.auth.models import User from django.core.mail import send_mail __author__ = '<NAME>' def email_user(user, subject, message, sent_by=DEFAULT_FROM_EMAIL): if isinstance(user, User): to_email = user.email else: to_ema...
9919280
from __future__ import print_function import pickle import numpy as np import torch from torch import optim from model import TriMap from triplets import generate_triplets class Wrapper(object): def __init__(self, config): self.config = config def embed(self, embed_init=None, re...
9919343
import numpy as np from vectorhub.encoders.image.tfhub import InceptionResnet2Vec from ....test_utils import assert_encoder_works def test_test_inception_resnet_works(): model = InceptionResnet2Vec() assert_encoder_works(model, 1536, data_type='image')
9919355
import sys import os from setuptools import setup from setuptools import Extension from setuptools import find_packages version = '0.3.3' # Please update tox.ini when modifying dependency version requirements install_requires = [ ] dev_extras = [ 'nose', 'pep8', 'tox', 'aiounittest', ] docs_extras ...
9919371
import setuptools setuptools.setup( name="AutoROM", package_dir={"AutoROM": "src"}, packages=["AutoROM", "AutoROM.roms"], extras_require={"accept-rom-license": ["AutoROM.accept-rom-license"]}, entry_points={ "console_scripts": ["AutoROM=AutoROM:cli"], "ale_py.roms": ["AutoROM=AutoRO...
9919380
import os import torch import mir_eval import csv import argparse import pandas as pd import numpy as np from MSnet.utils import getlist_ADC2004, getlist_MIREX05, getlist_mdb, getlist_mdb_vocal, melody_eval, select_vocal_track, csv2ref from MSnet.MelodyExtraction import MeExt def main(data_dir, model_type, output_dir,...
9919451
import csv import scipy.misc from random import shuffle import cv2 from skimage.util import random_noise from numpy.random import uniform as random import numpy as np class data_handler(object): def __init__(self, validation_split = 0.2, batch_size = 128, left_and_right_images = False, root_path = '', left_right_o...
9919459
from matplotlib.pyplot import show from hcluster import pdist, linkage, dendrogram import numpy from numpy.random import rand X = rand(10,100) X[0:5,:] *= 2 Y = pdist(X) Z = linkage(Y) dendrogram(Z) show()
9919478
cube = lambda x: x**3 def fibonacci(n): if n == 0: return [] if n == 1: return [0] prev = 0 cur = 1 out = [prev, cur] for _ in range(n-2): prev, cur = cur, prev + cur out.append(cur) return out
9919495
from sqlobject import * from sqlobject.tests.dbtest import * ######################################## ## Unicode columns ######################################## class TestUnicode(SQLObject): count = IntCol(alternateID=True) col1 = UnicodeCol(alternateID=True, length=100) col2 = UnicodeCol(dbEncoding='lat...
9919526
import logging from lcc.data_manager.package_reader import PackageReader from lcc.entities.star import Star import unittest import numpy as np logging.basicConfig(level=logging.DEBUG) class TestDescriptors(unittest.TestCase): n_stars = 10 def setUp(self): self.descriptors = PackageReader.getClasse...
9919544
from collections import OrderedDict import copy import sys class obj(object): def __init__(self,d=None): if not(d is None): for a, b in d.items(): if isinstance(b, (list, tuple)): setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b]) ...
9919571
import random import numpy as np from .memory import Memory, TransitionBatch from .registry import register @register("simple") class SimpleMemory(Memory): """ Simple memory """ def __init__(self, hparams, worker_id): super(SimpleMemory, self).__init__(hparams, worker_id) self._memory = [] def add_sa...
9919616
from pathlib import Path from typing import List, Optional import joblib import torch from random import random from guacamol.goal_directed_generator import GoalDirectedGenerator # from guacamol.scoring_function import ScoringFunction from guacamol.utils.chemistry import canonicalize_list, canonicalize from joblib imp...
9919631
import dis from functools import lru_cache from types import CodeType from typing import FrozenSet from scalene.scalene_statistics import * class ScaleneFuncUtils: # We use these in is_call_function to determine whether a # particular bytecode is a function call. We use this to # distinguish between P...
9919636
from autosar.writer.writer_base import BaseWriter from autosar.writer.package_writer import PackageWriter from autosar.base import applyFilter import collections class WorkspaceWriter(BaseWriter): def __init__(self, version, patch, schema, packageWriter): super().__init__(version, patch) as...
9919641
import tvm import numpy as np from tvm.tensor_graph.core import compute, GraphTensor, GraphOp, ForwardGraph, \ BackwardGraph, GraphMutator, PyTIRGraph import tvm.tensor_graph.nn.functional as F from tvm.tensor_graph.nn.modules.loss import CELoss from tvm.tensor_graph.nn.modules.optimize im...
9919651
import inspect import textwrap from weakref import WeakSet from . import SeamlessBase from copy import deepcopy from .status import StatusReasonEnum cell_counter = 0 text_types = ( "text", "python", "ipython", "cson", "yaml", "str", "int", "float", "bool", ) text_types2 = ( "text", "python", "ipython", ...
9919675
import sys import signal import logging import webbrowser from Queue import Queue from datetime import datetime import gi gi.require_version('Gtk', '3.0') gi.require_version('AppIndicator3', '0.1') import notify2 from gi.repository import Gtk, AppIndicator3, GObject from apscheduler.schedulers.background import Bloc...
9919722
from tensorforce.agents import PPOAgent from helper.wrappers import ClientToEnv, DictToListFull, JSONable from ...templates import TensorforceAgent class TensorforcePPOAgent(TensorforceAgent): def __init__(self, observation_space, action_space, directory='./TensorforcePPOAgent/'): # Crea...
9919730
from panda3d.core import NodePath, TransparencyAttrib, LVecBase4f, LineSegs from simulator.services.services import Services from simulator.views.map.data.map_data import MapData from simulator.views.map.geometry.meshes.dynamic_voxel_mesh import DynamicVoxelMesh from simulator.views.map.geometry.meshes.static_voxel_me...
9919788
import hashlib import time import zlib from typing import List def get_word_list(filepath: str = "words.txt") -> List[str]: with open(filepath) as fp: return [line.strip() for line in fp] def test_hash_functions(hash_functions): t0 = time.time() words = get_word_list() t1 = time.time() p...
9919806
from typing import Dict, Set, Any def get_values_from_signatures(sigs) -> Dict[str, Set[Any]]: ksizes = set() scales = set() for sig in sigs: ksizes.add(sig.minhash.ksize) scales.add(sig.minhash.scaled) return { 'ksize': ksizes, 'scaled': scales, }
9919807
class Loan: def __init__(self, line: str): self.line = line.replace('"', '').replace("'", "").replace("\t", "") self.loan_id, self.member_id, self.loan_amnt, self.funded_amnt, self.funded_amnt_inv, self.term, \ self.int_rate, self.installment, self.grade, self.sub_grade, self.emp_title, sel...
9919827
from drifter_ml import classification_tests import joblib import pandas as pd import code def test(): df = pd.read_csv("data.csv") column_names = ["A", "B", "C"] target_name = "target" clf = joblib.load("model1.joblib") test_suite = classification_tests.ClassificationTests(clf, ...
9919911
import threading from .decorator import decorator LOCK = threading.RLock() @decorator def synchronized(f, *args, **kw): """ Synchronization decorator """ with LOCK: return f(*args, **kw) class SynchronizedType(type): def __new__(cls, clsname, bases, local): for name, item in local.it...
9919940
import torch from torch import nn ## NOTE: The implementation of SLDA was extended from: https://github.com/tyler-hayes/Deep_SLDA (retrieved: 17 Dec 2020) #################################################################################################################### class StreamingLDA(nn.Module): '''Stre...
9919957
import os, sys from intrinsic_qbert import QBERTTrainer import argparse def parse_args(): parser = argparse.ArgumentParser() # GoExplore params parser.add_argument('--resolution', '--res', type=float, default=16, help='Length of the side of a grid cell.') parser.add_argument('--use_scores', dest='use_...
9919962
import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''D-Link DIR-600M - Authentication Bypass''', "description": '''An issue was discovered on D-Link DIR-600M 3.02, 3.03, 3.04, and 3.06 devices. wan.htm can be accessed directly without authentication, whi...
9919976
import os import pandas as pd import rampwf as rw problem_title = 'Particle tracking in the LHC ATLAS detector' # A type (class) which will be used to create wrapper objects for y_pred Predictions = rw.prediction_types.make_clustering() # An object implementing the workflow workflow = rw.workflows.Clusterer() score_ty...
9919997
import sublime import os import re if sublime.platform() == "windows": from winreg import OpenKey, QueryValueEx, HKEY_LOCAL_MACHINE, KEY_READ PATTERN = re.compile(r""" (?P<quote>["']) (?P<quoted_var> \$ (?: [_a-z][_a-z0-9]* | \{[^}]*\} ) ) (?P=quote) | (?P<var> \$ (?: [_...
9920014
from distutils.core import setup from Cython.Build import cythonize import numpy as np setup( name = "features", ext_modules = cythonize("features.pyx"), include_dirs = [np.get_include()] )
9920034
import time import argparse import numpy as np import tensorflow as tf import preprocess.mnist as preprocess import utils from model import model_utils from model import imm print("==> parsing input arguments") flags = tf.app.flags ## Data input settings flags.DEFINE_boolean("mean_imm", True, "include Mean-IMM") fl...
9920035
import numpy as np import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams import theano from keras.layers.core import Layer class SampleBernoulli(Layer): """ Layer which samples a Bernoulli distribution whose statistics (mean, 'p') are given as inputs to the layer....
9920067
import importlib import logging import os import sys import traceback import matplotlib from matplotlib import cbook from matplotlib.backend_bases import _Backend _log = logging.getLogger(__name__) # NOTE: plt.switch_backend() (called at import time) will add a "backend" # attribute here for backcompat. def _get_...
9920077
from os import environ config = { 'SECRET_KEY': environ['SECRET_KEY'], 'DOMAIN_ROOT': environ['DOMAIN_ROOT'], # 'SERVER_NAME': f"auth.{environ['DOMAIN_ROOT']}", 'SQLALCHEMY_DATABASE_URI': environ['DATABASE_URL'], 'REDIS_URL': environ['REDIS_URL'], 'AUTH_GOOGLE': { 'consumer_key': environ...
9920088
from .cli import run from .socket_interface import ReceptorControl __all__ = ["run", "ReceptorControl"]
9920142
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import six import nixnet from nixnet import constants from nixnet import types def main(): interface1 = 'LIN1' interface2 = 'LIN2' database = 'NIXNET_exampleLDF' with nixnet.Fra...
9920146
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class NonMaxSuppression(Base): @staticmethod def export_nonmaxsupp...
9920164
from django.contrib import admin from django.urls import path, include, re_path from core import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index), path('cloud/', views.cloud), path('datasets/', views.datasets), path('models/', views.models), path('trials/', views.tr...
9920202
import requests from bs4 import BeautifulSoup from scibot.utils import log try: from urllib.parse import urlencode, quote except ImportError: from urllib import urlencode, quote # existing identifiers and rrids def existing_tags(target_uri, h): params = { 'limit':200, 'uri':target_uri, ...
9920215
import os import tempfile from test.integration.base import DBTIntegrationTest, use_profile from dbt.exceptions import CompilationException, DependencyException from dbt import deprecations class TestSimpleDependency(DBTIntegrationTest): def setUp(self): DBTIntegrationTest.setUp(self) self.run_sq...
9920246
def hsvToRGB(h, s, v): """Convert HSV color space to RGB color space @param h: Hue @param s: Saturation @param v: Value return (r, g, b) """ import math hi = math.floor(h / 60.0) % 6 f = (h / 60.0) - math.floor(h / 60.0) p = v * (1.0 - s) q = v * (1.0 - (f*s)) t =...
9920247
import warnings from typing import TYPE_CHECKING, Any, Dict, Optional, Union from valohai_cli.exceptions import APINotFoundError from valohai_cli.messages import error, info from valohai_cli.utils import walk_directory_parents from .paths import get_settings_file_name from .persistence import FilePersistence, Persist...
9920258
import factory from tenancy.models import Tenant, TenantGroup class TenantGroupFactory(factory.django.DjangoModelFactory): class Meta: model = TenantGroup id = factory.Sequence(lambda n: n) name = factory.LazyAttribute(lambda o: 'Tenant Group %i' % o.id) slug = factory.LazyAttribute(lambda o:...
9920265
from botocore import auth class SigV2ComputingAuth(auth.SigV2Auth): def calc_signature(self, request, params): if 'AWSAccessKeyId' in params: params['AccessKeyId'] = params['AWSAccessKeyId'] del params['AWSAccessKeyId'] return super(SigV2ComputingAuth, self).calc_signature(...
9920313
from rlbot.agents.base_agent import SimpleControllerState class Choice: def utility(self, bot) -> float: raise NotImplementedError def exec(self, bot) -> SimpleControllerState: raise NotImplementedError def reset(self): pass class UtilitySystem: def __init__(self, choices, ...
9920342
import tensorflow as tf def get_second_dimension(tensor): return tensor.get_shape().as_list()[1]
9920366
import unittest from sklearn.feature_extraction.text import TfidfVectorizer def get_tf_idf_vectors(corpus): tfidf_model = TfidfVectorizer() vector_list = tfidf_model.fit_transform(corpus).todense() return vector_list corpus = [ 'Data Science is an overlap between Arts and Science', 'Generally,...
9920378
import json from pathlib import Path base_dir = Path(__file__).parent schema_path = base_dir / "ptabApiV2.json" schema_doc = json.loads(schema_path.read_text()) from .model import *
9920404
from bs4 import BeautifulSoup import requests import string import re import json def scrape_data(topic_url): topic = {} topic['name'] = topic_url.getText() topic['count'] = None topic['companies'] = None topic['skills'] = None topic['topSkills'] = None if topic_url.has_attr('href'): ...
9920405
import shapely.wkb from geopyspark import get_spark_context from geopyspark.geotrellis.constants import LayerType, CellType from geopyspark.geotrellis.layer import TiledRasterLayer __all__ = ['euclidean_distance'] def euclidean_distance(geometry, source_crs, zoom, cell_type=CellType.FLOAT64): """Calculates the ...
9920410
from mpi4py import MPI import numpy as np from baselines.common import zipsame def mpi_moments(x, axis=0): x = np.asarray(x, dtype='float64') newshape = list(x.shape) newshape.pop(axis) n = np.prod(newshape,dtype=int) totalvec = np.zeros(n*2+1, 'float64') addvec = np.concatenate([x.sum(axis=axi...
9920466
import komand from .schema import CreateCaseObservableInput, CreateCaseObservableOutput, Component # Custom imports below from thehive4py.models import Case, CaseObservable import requests class CreateCaseObservable(komand.Action): def __init__(self): super(self.__class__, self).__init__( nam...
9920494
from setuptools import setup, find_packages setup(name="cobrame", version="0.0.9", author="<NAME> and <NAME>", url="https://github.com/SBRG/cobrame", install_requires=["sympy", "six", "Biopython", "cobra<=0.5.11", "pandas", "scipy", "numpy", "setuptools", "jsonschema"],...
9920525
from colossalai.context.parallel_context import ParallelContext from colossalai.core import global_context as gpc from colossalai.logging import get_dist_logger from colossalai.context import ParallelMode from .datasets.data_samplers import build_pretraining_data_loader from .datasets.builder import build_train_valid_t...
9920675
import KitNET as kit import numpy as np import pandas as pd import time ############################################################################## # KitNET is a lightweight online anomaly detection algorithm based on an ensemble of autoencoders. # For more information and citation, please see our NDSS'18 paper: Ki...
9920722
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class Geneve(Base): __slots__ = () _SDM_NAME = 'geneve' _SDM_ATT_MAP = { 'Version': 'geneve.header.version-1', 'Optionslen': 'geneve.header.optionslen-2', 'Flags': 'geneve.header.flags-3', 'Prot...
9920733
from utils import * class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, dropout=0.0, base_rnn=nn.LSTM, pretrained_embeddings=None, dropout_p=0.1): super(EncoderRNN, self).__init__() self.input_size = input_size #vocabulary size self.hidden_size = hidden_si...
9920747
import base64 import json import logging import os.path import pkg_resources import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager from .exceptions import SHCRegistrationError, SHCSessionError from .generate_cert import generate_certificate logger = l...
9920753
from rest_framework import serializers class IamportSmsCallbackSerializer(serializers.Serializer): imp_uid = serializers.CharField() merchant_uid = serializers.CharField()
9920787
import os from datetime import datetime from uuid import uuid4 import pandas as pd from h2o_wave import ui, Q, app, main from rainforest.config import N_SPECIES from rainforest.pann import load_pretrained_model, get_model_predictions_for_clip from rainforest.utils import show_references, get_candidates, get_annotatio...
9920788
import sys, imp, codecs, shlex, os, json, traceback, tempfile, subprocess, threading from . import util from .global_vars import * from .javascript_enhancements_settings import * class NodeJS(): def __init__(self, check_local = False): self.check_local = check_local self.node_js_path = "" if self.chec...
9920926
import warnings from scrapy.exceptions import ScrapyDeprecationWarning warnings.warn("Module `scrapy.contrib.spiders.crawl` is deprecated, " "use `scrapy.spiders.crawl` instead", ScrapyDeprecationWarning, stacklevel=2) from scrapy.spiders.crawl import *
9920929
from canvasapi.canvas_object import CanvasObject class Todo(CanvasObject): def __str__(self): return "Todo Item ({})".format(self.type)
9920936
import os from flask import Flask from okta import UsersClient from flask_bcrypt import Bcrypt from flask_oidc import OpenIDConnect from flask_sqlalchemy import SQLAlchemy from oauth2client.client import OAuth2Credentials app = Flask(__name__) app.config['SECRET_KEY'] = '6c9a0af7a220762b3ec7d435b3ff14a4' app.config[...
9920939
import json import random import requests from olipy.ia import Text from botfriend.bot import BasicBot from botfriend.model import Post class JunkMailBot(BasicBot): COLLECTION = "tednelsonjunkmail" def update_state(self): cutoff = self.model.last_state_update_time old_state = self.model.json...
9920973
import copy import json import logging import sys from datetime import datetime from multiprocessing import Process from types import FrameType from typing import Dict import pika.exceptions from pika.adapters.blocking_connection import BlockingChannel from src.alerter.alerter_starters import start_evm_node_alerter f...
9921009
import numpy as np import hyperparameters as hp class ActionMeta(type): def __init__(cls, name, bases, d): type.__init__(cls, name, bases, d) cls.action_to_num = dict() cls.num_to_action = dict() options = [True, False] counter = 0 for left in options: fo...
9921010
class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ answer =[] first_x = len(A) first_y = len(A[0]) for i in range(first_y): mid_answer = [] for j in range(first_x): ...
9921019
from hyperion.dust import SphericalDust import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from astropy import units as u from astropy import constants as constants dustfile = '/ufrc/narayanan/desika.narayanan/pd/hyperion-dust/dust_files/d03_3.1_6.0_A.hdf5' dust = SphericalDust(dustfile) mw_df_nu...
9921074
import pint u = pint.UnitRegistry() Q = u.Quantity c = 299792458 * u.meter / u.sec # the following is the same print(c.to('mph')) print(c.to('mile/hour')) rho = 62.4 * u.lb / u.foot**3 print(rho.to('kg/m**3')) Rg = Q(0.08206, 'L*atm/(mole*K)') print(Rg.to('J/mol/K')) import numpy as np R = 25 * u.feet L = 5 * u...
9921100
import time import tqdm import pandas import requests if __name__ == "__main__": website_url = "http://rebase.neb.com" methylations = ['Dam', 'Dcm', 'CpG', 'EcoBI', 'EcoKI'] columns = ['enzyme', 'req_seq', 'suppliers'] + methylations print("Getting enzyme list and suppliers...") html = requests.g...
9921133
from elasticsearch.exceptions import NotFoundError from kitsune.products.tests import ProductFactory, TopicFactory from kitsune.search.documents import WikiDocument from kitsune.search.tests import Elastic7TestCase from kitsune.wiki.tests import DocumentFactory, RevisionFactory class WikiDocumentSignalsTests(Elastic...
9921151
from __future__ import absolute_import, division, print_function from scitbx.rigid_body.proto.utils import \ center_of_mass_from_sites, \ T_as_X from scitbx import matrix import math class six_dof_alignment(object): def __init__(O, sites): O.pivot = center_of_mass_from_sites(sites=sites) O.normal = None...
9921155
import os import torch import math from torch import nn class PosEncoding(nn.Module): ''' Transformer-style positional encoding with wavelets ''' def __init__(self, d_model, max_len=1250): super().__init__() self.d_model = d_model pe = torch.zeros(max_len, d_model) posi...
9921168
from __future__ import absolute_import import pandas as pd import numpy as np import pyaf.ForecastEngine as autof import pyaf.Bench.TS_datasets as tsds def build_model(iPerf): b1 = tsds.load_ozone() df = b1.mPastData lEngine = autof.cForecastEngine() lEngine H = b1.mHorizon; # lEngine.mOpti...
9921187
import numpy as np class CategoricalCrossentropy: def __init__(self): self.epsilon = 1e-15 def __call__(self, y: np.ndarray, y_pred: np.ndarray) -> np.float64: return self.loss(y, y_pred) def loss(self, y: np.ndarray, y_pred: np.ndarray) -> np.float64: # Avoid division by zero ...
9921204
from django.forms import ModelForm from models import ErrorReport class ErrorReportForm(ModelForm): class Meta: fields = ('message', 'url', 'line_number',) model = ErrorReport