id
stringlengths
3
8
content
stringlengths
100
981k
11462402
import locale import logging import os import re import subprocess from io import open import click import sqlparse from .favoritequeries import favoritequeries from .main import NO_QUERY, PARSED_QUERY, special_command from .utils import handle_cd_command TIMING_ENABLED = False use_expanded_output = False PAGER_ENA...
11462408
import sys from io import BytesIO from collections import OrderedDict import urllib import shlex import subprocess import logging from .. import argparser log = logging.getLogger('curlbomb.share') def add_parser(subparsers): share_parser = subparsers.add_parser( 'share', help="Share a resource URL with a...
11462413
import os import tensorflow as tf from gans.callbacks import callback from gans.utils import constants from gans.utils import logging log = logging.get_logger(__name__) class GANCheckpointManager(callback.Callback): def __init__( self, components_to_save, root_checkpoint_pa...
11462457
import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from wireframe.utils import argsort2d DX = [0, 0, 1, -1, 1, 1, -1, -1] DY = [1, -1, 0, 0, 1, -1, 1, -1] def ap(tp, fp, npos): recall = tp / npos precision = tp / np.maximum(tp + fp, 1e-9) recall = np.concatenate(([0.0], recall, [1...
11462499
import os import torch from torch.utils.data import Dataset import torchvision.transforms as transforms from PIL import Image class FontData(): def __init__(self, font_name, font_path, image=None): self.font_name = font_name self.font_path = font_path self.image = None def load_data(self, loader): ...
11462508
import tensorflow as tf class LoggerHook(tf.train.SessionRunHook): def __init__(self, display_step): self._display_step = display_step def begin(self): self._step = -1 def before_run(self, run_context): self._step += 1 if self._step % self._display_step == 0: ...
11462530
import clify import argparse from dps import cfg from dps.config import DEFAULT_CONFIG from dps.projects.nips_2018.envs import air_testing_config as env_config # from dps.projects.nips_2018.envs import grid_fullsize_config as env_config from dps.projects.nips_2018.algs import air_config as alg_config distributions =...
11462560
from trakt.core.helpers import from_iso8601_datetime, to_iso8601_datetime, deprecated from trakt.objects.core.helpers import update_attributes from trakt.objects.video import Video class Episode(Video): def __init__(self, client, keys=None, index=None): super(Episode, self).__init__(client, keys, index) ...
11462591
import itertools import sys from difflib import SequenceMatcher as SM def uprint(*objects, sep=' ', end='\n', file=sys.stdout): enc = file.encoding if enc == 'UTF-8': print(*objects, sep=sep, end=end, file=file) else: def f(obj): return str(obj) \ .encode(enc, ...
11462612
from collections import defaultdict class Solution: def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]: data = [[username[i], timestamp[i], website[i]] for i in range(len(username))] data.sort() dic = defaultdict(list) for...
11462632
from __future__ import print_function import cw import cw.slurm import bluelet import threading import concurrent.futures import os import sys class Client(object): def __init__(self, host=None, port=cw.PORT): # if no host specified, then auto-detect if slurm should be used if host is None: ...
11462680
import types from collections.abc import Iterable from typing import Optional, Tuple, Union import astromodels import numba as nb import numpy as np from threeML.io.logging import setup_logger from threeML.plugin_prototype import PluginPrototype __instrument_name = "n.a." log = setup_logger(__name__) _tiny = np.f...
11462694
import torch import torch.nn as nn def extract(a, t, x_shape): b, *_ = t.shape out = a.gather(-1, t).float() return out.reshape(b, *((1,) * (len(x_shape) - 1))) class DDPMv2(nn.Module): def __init__( self, decoder, beta_1=1e-4, beta_2=0.02, T=1000, var...
11462695
import string from utils import strings def print_results(file_bin, signature_range_list, output_file): out = open(output_file, "w") out.write("=== AVSignSeek ===\n") for signature_range in signature_range_list: start = signature_range[0] end = signature_range[1] print("[+] Signa...
11462713
import pynes from pynes.game import Game from pynes.bitbag import * from pynes.nes_types import * game = Game() palette = game.assign('palette', NesArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15, 0x0F, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, ...
11462738
import numpy as np import os import shutil import tensorflow as tf import tempfile from gdmix.io.input_data_pipeline import per_record_input_fn from gdmix.util import constants os.environ['CUDA_VISIBLE_DEVICES'] = '-1' num_records = 10 np.random.seed(0) labels = np.random.randint(2, size=num_records, dtype=np.int32)...
11462742
import json class TestListSwitchHost: def test_no_args(self, host, add_host, add_switch): # Add interfaces to our switch and backend result = host.run('stack add host interface switch-0-0 interface=eth0 network=private') assert result.rc == 0 result = host.run('stack add host interface backend-0-0 interface...
11462746
from umongo import Document, validate from umongo.fields import StringField from app import app instance = app.config["LAZY_UMONGO"] @instance.register class Permission(Document): codename = StringField( unique=True, allow_none=False, required=True, validate=validate.Regexp( ...
11462764
class DataGridColumn(DependencyObject): """ Represents a System.Windows.Controls.DataGrid column. """ def CancelCellEdit(self,*args): """ CancelCellEdit(self: DataGridColumn,editingElement: FrameworkElement,uneditedValue: object) Causes the cell being edited to revert to the original,unedited value. ...
11462770
import tensorflow as tf import numpy as np def fc_op(input_op, name, n_out, layer_collector, act_func=tf.nn.leaky_relu): n_in = input_op.get_shape()[-1].value with tf.name_scope(name) as scope: kernel = tf.Variable(tf.contrib.layers.xavier_initializer()([n_in, n_out]), dtype=tf.float32, name=scope + "...
11462799
import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(17,GPIO.OUT) servo=GPIO.PWM(17,50) servo.start(0) time.sleep(1) duty =2 while duty<=12: servo.ChangeDutyCycle(duty) time.sleep(1) duty=duty+1 time.sleep(2) while duty>=0: servo.ChangeDutyCycle(duty) ...
11462805
import inspect class Player(object): """A class for a player in the tournament. This is an abstract base class, not intended to be used directly. """ name = "Player" def __init__(self): """Initiates an empty history and 0 score for a player.""" self.history = [] self.sto...
11462874
def _get_default_options(): """ Returns a dictionary with the available compiler options and the default values Returns: default_options (Dict) """ return { 'library_folders': [], 'verbose': False, 'check_balanced': True, 'mtime_check': True, 'cache'...
11462929
import os from importlib import import_module from uploader import AbstractUploader class Uploader: @staticmethod def get(server: str, path: str) -> AbstractUploader: return import_module(f'uploader.{server}').Uploader(path) @staticmethod def server() -> list: return tuple(os.path.spl...
11462955
import tsensor import numpy as np def f(): # Currently can't handle double assign a = b = np.ones(1) @ np.ones(2) def A(): with tsensor.clarify(): f() def test_nested(): msg = "" try: A() except BaseException as e: msg = e.args[0] expected = "matmul: Input operan...
11462981
import numpy as np import pdb class Resampling: """ References: Thrun, Sebastian, <NAME>, and <NAME>. Probabilistic robotics. MIT press, 2005. [Chapter 4.3] """ def __init__(self): """ TODO : Initialize resampling process parameters here """ def multinomial_sampler(se...
11462986
r""" Diametrically point loaded 2-D disk. See :ref:`sec-primer`. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) = 0 \;, \quad \forall \ul{v} \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) + \lambda \ \delta_{ij...
11463005
from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print(tag) for li in attrs: print('->', li[0], '>', li[1]) if __name__ == '__main__': n = int(input()) s = '' for _ in range(n): t = input() s += t ...
11463011
import sys import sqlite # The shared connection object cx = None def getCon(): # All code gets the connection object via this function global cx return cx def createSchema(): # Create the schema and make sure we're not accessing an old, incompatible schema cu = getCon().cursor() cu.execute("...
11463014
from typing import Optional from platypush.message.event import Event from platypush.plugins.mail import Mail class MailEvent(Event): def __init__(self, mailbox: str, message: Optional[Mail] = None, *args, **kwargs): super().__init__(*args, mailbox=mailbox, message=message or {}, **kwargs) class MailRe...
11463039
import numpy as np from gym_flock.envs.flocking.flocking_relative import FlockingRelativeEnv from gym_flock.envs.flocking.utils import grid class FlockingTwoFlocksEnv(FlockingRelativeEnv): def reset(self): self.x = np.zeros((self.n_agents, self.nx_system)) # grids, vels = twoflocks(self.n_agents,...
11463043
import numpy as np import networkx as nx import cPickle as cp import random import ctypes import os import sys from tqdm import tqdm sys.path.append( '%s/tsp2d_lib' % os.path.dirname(os.path.realpath(__file__)) ) from tsp2d_lib import Tsp2dLib n_valid = 100 def find_model_file(opt): max_n = int(opt['max_n']) ...
11463108
import numpy as np a = np.array([0, 0, 30, 10, 10, 20]) print(a) # [ 0 0 30 10 10 20] print(np.unique(a)) # [ 0 10 20 30] print(type(np.unique(a))) # <class 'numpy.ndarray'> l = [0, 0, 30, 10, 10, 20] print(l) # [0, 0, 30, 10, 10, 20] print(np.unique(l)) # [ 0 10 20 30] print(type(np.unique(l))) # <class 'numpy....
11463167
from unittest.mock import patch from cicada2.engine import runners def test_config_to_runner_env(): config = {"foo": "bar", "fizz": "buzz"} env_config = runners.config_to_runner_env(config) assert env_config == {"RUNNER_FOO": "bar", "RUNNER_FIZZ": "buzz"} @patch("cicada2.engine.runners.runner_healthc...
11463188
from __future__ import print_function import os import sys import imp import inspect class TestFunction(object): is_class = False def __init__(self, target, name=None, is_method=False): self.target = target if not name: name = target.__name__ self.name = '{}:{}'.format(ta...
11463194
import logging import ibmsecurity.utilities.tools logger = logging.getLogger(__name__) def get_all(isamAppliance, check_mode=False, force=False): """ Get all rsyslog objects """ return isamAppliance.invoke_get("Get all rsyslog objects", "/core/rsp_rsyslog_objs") ...
11463242
import h5py import numpy ############################################################################### # This file writes all of the materials data (multi-group nuclear # cross-sections) for the LRA diffusion # benchmark problem to an HDF5 file. The script uses the h5py Python package # to interact with the HDF5 fi...
11463251
from typing import Dict, List from uuid import uuid4 from ee.clickhouse.models.event import create_event from ee.clickhouse.models.session_recording_event import create_session_recording_event def bulk_create_events(events: List[Dict], **kw): for event_data in events: create_event(**event_data, **kw, eve...
11463253
import logging import os from overrides import overrides from typing import Dict, List from repro.common import TemporaryDirectory from repro.common.docker import make_volume_map, run_command from repro.common.io import write_to_text_file from repro.models import Model, TruecasingModel from repro.models.susanto2016 im...
11463278
from django.conf.urls import url from . import views urlpatterns = [ url('', views.TableView.as_view(), name="table_api"), ]
11463319
import pygame_sdl2 import os import argparse import json def smoothscale(surf, size): while True: w, h = surf.get_size() if (w == size[0]) and (h == size[1]): break w = max(w // 2, size[0]) h = max(h // 2, size[1]) surf = pygame_sdl2.transform.smoothscale(su...
11463347
def upper(word: str) -> str: """ Will convert the entire string to uppercase letters >>> upper("wow") 'WOW' >>> upper("Hello") 'HELLO' >>> upper("WHAT") 'WHAT' >>> upper("wh[]32") 'WH[]32' """ # Converting to ascii value int value and checking to see if char is a lower ...
11463358
api_key: str = "api-key-string" bearer_token: str = "bearer-token-string" mock_data = {"testkey": "testval"} hooli_id = "9676868b-60d2-5ebe-aa66-c1de8162ff9d" from gremlinapi.attack_helpers import ( GremlinAttackTargetHelper, GremlinAttackCommandHelper, ) mock_access_token = "<PASSWORD>" mock_bearer_token = "<...
11463365
def checking_subset(): user_in = int(input()) set1 = set(list(map(int, input().splitl()))) user_in2 = int(input()) set2 = set(list(map(int, input().splitl()))) print(set1.issubset(set2)) user = int(input()) for i in range(user): checking_subset()
11463369
import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt # from noduleCADEvaluationLUNA16 import noduleCADEvaluation from noduleCADEvaluationLUNA16compare import noduleCADEvaluation import os import csv from multiprocessing import Pool import functools import SimpleITK as ...
11463388
import logging logger = logging.getLogger(__name__) import time from boto.exception import SDBResponseError from nymms.scheduler.lock.SchedulerLock import SchedulerLock class SDBLock(SchedulerLock): def __init__(self, duration, conn, domain_name, lock_name="scheduler_lock"): super(SDB...
11463423
import numpy as np # pythran export kernel(int, int, float64[:,:]) def kernel(TSTEPS, N, A): for t in range(0, TSTEPS - 1): for i in range(1, N - 1): A[i, 1:-1] += (A[i - 1, :-2] + A[i - 1, 1:-1] + A[i - 1, 2:] + A[i, 2:] + A[i + 1, :-2] + A[i + 1, 1:-1] + ...
11463460
from django import forms from osf.models.storage import ProviderAssetFile from osf.models.provider import AbstractProvider class ProviderAssetFileForm(forms.ModelForm): class Meta: model = ProviderAssetFile fields = ['name', 'file', 'providers', 'id'] id = forms.IntegerField(required=False, ...
11463518
import numpy as np # import uproot import json import datetime import pytz import os import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.lines as mlines import matplotlib.ticker as ticker from matplotlib.font_manager import FontProperties # Define some plot constan...
11463543
import arcade from triple_vision import Settings as s from triple_vision.triple_vision import TripleVision from triple_vision.views.leaderboard_view import LeaderboardView class PlayButton(arcade.TextButton): def __init__(self, view, *args, **kwargs) -> None: super().__init__(text='', *args, **kwargs) ...
11463570
def True(): pass def None(): pass def False(): pass def : meta.function.python, source.python, storage.type.function.python : meta.function.python, source.python True : keyword.illegal.name.python, meta.function.python, source.python ( : meta.function.parameters.python, m...
11463579
from prml.nn.image.convolve2d import convolve2d, Convolve2d from prml.nn.image.deconvolve2d import deconvolve2d, Deconvolve2d from prml.nn.image.max_pooling2d import max_pooling2d from prml.nn.image.util import img2patch, patch2img
11463586
import os import sys sys.path.insert(0, '../../') import time import glob import numpy as np import torch import nasbench201.utils as ig_utils import logging import argparse import shutil import torch.nn as nn import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn import sota.cnn.ge...
11463591
KEYWORDS = ['cgi', ] def rules(head='',context='',ip='',port='',productname={},keywords='',hackinfo=''): if 'cgi-bin' in hackinfo or 'cgi-bin' in context: return True else: return False
11463628
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import requests class EmailSender(object): def __init__(self, detail): self.detail = detail self.sender = None self.msg_type = 'email' def _get_server_connection(self): email_h...
11463642
import collections from arekit.common.evaluation.cmp_opinions import OpinionCollectionsToCompare class OpinionCollectionsToCompareUtils: def __init__(self): pass @staticmethod def iter_comparable_collections(doc_ids, read_result_collection_func, ...
11463674
PARSING_SCHEME = { 'name': 'a', 'conference': 'td[data-stat="conf_abbr"] a', 'games': 'td[data-stat="g"]:first', 'wins': 'td[data-stat="wins"]:first', 'losses': 'td[data-stat="losses"]:first', 'win_percentage': 'td[data-stat="win_loss_pct"]:first', 'conference_wins': 'td[data-stat="wins_conf...
11463683
from flask import Flask, session import meetyourmappers app = Flask(__name__) app.config.from_object("meetyourmappers.config") try: app.config.from_object("meetyourmappers.config_local") except: pass import meetyourmappers.views
11463704
from . import time from . import grid from .interp import interpNan import numpy as np def index2d(ind, ny, nx): iy = np.floor(ind / nx) ix = np.floor(ind % nx) return int(iy), int(ix) def fillNan(mat, mask): temp = mat.copy() temp[~mask] = np.nan return temp
11463711
import os from pathlib import Path from unittest import mock import click import pytest from cumulusci.cli.tests.utils import recursive_list_files, run_click_command from cumulusci.core.dependencies.dependencies import PackageNamespaceVersionDependency from cumulusci.core.exceptions import NotInProject from cumulusci...
11463738
import pandas as pd import numpy as np import scipy as sp import os import errno from sklearn.decomposition import PCA import umap.distances as dist from sklearn.utils.extmath import svd_flip from sklearn.utils import check_array, check_random_state from scipy import sparse import sklearn.utils.sparsefuncs as sf from u...
11463742
if __name__ == "__main__": with open("./lnbits/.env") as env_file: env = {} for line in env_file.readlines(): if "=" in line: key, value = line.split("=", 1) env[key] = value user = input("Input your user ID: ") allowed_users = env['LNBITS_ALLOWED_...
11463743
import tests.hakoblog # noqa: F401 from datetime import datetime from hakoblog.model.entry import Entry def test_init(): now = datetime.now(), entry = Entry( id=0, blog_id=1, title='こんにちは', body='今日は天気が良いですね。', created=now, modified=now, ) assert entr...
11463761
from .Zmod import Zmod, ZmodElement class FiniteField(Zmod): """ Finite Field Class """ def __init__(s, p): """ Constructor of FiniteField p should be prime """ s.n = s.p = p s.element_class = ZmodElement def __str__(s): return Zmod.__str__(s, "p")
11463782
from global_utils import print_summary from options import parse_options from global_utils import set_global_seed, save_performance, plot_data import time from agent_env_params import design_agent_and_env from multiprocessing import Process import random from environment import Environment from agent import A...
11463792
import numpy as np # -------------------------------------------------------------- # Rotation Functions # -------------------------------------------------------------- def rotxM(theta): """Return x rotation matrix""" theta = theta * np.pi / 180 M = [[1, 0, 0], [0, np.cos(theta), -np.sin(...
11463806
class Cache: def __init__(self, application, store_config=None): self.application = application self.drivers = {} self.store_config = store_config or {} self.options = {} def add_driver(self, name, driver): self.drivers.update({name: driver}) def set_configuration(s...
11463809
from template import testcase, base_test, trace_list from pathlib import Path import bitmath import csv class test(base_test): def generate_trace(self, pattern: str, sz: int, testcase_out_path, repeat, cache_trace: bool) -> Path: generate_trace = False if cache_trace: trace_file_path =...
11463816
import numpy as np class BaseDynamics: """Base class for all dynamics processes. The basic usage is as follows: >>> ground_truth = nx.read_edgelist("ground_truth.txt") >>> dynamics_model = Dynamics() >>> synthetic_TS = dynamics_model.simulate(ground_truth, <some_params>) >>> # G = Reconstruc...
11463817
import os import unittest from brazil_srag import srag _SOURCE_ID = "abc123" _SOURCE_URL = "foo.bar" class BrazilSRAGTest(unittest.TestCase): def setUp(self): # Default of 1500 is not enough to show diffs when there is one. self.maxDiff = 10000 def test_parse(self): current_dir = os...
11463957
from .kb import KB, Boolean, Integer # Initialise all variables that you need for you strategies and game knowledge. # Add those variables here.. The following list is complete for the Play Jack strategy. J0 = Boolean('j0') J1 = Boolean('j1') J2 = Boolean('j2') J3 = Boolean('j3') J4 = Boolean('j4') J5 = Boolean('j5') ...
11464028
from pydantic import BaseModel class A(BaseModel): cde: str xyz: str class B(A): cde: int xyz: str A(cde='abc', xyz='123') B(cde='abc', xyz='123')
11464031
import os import json import pickle import zipfile from tatk.util.camrest.state import default_state from tatk.util.dataloader.module_dataloader import ActPolicyDataloader from tatk.policy.vector.vector_camrest import CamrestVector class ActPolicyDataLoaderCamrest(ActPolicyDataloader): def __init__(self): ...
11464050
from click.testing import CliRunner from indexpy.cli import index_cli def test_custom_command(): @index_cli.command(name="only-print") def only_print(): print("Custom command") cli = CliRunner() assert cli.invoke(index_cli, ["only-print"]).output == "Custom command\n"
11464053
import copy import re def normalize(s): return re.sub('\s+', ' ', s.strip()) DEMO_SYNONYMS = [ ('rate', 'ratings'), ('rating', 'ratings'), ('approval', 'popularity'), ] def console(synonym_queries): synonym_list = copy.copy(DEMO_SYNONYMS) print('Using default synonyms:') for s1, s2 in...
11464099
from scipy.optimize import curve_fit import numpy as np def curve_func(x, a, b, c): return a *(1-np.exp( -1/c * x**b )) def fit(func, x, y): popt, pcov = curve_fit(func, x, y, p0 =(1,1,1), method= 'trf', sigma = np.geomspace(1,.1,len(y)), absolute_sigma=True, bounds= ([0,0,0],[1,1,np.inf]) ) return tupl...
11464108
import collections import chainer import numpy as np import onnx from typing import List, Mapping from chainer_compiler.ch2o import env from chainer_compiler.ch2o import utils def _is_float_value(v): # The latter is for numpy-like things. return isinstance(v, float) or int(v) != v class Value(object): ...
11464113
import sys import os import numpy as np from scipy.interpolate import interp1d # Get the inputs from the terminal line L = float(sys.argv[1]) theta = float(sys.argv[2]) folderNum = int(sys.argv[3]) # Delete the previous blockMeshDict os.system("rm ./baseCase/system/blockMeshDict") # Delete the individual folder if i...
11464167
import os import shutil import unittest from mock import patch import activity.activity_GenerateSWHReadme as activity_module from activity.activity_GenerateSWHReadme import ( activity_GenerateSWHReadme as activity_object, ) from provider.article import article import tests.activity.settings_mock as settings_mock fr...
11464168
class RedisStorage: def __init__(self, guild_id, plugin_name, redis): self.guild_id = guild_id self.plugin_name = plugin_name self.prefix = '{}.{}:'.format(plugin_name, guild_id) self.redis = redis def set(self, key, value, ex=None): ...
11464187
from rlzoo.common.policy_networks import * from rlzoo.common.value_networks import * from rlzoo.common.utils import set_seed """ full list of algorithm parameters (alg_params) ----------------------------------------------- net_list: a list of networks (value and policy) used in the algorithm, from common func...
11464209
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from src.genotype.cdn.nodes.module_node import ModuleNode from typing import List, Tuple from runs import runs_manager from configuration import config from src.genotype.neat.connection import Connection from src.genotype.neat...
11464246
from ctypes import * cliodb = cdll.LoadLibrary("cliodb-ffi/target/debug/libcliodbffi.so") cliodb.connect.argtypes = [c_char_p, c_void_p] cliodb.connect.restype = c_int cliodb.transact.argtypes = [c_void_p, c_char_p] cliodb.transact.restype = c_int # ValueTag enum (VAL_ENTITY, VAL_IDENT, VAL_STRING, VAL_TIMESTAMP) =...
11464253
import os from locust import TaskSet, task, HttpUser, between QUIET_MODE = True if os.getenv("QUIET_MODE", "true").lower() in ['1', 'true', 'yes'] else False TASK_DELAY_FROM = int(os.getenv("TASK_DELAY", "5")) TASK_DELAY_TO = int(os.getenv("TASK_DELAY", "30")) def log(message): if not QUIET_MODE: print(...
11464277
from relogic.logickit.dataflow import DataFlow, Example, Feature, MiniBatch from typing import List, Dict, Tuple import torch from relogic.logickit.utils import create_tensor from relogic.logickit.tokenizer.tokenization import BertTokenizer class DependencyParsingExample(Example): """DependencyParsingExample ""...
11464291
import os import sys import subprocess import filecmp testfile = '/home/rcarley/toe/hls/toe/toe_prj/solution2/ctest.tcl' number_of_tests = 5 projectname = 'toe_prj' ##projectname = '/home/rcarley/toe/hls/toe/toe_prj/' vivado_path = "vivado_hls" # infile = "in_toe.dat" # outfile = "out_toe.dat" curr_path = os.getcw...
11464308
import requests import time from datetime import datetime,timedelta import dateutil.parser class GetTopPostTime(): def set_info(self,parameters): """ Set the info about a parameter Args: self: (todo): write your description parameters: (dict): write your description ...
11464344
import logging import os import numpy as np bigrams_pool = [] with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bigrams_new.txt'), 'r') as f: for line in f: bigrams_pool.append(line.split()) def build_phoc(words, phoc_unigrams, unigram_levels, ...
11464349
import math import numpy as np import copy import random from fireplace.exceptions import GameOver, InvalidAction EPS = 1e-8 class MCTS(): """ This class handles the MCTS tree. """ def __init__(self, game, nnet, args): self.game = game self.nnet = nnet self.args = args ...
11464422
import contextlib import io import time import asyncio import nest_asyncio from logging import StreamHandler from aiohttp import ClientSession nest_asyncio.apply() DEFAULT_PAYLOAD = {"disable_web_page_preview": True, "parse_mode": "Markdown"} class TelegramLogHandler(StreamHandler): """ Handler to send logs...
11464438
import sys from json import loads from os import getenv from os.path import join, dirname standard_location = join(dirname(__file__), './config.json') env_var_config_file_path = getenv('TELEGRAM_PI_BOT_CONFIG', standard_location) try: input_config_file_path = sys.argv[1] if sys.argv and sys.argv[1] else env_var_c...
11464479
from .PBXResolver import * from .PBX_Constants import * class PBX_Base(object): def __init__(self, lookup_func, dictionary, project, identifier): # default 'name' property of a PBX object is the type self.name = self.__class__.__name__; # this is the identifier for this object ...
11464487
from datetime import datetime, timedelta import re from ebedke.utils.date import on_workdays, days_lower from ebedke.utils.http import get_dom from ebedke.pluginmanager import EbedkePlugin URL = "http://www.monks.hu/etlap" @on_workdays def get_menu(today): dom = get_dom(URL) week_date = dom.xpath("/html/body...
11464504
import numpy as np from scipy.stats import norm from PIL import Image, ImageDraw, ImageFont, ImageMath from pyray.shapes.twod.paraboloid import * from pyray.shapes.zerod.pointswarm import * from pyray.rotation import * from pyray.imageutils import * from pyray.axes import * from pyray.shapes.oned.curve import draw_curv...
11464506
import argparse import logging import pathlib import joblib import numpy as np from sklearn.preprocessing import PowerTransformer, StandardScaler, MinMaxScaler from util import init def parse_args(run_name): parser = argparse.ArgumentParser(description=run_name) parser.add_argument('--scaler', type=str, defa...
11464509
from moto.core.exceptions import JsonRESTError class NotFoundException(JsonRESTError): code = 400 def __init__(self, message): super(NotFoundException, self).__init__("NotFoundException", message) class ValidationException(JsonRESTError): code = 400 def __init__(self, message): sup...
11464520
from core.models import Follow from core.models import Pin from django import forms from datetime import datetime class PinForm(forms.Form): item = forms.IntegerField() influencer = forms.IntegerField() remove = forms.IntegerField(required=False) def __init__(self, user, *args, **kwargs): sel...
11464524
from guillotina import error_reasons from guillotina import logger from guillotina import response from guillotina import task_vars from guillotina._settings import app_settings from guillotina.browser import View from guillotina.i18n import default_message_factory as _ from guillotina.interfaces import IRequest from g...
11464557
from PuzzleLib.Backend import gpuarray from PuzzleLib.Modules import SubtractMean, LCN from PuzzleLib.Visual import loadImage, showImage def main(): subtractMean = SubtractMean(size=7) lcn = LCN(N=7) img = gpuarray.to_gpu(loadImage("../TestData/Bench.png")) subtractMean(img) showImage(subtractMean.data.get(),...
11464628
from sqlalchemy import Column, String, Integer, ForeignKey, func, Text, Table, Boolean from models import models from models.models import Base, datetime_to_string, string_to_datetime, db, optional_encoded_field class SampleSubmission(Base): __tablename__ = 'sample_submission' name = Column(String(255), defa...