id
stringlengths
3
8
content
stringlengths
100
981k
29310
from haptyc import * from base64 import b64encode, b64decode import json class TestLogic(Transform): # # test_h1: Decodes base64, fuzzes using random_insert, Re-encodes base64 # Number of tests: 50 # @ApplyIteration(50) def test_h1(self, data, state): data = b64decode(data) ...
29327
import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim class Generator: def __init__(self, learning_rate=1e-4, num_blocks=6): self.learning_rate = learning_rate self.num_blocks = num_blocks def pelu(self, x): with tf.variable_scope(x.op.name + '_activation', initializer=tf.c...
29329
from vcs import vtk_ui from vcs.colorpicker import ColorPicker from vcs.vtk_ui import behaviors from vcs.VCS_validation_functions import checkMarker import vtk import vcs.vcs2vtk from . import priority import sys class MarkerEditor( behaviors.ClickableMixin, behaviors.DraggableMixin, priority.PriorityEditor):...
29330
from functools import wraps from typing import Any, Callable, TypeVar, cast from grpc import Call, RpcError from grpc.aio import AioRpcError from .exceptions import AioRequestError, RequestError from .logging import get_metadata_from_aio_error, get_metadata_from_call, log_error TFunc = TypeVar("TFunc", bound=Callabl...
29346
from spotdl import handle from spotdl import const from spotdl import downloader import os import sys const.args = handle.get_arguments(to_group=True) track = downloader.Downloader(raw_song=const.args.song[0]) track_title = track.refine_songname(track.content.title) track_filename = track_title + const.args.output_...
29397
import torch from torch.distributions import Uniform from rl_sandbox.constants import CPU class UniformPrior: def __init__(self, low, high, device=torch.device(CPU)): self.device = device self.dist = Uniform(low=low, high=high) def sample(self, num_samples): return self.dist.rsample...
29426
def countWord(word): count = 0 with open('test.txt') as file: for line in file: if word in line: count += line.count(word) return count word = input('Enter word: ') count = countWord(word) print(word, '- occurence: ', count)
29439
import json import pickle import re from copy import copy, deepcopy from functools import lru_cache from json import JSONDecodeError from os import system, walk, sep from abc import ABC, abstractmethod from pathlib import Path import time from subprocess import check_output from tempfile import NamedTemporaryFile from ...
29489
import random def get_random_bag(): """Returns a bag with unique pieces. (Bag randomizer)""" random_shapes = list(SHAPES) random.shuffle(random_shapes) return [Piece(0, 0, shape) for shape in random_shapes] class Shape: def __init__(self, code, blueprints): self.code = code self....
29501
import math import sys from fractions import Fraction from random import uniform, randint import decimal as dec def log10_floor(f): b, k = 1, -1 while b <= f: b *= 10 k += 1 return k def log10_ceil(f): b, k = 1, 0 while b < f: b *= 10 k += 1 return k def log10_...
29507
import glob import matplotlib.pyplot as plt import numpy as np import sys plt.ion() data_files = list(glob.glob(sys.argv[1]+'/mnist_net_*_train.log')) valid_data_files = list(glob.glob(sys.argv[1]+'/mnist_net_*_valid.log')) for fname in data_files: data = np.loadtxt(fname).reshape(-1, 3) name = fname.split('/')[...
29523
import math import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate import pdb import sys from ilqr.vehicle_model import Model from ilqr.local_planner import LocalPlanner from ilqr.constraints import Constraints class iLQR(): def __init__(self, args, obstacle_bb, verbose=False): ...
29556
import matplotlib.pyplot as plt import numpy as np from gpar.regression import GPARRegressor from wbml.experiment import WorkingDirectory import wbml.plot if __name__ == "__main__": wd = WorkingDirectory("_experiments", "synthetic", seed=1) # Create toy data set. n = 200 x = np.linspace(0, 1, n) n...
29574
import unittest import io from unittest import mock from tests.lib.utils import INSPECT from custom_image_cli.validation_tool import validation_helper from custom_image_cli.validation_tool.validation_models.validation_models import \ ImageDetail, ImageManifest, EmrRelease class TestValidationHelper(unittest.TestC...
29599
import importlib import sys import pituophis # check if the user is running the script with the correct number of arguments if len(sys.argv) < 2: # if not, print the usage print('usage: pituophis [command] cd [options]') print('Commands:') print(' serve [options]') print(' fetch [url] [options]')...
29642
import ConfigParser from datetime import datetime import os import sys import numpy as np import pandas as pd import utils.counts import utils.counts_deviation __author__ = '<NAME>' # This script finds the days with the greatest deviation from some reference value (such as hourly means or medians) if __name__ == '_...
29643
from django.http import HttpResponse class HttpResponseNoContent(HttpResponse): status_code = 204
29648
import tensorflow as tf i = tf.compat.v1.constant(0, name="Hole") c = lambda i: tf.compat.v1.less(i, 10) b = lambda i: tf.compat.v1.add(i, 1) r = tf.compat.v1.while_loop(c, b, [i], name="While")
29707
import base64 import json import os import tempfile import uuid import zipfile from io import BytesIO import werkzeug from flask import Blueprint, jsonify, request from ..config import get_config from ..dataset import convert_ndarray_to_image, import_csv_as_mdp_dataset from ..models.dataset import Dataset, DatasetSch...
29714
from prefect import task, Flow, Parameter from prefect.tasks.prefect import StartFlowRun from prefect.storage import GitHub with Flow("token-test") as flow: StartFlowRun(project_name="testing", flow_name="flow_must_fail")() flow.storage = GitHub(repo="kvnkho/demos", path="/prefect/token_test.py") flow.register("t...
29725
import numpy as np from scipy import stats import pandas as pd from sklearn.cross_decomposition import PLSRegression def standardize_vector(v, center=True, scale=False): if center: v = v - np.mean(v) if scale: if np.std(v) == 0: return v else: return (v + 0.0)...
29732
import os import sys import os.path as osp from contextlib import contextmanager ############################################################ # Setup path def add_path(path): if path not in sys.path: sys.path.insert(0, path) curdir = osp.dirname(__file__) lib_path = osp.join(curdir, '..', 'lib') add_...
29750
from tkinter.commondialog import Dialog ERROR = 'error' INFO = 'info' QUESTION = 'question' WARNING = 'warning' ABORTRETRYIGNORE = 'abortretryignore' OK = 'ok' OKCANCEL = 'okcancel' RETRYCANCEL = 'retrycancel' YESNO = 'yesno' YESNOCANCEL = 'yesnocancel' ABORT = 'abort' RETRY = 'retry' IGNORE = 'ignore' OK = 'ok' CANCEL...
29760
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from board.feeds import EventFeed from board.views import IndexView, ServiceView admin.autodiscover() urlpatterns = patterns('', url(r'^$', IndexView.as_view(), name='index'), url(r'^services/(?P<slug>[-\w]+)$', Serv...
29767
from __future__ import ( annotations, ) import logging import warnings from pathlib import ( Path, ) from typing import ( TYPE_CHECKING, Optional, Type, TypeVar, Union, ) from .object import ( Object, ) if TYPE_CHECKING: from .config import ( Config, ) logger = loggin...
29769
from optparse import OptionParser import yaml import cwrap_parser import nn_parse import native_parse import preprocess_declarations import function_wrapper import dispatch_macros import copy_wrapper from code_template import CodeTemplate parser = OptionParser() parser.add_option('-s', '--source-path', help='path t...
29815
from configargparse import ArgParser from PIL import Image import logging import numpy as np import os def transform_and_save(img_arr, output_filename): """ Takes an image and optionally transforms it and then writes it out to output_filename """ img = Image.fromarray(img_arr) img.save(output_file...
29816
import os import json import boto3 def handler(event, context): table = os.environ.get('table') dynamodb = boto3.client('dynamodb') item = { "name":{'S':event["queryStringParameters"]["name"]}, "location":{'S':event["queryStringParameters"]["location"]}, "age":{'S':even...
29825
import os from starlette.applications import Starlette from starlette.responses import PlainTextResponse, Response from starlette.testclient import TestClient from apistar.client import Client, decoders app = Starlette() @app.route("/text-response/") def text_response(request): return PlainTextResponse("hello,...
29891
import numpy as np import math from scipy.optimize import minimize class Optimize(): def __init__(self): self.c_rad2deg = 180.0 / np.pi self.c_deg2rad = np.pi / 180.0 def isRotationMatrix(self, R) : Rt = np.transpose(R) shouldBeIdentity = np.dot(Rt, R) I = np.id...
29898
from django.apps import AppConfig class AldrynSearchConfig(AppConfig): name = 'aldryn_search' def ready(self): from . import conf # noqa
29941
class Solution: def getFormattedEMail(self, email): userName, domain = email.split('@') if '+' in userName: userName = userName.split('+')[0] if '.' in userName: userName = ''.join(userName.split('.')) return userName + '@' + domain def numUniqueEmail...
29945
class SendResult: def __init__(self, result={}): self.successful = result.get('code', None) == '200' self.message_id = result.get('message_id', None)
29948
from .GlobalData import global_data from .utils.oc import oc import requests import time import logging class App: def __init__(self, deployment, project, template, build_config,route=""): self.project = project self.template = template self.deployment = deployment self.build_conf...
29963
import requests_cache import os.path import tempfile try: from requests_cache import remove_expired_responses except ModuleNotFoundError: from requests_cache.core import remove_expired_responses def caching( cache=False, name=None, backend="sqlite", expire_after=86400, allowable_codes=(200...
29965
import os, sys exp_id=[ "exp1.0", ] env_source=[ "file", ] exp_mode = [ "continuous", #"newb", #"base", ] num_theories_init=[ 4, ] pred_nets_neurons=[ 8, ] pred_nets_activation=[ "linear", # "leakyRelu", ] domain_net_neurons=[ 8, ] domain_pred_mode=[ "onehot", ] mse_amp=[ 1e-7, ] simplify_criteria=[ '\("DLs",...
29991
import sys if len(sys.argv) != 4 : print 'usage:', sys.argv[0], 'index_fn id_mapping_fn output_fn' exit(9) a = open(sys.argv[1]) a.readline() header = a.readline() dir = a.readline() #build map: filename -> set of bad samples mp = {} mp_good = {} mp_bad = {} for line in a : t = line.split() mp[t[0]] = set() ...
29994
import tensorflow as tf import numpy as np import os import time from utils import random_batch, normalize, similarity, loss_cal, optim from configuration import get_config from tensorflow.contrib import rnn config = get_config() def train(path): tf.reset_default_graph() # reset graph # dra...
30036
from collections import OrderedDict import numpy as np from pandas import DataFrame from sv import SVData, CorTiming def loadSVDataFromBUGSDataset(filepath, logreturnforward, logreturnscale, dtfilepath=None): dts = None if dtfilepath is not None: with open(dtfilepath) as f: content = f.re...
30042
from __future__ import print_function import struct import copy #this class handles different protocol versions class RobotStateRT(object): @staticmethod def unpack(buf): rs = RobotStateRT() (plen, ptype) = struct.unpack_from("!IB", buf) if plen == 756: return RobotStateRT_V...
30046
import numpy as np import math import pickle def get_data(data, frame_nos, dataset, topic, usernum, fps, milisec, width, height, view_width, view_height): """ Read and return the viewport data """ VIEW_PATH = '../../Viewport/' view_info = pickle.load(open(VIEW_PATH + 'ds{}/viewport_ds{}_topic{}_user...
30081
import os import os.path import subprocess import sys if __name__ == "__main__": dirname = sys.argv[1] for x in os.listdir(dirname): if x.endswith('.crt'): try: filename = os.path.join(dirname, x) filehash = subprocess.check_output(['openssl', 'x509', '-noout...
30134
import time import requests from core.utils.parser import Parser from core.utils.helpers import Helpers from core.models.plugin import BasePlugin class HIBP(BasePlugin): def __init__(self, args): self.args = args self.base_url = "https://haveibeenpwned.com/api/v2/breachedaccount" self.url...
30189
import tensorflow as tf from tensorflow.keras.applications.vgg16 import VGG16 from tensorflow.keras import models from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.vgg16 import preprocess_input import numpy as np import cv2 # prebuild model with pre-trained weights on imagene...
30194
import pandas as pd import numpy as np print(pd.__version__) # 1.0.0 print(pd.DataFrame.agg is pd.DataFrame.aggregate) # True df = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]}) print(df) # A B # 0 0 3 # 1 1 4 # 2 2 5 print(df.agg(['sum', 'mean', 'min', 'max'])) # A B # sum 3.0 12.0 # mean ...
30209
import os import re import pickle import numpy as np import pandas as pd from tqdm import tqdm # Assign labels used in eep conversion eep_params = dict( age = 'Age (yrs)', hydrogen_lum = 'L_H', lum = 'Log L', logg = 'Log g', log_teff = 'Log T', core_hydrogen_frac = 'X_core', # must be added ...
30226
from enum import Enum class TradeStatus(Enum): PENDING_ACCEPT = 0 PENDING_CONFIRM = 1 PENDING_CANCEL = 2 CANCELED = 3 CONFIRMED = 4 FAILED = 5
30238
import filecmp import os import sys import shutil import subprocess import time import unittest if (sys.version_info > (3, 0)): import urllib.request, urllib.parse, urllib.error else: import urllib from optparse import OptionParser from PyQt4 import QtCore,QtGui parser = OptionParser() parser.add_option("-r",...
30257
from pyssian.chemistryutils import is_basis,is_method import unittest class ChemistryUtilsTest(unittest.TestCase): def setUp(self): self.Valid_Basis = '6-311+g(d,p) 6-31g* cc-pVTZ D95V* LanL2DZ SDD28 Def2SVP UGBS2P2++'.split() self.Fake_Basis = '6-311g+(d,p) 6-31*g ccpVTZ D96V* LanL2TZ SDD Def2SP U...
30267
import logging from django.apps import apps from django.contrib.auth.mixins import LoginRequiredMixin from django.http import Http404, HttpResponse, JsonResponse from django.views.generic import TemplateView, View from zentral.core.stores import frontend_store logger = logging.getLogger("server.base.views") class H...
30280
from haystack.forms import FacetedSearchForm from haystack.query import SQ from django import forms from hs_core.discovery_parser import ParseSQ, MatchingBracketsNotFoundError, \ FieldNotRecognizedError, InequalityNotAllowedError, MalformedDateError FACETS_TO_SHOW = ['creator', 'contributor', 'owner', 'content_typ...
30281
from typing import Any, Dict, List import datetime import pandas as pd import plotly.express as px import plotly.figure_factory as ff import plotly.graph_objects as go import streamlit as st from fbprophet import Prophet from fbprophet.plot import plot_plotly from plotly.subplots import make_subplots from streamlit_p...
30303
import logging import pytest from tests.common.utilities import wait_until from utils import get_crm_resources, check_queue_status, sleep_to_wait CRM_POLLING_INTERVAL = 1 CRM_DEFAULT_POLL_INTERVAL = 300 MAX_WAIT_TIME = 120 logger = logging.getLogger(__name__) @pytest.fixture(scope='module') def get_function_conple...
30322
import argparse import logging from pathlib import Path import dask import h5py import joblib import numpy as np import pandas as pd from dask.diagnostics import ProgressBar from tqdm import tqdm from dsconcept.get_metrics import ( get_cat_inds, get_synth_preds, load_category_models, load_concept_mode...
30356
import yaml from javaSerializationTools import JavaString, JavaField, JavaObject, JavaEndBlock from javaSerializationTools import ObjectRead from javaSerializationTools import ObjectWrite if __name__ == '__main__': with open("../files/7u21.ser", "rb") as f: a = ObjectRead(f) obj = a.readContent()...
30425
from base import job_desc_pb2 from base import task_desc_pb2 from base import reference_desc_pb2 from google.protobuf import text_format import httplib, urllib, re, sys, random import binascii import time import shlex def add_worker_task(job_name, task, binary, args, worker_id, num_workers, extra_args): task.uid = 0...
30448
from tastypie.api import Api from encuestas.api.user import UserResource from encuestas.api.encuesta import EncuestaResource from encuestas.api.grupo import GrupoResource from encuestas.api.pregunta import PreguntaResource from encuestas.api.opcion import OpcionResource from encuestas.api.link import LinkResource from ...
30469
description = 'setup for the status monitor' group = 'special' _expcolumn = Column( Block('Experiment', [ BlockRow( # Field(name='Proposal', key='exp/proposal', width=7), # Field(name='Title', key='exp/title', width=20, # istext=True, maxlen=20), Field(name...
30476
import base64 import datetime import io import json import traceback import aiohttp import discord import pytimeparse from data.services.guild_service import guild_service from discord.commands import Option, slash_command, message_command, user_command from discord.ext import commands from discord.utils import forma...
30493
import os import shutil import subprocess from possum.exc import PipenvPathNotFound class PipenvWrapper: def __init__(self): self.pipenv_path = shutil.which('pipenv') if not self.pipenv_path: raise PipenvPathNotFound # Force pipenv to ignore any currently active pipenv envir...
30498
class O(object): pass class A(O): pass class B(O): pass class C(O): pass class D(O): pass class E(O): pass class K1(A,B,C): pass class K2(D,B,E): pass class K3(D,A): pass class Z(K1,K2,K3): pass print K1.__mro__ print K2.__mro__ print K3.__mro__ print Z.__mro__
30507
from django.conf import settings from django.contrib.postgres.fields import JSONField from django.db import models from django.db.models import Q from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ TARGET_FKEY_ATTRS = dict( null=True, blank=True, on_...
30522
import mimetypes from django.contrib.staticfiles.storage import staticfiles_storage from django.core import signing from django.forms import widgets from django.forms.utils import flatatt from django.utils.safestring import mark_safe from django.utils.html import format_html from django.utils.translation import ugette...
30565
import datetime import unittest class KalmanFilterTest(unittest.TestCase): def test_kalman_filter_with_prior_predict(self): t0 = datetime.datetime(2014, 2, 12, 16, 18, 25, 204000) print(t0) self.assertEqual(1., 1.) def test_kalman_filter_without_prior_predict(self...
30595
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import os from datasets import convert_data FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('data_type', None, 'The type of the dataset to convert, ne...
30597
import logging import numpy as np from bico.geometry.point import Point from bico.nearest_neighbor.base import NearestNeighbor from bico.utils.ClusteringFeature import ClusteringFeature from datetime import datetime from typing import Callable, TextIO, List logger = logging.getLogger(__name__) class BICONode: de...
30674
from django.core.exceptions import SuspiciousOperation from django.core.signing import Signer, BadSignature from django.forms import HiddenInput signer = Signer() class SignedHiddenInput(HiddenInput): def __init__(self, include_field_name=True, attrs=None): self.include_field_name = include_field_name ...
30690
from typing import Union from scipy.spatial.qhull import Delaunay from shapely.geometry import LineString from subsurface.structs.base_structures import StructuredData import numpy as np try: import segyio segyio_imported = True except ImportError: segyio_imported = False def read_in_segy(filepath: str, ...
30696
from pylayers.gis.layout import * from pylayers.antprop.signature import * from pylayers.antprop.channel import * import pylayers.signal.waveform as wvf import networkx as nx import numpy as np import time import logging L = Layout('WHERE1_clean.ini') #L = Layout('defstr2.ini') try: L.dumpr() except: L.build()...
30718
from .models import db, User from m import Router from m.utils import jsonify router = Router(prefix='') @router.route('/', methods=['POST']) def home(ctx, request): name = request.json().get('name') user = User(name=name) db.session.add(user) try: db.session.commit() except Exception as ...
30784
import wallycore as wally from . import exceptions from gaservices.utils import h2b wordlist_ = wally.bip39_get_wordlist('en') wordlist = [wally.bip39_get_word(wordlist_, i) for i in range(2048)] def seed_from_mnemonic(mnemonic_or_hex_seed): """Return seed, mnemonic given an input string mnemonic_or_hex_se...
30791
from rest_framework import status from rest_framework.exceptions import APIException class FeatureStateVersionError(APIException): status_code = status.HTTP_400_BAD_REQUEST class FeatureStateVersionAlreadyExistsError(FeatureStateVersionError): status_code = status.HTTP_400_BAD_REQUEST def __init__(self...
30793
import numpy as np import pandas as pd import pytest from etna.datasets import TSDataset from etna.datasets import generate_ar_df from etna.datasets import generate_const_df from etna.datasets import generate_periodic_df from etna.metrics import R2 from etna.models import LinearPerSegmentModel from etna.transforms imp...
30845
from pygments.lexer import RegexLexer, include, words from pygments.token import * # https://docs.nvidia.com/cuda/parallel-thread-execution/index.html class CustomLexer(RegexLexer): string = r'"[^"]*?"' followsym = r'[a-zA-Z0-9_$]*' identifier = r'(?:[a-zA-Z]' + followsym + r'| [_$%]' + followsym + r')' ...
30859
singular = [ 'this','as','is','thesis','hypothesis','less','obvious','us','yes','cos', 'always','perhaps','alias','plus','apropos', 'was','its','bus','his','is','us', 'this','thus','axis','bias','minus','basis', 'praxis','status','modulus','analysis', 'aparatus' ] invariable = [ #frozen_li...
30895
from zerocopy import send_from from socket import * s = socket(AF_INET, SOCK_STREAM) s.bind(('', 25000)) s.listen(1) c,a = s.accept() import numpy a = numpy.arange(0.0, 50000000.0) send_from(a, c) c.close()
30937
if __name__ == '__main__': n = int(input()) s = set() for i in range (n): s.add(input()) print((len(s)))
30941
import datetime from flask_ldap3_login import LDAP3LoginManager, AuthenticationResponseStatus from lost.settings import LOST_CONFIG, FLASK_DEBUG from flask_jwt_extended import create_access_token, create_refresh_token from lost.db.model import User as DBUser, Group from lost.db import roles class LoginManager(): de...
30972
def main(): a = ["a", 1, "5", 2.3, 1.2j] some_condition = True for x in a: # If it's all isinstance, we can use a type switch if isinstance(x, (str, float)): print("String or float!") elif isinstance(x, int): print("Integer!") else: print("...
31027
import time import os from pykafka.test.kafka_instance import KafkaInstance, KafkaConnection def get_cluster(): """Gets a Kafka cluster for testing, using one already running is possible. An already-running cluster is determined by environment variables: BROKERS, ZOOKEEPER, KAFKA_BIN. This is used prim...
31031
import base64 from scapy.layers.inet import * from scapy.layers.dns import * import dissector class SIPStartField(StrField): """ field class for handling sip start field @attention: it inherets StrField from Scapy library """ holds_packets = 1 name = "SIPStartField" def getfield(self, pk...
31105
import abc import logging from datetime import datetime from .log_adapter import adapt_log LOGGER = logging.getLogger(__name__) class RunnerWrapper(abc.ABC): """ Runner wrapper class """ log = adapt_log(LOGGER, 'RunnerWrapper') def __init__(self, func_runner, runner_id, key, tracker, log_exception=Tru...
31111
import traceback import copy import gc from ctypes import c_void_p import itertools import array import math import numpy as np from OpenGL.GL import * from PyEngine3D.Common import logger from PyEngine3D.Utilities import Singleton, GetClassName, Attributes, Profiler from PyEngine3D.OpenGLContext import OpenGLContex...
31119
from django.db import models class BaseModel(models.Model): class Meta: abstract = True def reload(self): new_self = self.__class__.objects.get(pk=self.pk) # Clear and update the old dict. self.__dict__.clear() self.__dict__.update(new_self.__dict__)
31122
import io import os from svgutils import transform as svg_utils import qrcode.image.svg from cwa_qr import generate_qr_code, CwaEventDescription class CwaPoster(object): POSTER_PORTRAIT = 'portrait' POSTER_LANDSCAPE = 'landscape' TRANSLATIONS = { POSTER_PORTRAIT: { 'file': 'poster/p...
31160
from contextlib import contextmanager import torch import torch.nn.functional as F from torch.nn import Module, Parameter from torch.nn import init _WN_INIT_STDV = 0.05 _SMALL = 1e-10 _INIT_ENABLED = False def is_init_enabled(): return _INIT_ENABLED @contextmanager def init_mode(): global _INIT_ENABLED ...
31271
import warnings from dataclasses import dataclass from typing import List, Optional import torch from falkon.utils.stream_utils import sync_current_stream from falkon.mmv_ops.utils import _get_gpu_info, create_output_mat, _start_wait_processes from falkon.options import FalkonOptions, BaseOptions from falkon.utils i...
31273
import codecs import sys RAW_DATA = "../data/ptb/ptb.train.txt" VOCAB = "data/ptb.vocab" OUTPUT_DATA = "data/ptb.train" # 读取词汇表并建立映射 with codecs.open(VOCAB, "r", "utf-8") as f_vocab: vocab = [w.strip() for w in f_vocab.readlines()] word_to_id = {k: v for (k, v) in zip(vocab, range(len(vocab)))} # 如果出现了被删除的低频词,替换...
31317
from utils import * car = get_car() # Positive cases. Can't print the result because the address may change # from run to run. # dbgscript.search_memory(car['name'].address-16, 100, b'FooCar', 1) dbgscript.search_memory(car['name'].address-16, 100, b'FooCar', 2) # Negative cases. # # 4 is not a multipl...
31356
from django.contrib import messages from django.http import HttpResponseRedirect from django.utils.functional import cached_property from django.utils.translation import ugettext as _ from django.utils.translation import ugettext_noop, ugettext_lazy from couchdbkit import ResourceNotFound from memoized import memoized...
31372
import NLQ_Preprocessor as preProcessor import NLP_Engine as nlpEngine import NLQ_Interpreter as interpreter import nltk import time class NLQ_Chunker: def __init__(self): self.preprocessor = preProcessor.PreProcessor() self.nlp_engine = nlpEngine.NLP_Engine() self.interpreter = interpre...
31427
import numpy as np from pyquil import Program from pyquil.api import QuantumComputer, get_qc from grove.alpha.jordan_gradient.gradient_utils import (binary_float_to_decimal_float, measurements_to_bf) from grove.alpha.phaseestimation.phase_estimation import phase_...
31428
from torch import randn from torch.nn import Conv2d from backpack import extend def data_conv2d(device="cpu"): N, Cin, Hin, Win = 100, 10, 32, 32 Cout, KernelH, KernelW = 25, 5, 5 X = randn(N, Cin, Hin, Win, requires_grad=True, device=device) module = extend(Conv2d(Cin, Cout, (KernelH, KernelW))).to...
31460
import os import json from contextlib import suppress from OrderBook import * from Signal import Signal class OrderBookContainer: def __init__(self, path_to_file): self.order_books = [] self.trades = [] self.cur_directory = os.path.dirname(path_to_file) self.f_name = ...
31467
import os from biicode.common.model.brl.block_cell_name import BlockCellName from biicode.common.model.bii_type import BiiType def _binary_name(name): return os.path.splitext(name.replace("/", "_"))[0] class CPPTarget(object): def __init__(self): self.files = set() # The source files in this targe...
31490
from ._base import BaseWeight from ..exceptions import NotFittedError from ..utils.functions import mean_log_beta import numpy as np from scipy.special import loggamma class PitmanYorProcess(BaseWeight): def __init__(self, pyd=0, alpha=1, truncation_length=-1, rng=None): super().__init__(rng=rng) ...
31528
import sys if sys.version_info > (3,): basestring = (str, bytes) long = int class DeprecatedCellMixin(object): """Deprecated Cell properties to preserve source compatibility with the 1.0.x releases.""" __slots__ = () @property def r(self): """The row number of this cell. .....
31593
import numpy as np import os import os.path as path from keras.applications import vgg16, inception_v3, resnet50, mobilenet from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array import kmri base_path = path.dirname(path.realpath(__file__)) img_path = path.join(base_path, 'i...
31597
import brownie def test_set_minter_admin_only(accounts, token): with brownie.reverts("dev: admin only"): token.set_minter(accounts[2], {"from": accounts[1]}) def test_set_admin_admin_only(accounts, token): with brownie.reverts("dev: admin only"): token.set_admin(accounts[2], {"from": account...
31602
import numpy from scipy.ndimage import gaussian_filter from skimage.data import binary_blobs from skimage.util import random_noise from aydin.it.transforms.fixedpattern import FixedPatternTransform def add_patterned_noise(image, n): image = image.copy() image *= 1 + 0.1 * (numpy.random.rand(n, n) - 0.5) ...