id
stringlengths
3
8
content
stringlengths
100
981k
3306065
from swsscommon import swsscommon from dvslib.dvs_database import DVSDatabase import ast class TestVirtualChassis(object): def set_lag_id_boundaries(self, vct): """This functions sets lag id boundaries in the chassis app db. In VOQ systems the lag id boundaries need to be set before confi...
3306093
import os import librosa import argparse import numpy as np import mmcv import pdb from math import pi from numpy import linalg as LA from scipy.signal import hilbert from data.stereo_dataset import generate_spectrogram import statistics as stat def get_content(value_list, text): if len(value_list) == 1: c...
3306098
import argparse from .finetune_bert import run as bert_run def set_bert_defaults(args): args.bert_model = args.model args.do_lower_case = "uncased" in args.model if args.learning_rate is None: args.learning_rate = 5e-5 if args.warmup_proportion is None: args.warmup_proportion = 0.1 ...
3306181
self.description = "Sysupgrade with a set of sync packages replacing a local one" sp1 = pmpkg("pkg2") sp1.replaces = ["pkg1"] sp2 = pmpkg("pkg3") sp2.replaces = ["pkg1"] for p in sp1, sp2: self.addpkg2db("sync", p) lp = pmpkg("pkg1") self.addpkg2db("local", lp) self.args = "-Su" self.addrule("PACMAN_RETCODE=0")...
3306190
import asyncio import signal from .util import Logger class FFMpeg: FFMPEG_BIN = "ffmpeg" def __init__(self, flags): self._logger = Logger("ffmpeg") self._ffmpeg = None self._flags = flags async def __aenter__(self): self._loop = asyncio.get_running_loop() self._f...
3306209
class Command(object): def __init__(self, **props): self.add = props.get('add') or [] self.remove = props.get('remove') or []
3306240
import numpy as np import torch from GPmodel.inference.inference import Inference from GPmodel.sampler.tool_partition import group_input from GPmodel.sampler.tool_slice_sampling import univariate_slice_sampling from GPmodel.sampler.priors import log_prior_constmean, log_prior_noisevar, log_prior_kernelamp def slice...
3306246
import math import random import pyglet from pyglet import gl WIDTH = 1024 HEIGHT = 768 ROTATION_SPEED = 200 ACCELERATION = 300 SPACESHIP_RADIUS = 40 START_LIVES = 3 SHOOT_DELAY = 0.3 LASER_SPEED = 500 LASER_RADIUS = 5 UFO_RADIUS = 45 UFO_SPEED = 50 UFO_ROTATION_SPEED = 4000 COLLISION_SPEED_FACTOR = 0.2 ASTEROID_SPEE...
3306258
import random import os ENVIRONMENT_VARIABLE = 'RANDOM_SEED' def set_random_seed_at_load_time(): seed = get_seed_from_environment_variable() set_random_seed(seed) def get_seed_from_environment_variable(): default_seed = get_default_seed() return os.getenv(ENVIRONMENT_VARIABLE, default_seed) def get_...
3306265
import argparse import io import os import re import subprocess import tempfile from rustfst_python_bench.algorithms.supported_algorithms import SupportedAlgorithms from rustfst_python_bench.constants import OPENFST_BINS, RUSTFST_CLI from rustfst_python_bench.utils import header_report def parse(): parser = argp...
3306288
try: # bis 1.8.x from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor from django.db.models.fields.related import ManyRelatedObjectsDescriptor from django.db.models.fields.related import ReverseManyRelatedObjectsDescriptor from django.db.models.fields.related import Forei...
3306319
from typing import Dict, List, Union class RequestHandler(object): def __init__(self, request: Dict): self.request = request def validate(self): """ Validate the request """ raise NotImplementedError def extract_request(self) -> Union[List,Dict]: """ ...
3306342
import re from tqdm import tqdm import logging from distributed import comm from utils import Colorer LINE_DISPLAY_FREQ = 0.1 log = logging.getLogger('main') C = Colorer.instance() class DistributedProgressDisplayer(object): """Progress logger for the distributed learning environment. Tqdm progress bars ar...
3306345
import json import getopt import sys import colorama import logging import colorlog import pandas as pd import datetime import select import psycopg2 as pg import psycopg2.extras as pgx import time import subprocess import os from sqlalchemy import create_engine from sqlalchemy.pool import NullPool #==================...
3306356
VERSION = (0, 2, 2) from django.conf import settings from django.contrib.auth import get_user, SESSION_KEY from django.core.cache import cache from django.db.models.signals import post_save, post_delete from django.utils.functional import SimpleLazyObject from django.contrib.auth.models import AnonymousUser try: ...
3306363
from packetbeat import BaseTest """ Tests for checking the procs monitoring configuration. """ class Test(BaseTest): MsgNotOnLinux = "Disabled /proc/ reading because not on linux" MsgEnabled = "Process matching enabled" def test_procs_default(self): """ Should be disabled by default. ...
3306364
import logging import sys import torch.distributed as dist class LoggerFactory: @staticmethod def create_logger(name=None, level=logging.INFO): """create a logger Args: name (str): name of the logger level: level of logger Raises: ValueError is na...
3306370
import os import numpy import onnx def is_equal_tensor_proto(a, b): name_a = a.name name_b = b.name a.name = "" b.name = "" res = a == b a.name = name_a b.name = name_b return res def node_replace_input_with(node_proto, name, new_name): for i, input_name in enumerate(node_p...
3306371
import functools from django import db from django.db import OperationalError from yawn.utilities import logger def close_on_exception(func): """ A wrapper to close the database connection if a DB error occurs, so that it will get re-opened on the next use. Squashes the exception and logs it. "...
3306398
from __future__ import division import numpy as np import numpy.linalg as la from ...utils import splogdet, spsolve from ...steps import metropolis from pysal.spreg.utils import spdot ############################# # SPATIAL SAMPLE METHODS # ############################# def logp_rho_cov(state, val): """ Th...
3306409
from backtester.features.feature import Feature import numpy as np import pandas as pd class ScoreFairValueFeature(Feature): @classmethod def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager): instrumentLookbackData = instrumentManager.getLookbackInstrumentFeatu...
3306448
import json import sys sys.path.insert(0, '../src') import index ## the Lambda source code file at ../src/index.py with open('events/alexa-start-session.json') as test_request: ## the request JSON stored in a separate file request_json = json.load(test_request) # print request_json myEvent = json.loads(...
3306456
from kivy.animation import Animation from kivy.clock import Clock from kivy.core.window import Window from kivy.metrics import dp from kivy.properties import BooleanProperty, ObjectProperty, StringProperty from kivy.uix.behaviors import ButtonBehavior from kivy.uix.image import Image from kivy.uix.recycleview import Re...
3306473
from corehq.messaging.scheduling.models import AlertSchedule, TimedSchedule from corehq.util.test_utils import unit_testing_only @unit_testing_only def delete_alert_schedules(domain): for schedule in AlertSchedule.objects.filter(domain=domain): schedule.delete_related_events() schedule.delete() ...
3306537
from func.db_mongo import * el = db['test'].find_one({'id': 1}) el['param 1'] = 'me' db['test'].save(el)
3306565
from django.contrib.auth.models import User from django.db.models import Sum from multidb.pinning import use_master from affiliates.base.management.commands import QuietCommand from affiliates.links.models import LeaderboardStanding class Command(QuietCommand): help = ('Populate the leaderboard with the latest ...
3306598
from onnx_tf.handlers.frontend_handler import FrontendHandler from onnx_tf.handlers.handler import onnx_op from onnx_tf.handlers.handler import tf_op from .math_mixin import ReductionMixin @onnx_op("ReduceMean") @tf_op("Mean") class ReduceMean(ReductionMixin, FrontendHandler): @classmethod def version_1(cls, nod...
3306604
import csv import xmltodict as xml import urllib.request import json from termcolor import colored in_file = './in.csv' store_ids = [215, 211] store_names = [] country_code = 'us' language_code = 'en' availability_base_url = 'https://www.ikea.com/' + country_code + '/' + language_code +'/iows/catalog/availability/' ...
3306609
from hamilton.function_modifiers import tag, extract_fields @tag(test='a') def a() -> int: return 0 @tag(test='b_c') @extract_fields({'b': int, 'c': str}) def b_c(a: int) -> dict: return {'b': a, 'c': str(a)} def d(a: int) -> int: return a
3306612
import FWCore.ParameterSet.Config as cms from Configuration.ProcessModifiers.run2_miniAOD_UL_cff import run2_miniAOD_UL from Configuration.ProcessModifiers.miniAOD_skip_trackExtras_cff import miniAOD_skip_trackExtras # This modifier is for additional settings to run miniAOD on top of # ultra-legacy (during LS2) Run-...
3306624
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm print('The 3 equations are entered individually, each value of the equation is entered separated by a space, for example: \ninput = 6 5 -3 4 \nThis will be equal to 6x + 5y- 3z = 4') print('Enter value...
3306647
from .direct_debit_payment_method import DirectDebitPaymentMethod from .direct_debit_payment_method_properties import DirectDebitPaymentMethodProperties from .direct_debit_payment_method_type import DirectDebitPaymentMethodType
3306660
from typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, Sequence import numpy as np import torch from torch.utils.data import DataLoader, Dataset, Sampler from torch.utils.data._utils.collate import default_collate from math import ceil from health_ml.utils.common_utils import _create_generator c...
3306664
from pathlib import Path from typing import Callable, List, Optional, Dict import cv2 import torch import pandas as pd from torch.utils.data import Dataset from transforms import tensor_transform N_CLASSES = 1103 DATA_ROOT = Path('./data') def build_dataframe_from_folder(root: Path, class_map: Optional[Dict] = No...
3306690
import numpy as np from dask.dataframe.extensions import make_array_nonempty from pandas.core.dtypes.dtypes import register_extension_dtype from ..geometry.line import Line, LineArray, LineDtype @register_extension_dtype class RingDtype(LineDtype): _geometry_name = 'ring' @classmethod def construct_arra...
3306732
import re import unittest def verifyOutputContains(output, value): for line in output: if value in line: return unittest.TestCase.assertTrue(unittest.TestCase(), False, "The value \'" + value + "\' not found in the cleos output") def verifyOutputContainsRegex(output, regex): for line...
3306760
import io import sys from os import listdir from os.path import join, dirname, abspath, isfile import shutil from shutil import copyfile import utils.config_loader as config from utils.config_loader import logger, path_parser import utils.tools as tools sys.path.insert(0, dirname(dirname(abspath(__file__)))) def ma...
3306775
from itertools import product import nose.tools as nt import numpy as np from scipy.stats import t as tdist from scipy.stats import laplace, logistic, norm as ndist from ..convenience import lasso, step, threshold from ..query import optimization_sampler from ...tests.instance import (gaussian_instance, ...
3306788
import base64 import importlib.util import io import os import re import sys import functools from hashlib import md5 from mimetypes import guess_type from os.path import dirname, abspath, split from urllib.parse import parse_qs def import_python_module_by_filename(name, module_filename): """ Import's a file ...
3306791
from __future__ import print_function # coding=utf-8 import os import sys import sqlite3 import logging logger = logging.getLogger(__file__) logging.basicConfig( format="[%(asctime)s - %(filename)s:line %(lineno)s] %(message)s", datefmt='%d %b %H:%M:%S', level=logging.INFO) logger.setLevel(...
3306809
from MBase.MFinalValueReachedException import MFinalValueReachedException class MValueAnimator: """ A class to animate single integer or float values. It would also help in applying various mathematical functions to the progress of the animation. """ def __init__(self, initial_value, final_val...
3306812
from django.core.exceptions import ValidationError from formation.render_base import Renderable class Unset: """A class that allows us to differentiate between None (or null) and a value that has not been set. """ def __bool__(self): return False UNSET = Unset() DEFAULT_CONTEXT_KEY = "...
3306819
import configparser import camera_calibration """ @author(s): <NAME>, <NAME> This initializes necessary directories and files. """ import os import numpy as np db_dir = 'database' im_dir = 'database/images' def initialize(config_path='config.ini'): """ Initializes the user settings and folders. Para...
3306825
import re import prompt_toolkit from prompt_toolkit.filters import is_searching, vi_insert_mode, emacs_insert_mode, is_read_only from prompt_toolkit.filters.utils import is_true from prompt_toolkit.document import Document shiftwidth = 2 indent_let = 4 indent_if = 3 indent_after_bare_where = 2 indent_before_where = 2 ...
3306886
import collections import ctypes import logging from .generated.vega10_pptable import * LOG = logging.getLogger(__name__) class UnknownRevId(KeyError): pass def parse_table(buffer, offset, type_select): header = Vega10_PPTable_Generic_SubTable_Header.from_buffer(buffer, offset) return type_select(hea...
3306927
import random import numpy as np import graph def gen(n: int): boxs = ['1', '2', '3'] balls = [ ['red', 'red', 'red', 'blue', 'yellow'], ['yellow', 'yellow', 'yellow', 'red', 'blue'], ['blue', 'blue', 'blue', 'red', 'yellow'] ] states = [] observations = [] for i in ran...
3306946
from pytorch_toolbelt.modules.pooling import GWAP from torch import nn class GlobalWeightedAvgPoolHead(nn.Module): """ 1) Squeeze last feature map in num_classes 2) Compute global average """ def __init__(self, feature_maps, num_classes: int, dropout=0.): super().__init__() self.f...
3307008
import HybridTut # import parameters file from netpyne import sim # import netpyne init module sim.createSimulateAnalyze(netParams = HybridTut.netParams, simConfig = HybridTut.simConfig) # create and simulate network # Check the model output: sim.checkOutput is used for testing purposes. Please comment out the fo...
3307024
import sbol3 X_COORDINATE_URI = 'http://example.org/my_vis#x_coordinate' Y_COORDINATE_URI = 'http://example.org/my_vis#y_coordinate' class ComponentExtension(sbol3.Component): """Override sbol3.Component to add two fields for visual display. """ def __init__(self, identity, types, *...
3307029
import socket def validateipv4ip(address): try: socket.inet_aton(address) print ("Correct IPv4 IP") except socket.error: print ("wrong IPv4 IP") def validateipv6ip(address): ### for IPv6 IP address validation try: socket.inet_pton(socket.AF_INET6,address) print ...
3307082
import causaldag as cd import time import numpy as np import matplotlib.pyplot as plt np.random.seed(1729) dags = cd.rand.directed_erdos(8, .5, 50) cpdags = [dag.cpdag() for dag in dags] arcs = np.array([len(dag.arcs) for dag in dags]) dir_arcs = np.array([len(cpdag.arcs) for cpdag in cpdags]) edges = np.array([len(cp...
3307114
if __name__ == "__main__": import json with open('all_stories.json', 'r') as infile: data = json.loads(infile.read()) allWords = set() for entry in data: allWords |= set(entry['words']) print('{} unique words in all the stories'.format(len(allWords))) print('{} documents total...
3307125
import contextlib import io import sys # Option 1 output_stream = io.StringIO() with contextlib.redirect_stdout(output_stream): help(pow) output_stream = output_stream.getvalue() print("value:", output_stream) # Option 2 with open("help.txt", "w") as f: with contextlib.redirect_stdout(f): help(pow)...
3307144
from bs4 import BeautifulSoup import yaml import requests import sqlite3 import timeit class DocSet(object): def __init__(self, name): self.name = name self.init_db() self.entries = [] @property def path(self): return '{name}.docset'.format(name = self.name) def ini...
3307149
import calendar import csv from base64 import b64encode from datetime import datetime from geopy.distance import vincenty from pokeconfig import Pokeconfig class Pokedata: pokedata = None @staticmethod def get(pokemon_id): if not Pokedata.pokedata: Pokedata.pokedata = {} w...
3307170
from djassembla.models import Space, Ticket from urllib2 import urlopen, Request, build_opener, HTTPHandler import base64 from djassembla.errors import AssemblaError from xml.dom.minidom import parseString from lxml import etree import urllib class Connection(object): _ROOT_URL = "https://www.assemb...
3307196
import os import shutil import socket import subprocess import sys import tempfile from pywincffi.core import dist from pywincffi.dev.testutil import TestCase from pywincffi.kernel32 import ( GetStdHandle, CloseHandle, GetHandleInformation, SetHandleInformation, DuplicateHandle, GetCurrentProcess, CreateEvent)...
3307227
import base64 import json import os import tempfile from textwrap import dedent from cryptography.fernet import Fernet import requests_mock from specter import Spec, DataSpec, expect from six.moves import urllib from moto import mock_ssm from pike.discovery import py import aumbry from aumbry.errors import LoadError,...
3307230
import os, h5py import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import LogNorm, Normalize plt.switch_backend('Agg') import time from vegan import discriminator as build_discriminator from vegan import generator as build_generator #Get ...
3307308
import re import subprocess from typing import List from nvhtop.process import CPUProcess class ProcessStatus(object): PS_FORMAT = "pid,user,%cpu,%mem,etime,command" PATTERN = re.compile(r"\s+") MAX_SPLIT = 5 def __init__(self, pids: List[int]) -> None: self._pids = pids self._comman...
3307342
import os from .root import * if os.name == 'nt': from .nt import get_nameservers elif os.name == 'posix': from .posix import get_nameservers
3307437
import numpy as np from numpy.testing import assert_almost_equal, assert_equal from scipy.io import loadmat from sklearn.cross_decomposition import CCA from meegkit.cca import cca_crossvalidate, nt_cca, mcca from meegkit.utils import multishift, tscov def test_cca(): """Test CCA.""" # Compare results with Ma...
3307462
from datetime import datetime import logging from django.shortcuts import render, redirect from django.template.response import TemplateResponse from django.utils import timezone from .pdf_render import Render from .forms import AddressForm from .forms import PropertyForm from .property import PropSetup from .context_d...
3307471
import time from types import GeneratorType from collections import Iterable from six import string_types from scrapinghub.client.frontiers import Frontiers, Frontier, FrontierSlot from ..conftest import TEST_FRONTIER_SLOT def _add_test_requests_to_frontier(frontier): slot = frontier.get(TEST_FRONTIER_SLOT) ...
3307486
import numpy as np from tqdm import trange import json import os import sys import tensorflow as tf from tensorflow.contrib import rnn utils_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) utils_dir = os.path.join(utils_dir, 'utils') sys.path.append(utils_dir) from model_utils i...
3307496
from http.server import HTTPServer from .run import handler def main(): server = HTTPServer(("localhost", 8080), handler) print("Starting server, use <Ctrl-C> to stop") server.serve_forever() if __name__ == "__main__": main()
3307502
from simple_playgrounds.engine import Engine from simple_playgrounds.playground.layouts import SingleRoom from simple_playgrounds.element.elements.conditioning import ColorChanging, FlipReward from simple_playgrounds.element.elements.activable import RewardOnActivation from simple_playgrounds.common.timer import Perio...
3307526
import bisect from biicode.common.utils.serializer import ListDeserializer class TimeBaseMap(tuple): ''' Two lists, first of time, second of ID or BlockVersionTable or set or Renames ''' def __new__(cls, data=None): if not data: obj = super(TimeBaseMap, cls).__new__(cls, ([], [])) ...
3307560
from subprocess import call, TimeoutExpired import fnmatch import sys import shutil import os import time # Current timeout set to 25 minutes, i.e. 25*60 seconds. #TIMEOUT=1500 TIMEOUT=600 THREADS=1 # Current number of executions is 1M. #EXECUTIONS=1000000 EXECUTIONS=350000 SEED=1 COMMAND='bughunt.exe' # Change work...
3307581
import io import unittest import chainer from chainer import testing class DummyTrainer(object): def __init__(self): self.elapsed_time = 0 class TestTimeTrigger(unittest.TestCase): def setUp(self): self.trigger = chainer.training.triggers.TimeTrigger(1) self.trainer = DummyTrainer...
3307600
class Colourable: @staticmethod def tikzify_colour(colour): """Turn colour into tikz Code""" if colour["name"] == colour["mix_with"] or colour["mix_percent"] == 0: if colour["strength"] == 100: return colour["name"] return colour["name"] + '!' + str(colour...
3307604
import glob import os import cv2 import numpy as np from scipy import ndimage from skimage.io import imread, imsave from skimage.measure import label, regionprops from skimage.transform import resize def get_percentile_intensity_in_mask_img(img, mask, percentile, max_intensity=220): values = img[np.nonzero(mask)]...
3307623
import os DB_HOST=os.environ.get('DB_HOST') DB_USER=os.environ.get('DB_USER') DB_PASS=os.environ.get('DB_PASS') DB_NAME=os.environ.get('DB_NAME') DEBUG=os.environ.get('PORT') is None PORT=os.environ.get('PORT') if not DB_HOST: from config import *
3307638
from FORMAT import Call_API from FORMAT import Json import json #XDCXRP #XLMXRP class Bitrue_API: def __init__(self): print("STart Bitrue API") self.Biture_Main() def Biture_Main(self): Asset_list = ["XDCXRP","XLMXRP"] #while True: output = Call_API.API_GET_Call("h...
3307648
import pytest from machinable import Experiment, Project from machinable.errors import ConfigurationError, MachinableError from machinable.view import from_element, get def test_view(): Project("./tests/samples/project").connect() with pytest.raises(ModuleNotFoundError): get("non.existing", Experiment...
3307655
import os import tensorflow as tf IMAGE_SIZE = 32 # Global constants describing the CIFAR-10 data set. NUM_CLASSES = 10 NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000 NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10000 def read_cifar10(filenames, use_queue=False): class CIFAR10Record(object): pass result = CIFAR10Record() ...
3307699
from collections import OrderedDict from .CloneValidation import CloneValidation class Clone: """Gather all informations necessary to validate a clone. Parameters ---------- name Name of the clone. Could be for instance a microplate well. digestions A dictionnary ``{digestion: CloneO...
3307723
import attr import pytest from typing import Optional, Text from sleap.nn.system import use_cpu_only use_cpu_only() # hide GPUs for test from sleap.nn.config import utils def test_one_of(): @utils.oneof @attr.s(auto_attribs=True) class ExclusiveClass: a: Optional[Text] = None b: Option...
3307727
from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from news.models import NewsItem class NewsFeed(Feed): def title(self): return u"%s" % Site.objects.get_current().name def description(self): return u'Latest news from %s'...
3307740
from flask import Blueprint room_api = Blueprint('room_api', __name__) @room_api.route('/api/v1/rooms', methods=['POST']) def create_room(): return '' @room_api.route('/api/v1/rooms', methods=['GET']) def get_rooms(): return '' @room_api.route('/api/v1/rooms/<room_id>', methods=['GET']) def get_room(room_id...
3307741
import attr import numpy as np import collections import itertools import pyrsistent import json import os import torch import torch.nn as nn import torch.nn.functional as F from tensor2struct.models import abstract_preproc, decoder from tensor2struct.modules import attention, variational_lstm, lstm, embedders from t...
3307744
API_STAGE = 'dev' APP_FUNCTION = 'raises_exception' APP_MODULE = 'tests.test_handler' BINARY_SUPPORT = False CONTEXT_HEADER_MAPPINGS = {} DEBUG = 'True' DJANGO_SETTINGS = None DOMAIN = 'api.example.com' ENVIRONMENT_VARIABLES = {} LOG_LEVEL = 'DEBUG' PROJECT_NAME = 'raises_exception' COGNITO_TRIGGER_MAPPING = {} EXCEPTI...
3307769
import jax import jax.numpy as jnp from flax import linen as nn import chex from jax.nn.initializers import ( glorot_normal, glorot_uniform, he_normal, he_uniform, kaiming_normal, kaiming_uniform, lecun_normal, lecun_uniform, xavier_normal, xavier_uniform, ) kernel_init_fn = { ...
3307786
from fypy.model.levy.LevyModel import LevyModel from fypy.model.FourierModel import Cumulants from fypy.termstructures.ForwardCurve import ForwardCurve from fypy.termstructures.DiscountCurve import DiscountCurve import numpy as np from scipy.special import gamma from typing import List, Tuple, Optional, Union class C...
3307801
import math import torch import torch.nn as nn from functions import * class ReLU(nn.Module): def forward(self, input): return relu(input) class Linear(nn.Module): r"""Applies a linear transformation to the incoming data: :math:`y = Ax + b` Args: in_features: size of each input sample...
3307826
from hacksport.docker import DockerChallenge, Netcat class Problem(DockerChallenge): # by overriding the setup class a challenge author can pass custom arguments # to the docker build process as well as specify custom descriptions for the # dynamically assigned ports def setup(self): # The us...
3307901
import sys, os, json import requests import psycopg2 from urllib3.filepost import encode_multipart_formdata ### # RUN AS USER UBUNTU ### # TODO: Update pipeline to use new nested dataset structure def main(): with open(inputfile, 'r') as inp: curr_group = { "sensor": None, # e.g. "co2...
3307910
from .Interface import IBroker, ISizer class BuyCashPercent(ISizer): def __init__(self, percent: float): self.__percent = percent super(BuyCashPercent, self).__init__() def amount(self, security: str, price: float, broker: IBroker) -> int: if price < 0.01: return 0 ...
3307914
from langcodes.util import data_filename LIST_KEYS = {'Description', 'Prefix'} def parse_file(file): """ Take an open file containing the IANA subtag registry, and yield a dictionary of information for each subtag it describes. """ lines = [] for line in file: line = line.rstrip('\n')...
3307941
from django.shortcuts import * from django.contrib.auth import views as auth_views from django.contrib.auth.decorators import * from django.contrib.auth.forms import PasswordResetForm from django.utils.decorators import method_decorator from django.contrib import messages from django.shortcuts import render_to_response...
3307981
from pyCompute.graph import Operation import pyCompute.graph import numpy class add(Operation): def __init__(self, tensor_x, tensor_y, name): super().__init__(inputs = [tensor_x, tensor_y], name = name) def compute(self, x, y): self.input_tensors = [x, y] return x + y class mat...
3307982
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() # Grab the version from bumpversion with open(path.join(here, ".v...
3308023
import csv from django.core.management.base import BaseCommand from django.contrib.contenttypes.models import ContentType from django.utils.encoding import smart_unicode class Command(BaseCommand): args = '' help = 'Helper to export CSV data' def handle(self, *args, **options): outdir = args[0] ...
3308056
import os import logging from sdmdl.sdmdl.config import Config from sdmdl.sdmdl.occurrences import Occurrences from sdmdl.sdmdl.gis import GIS from sdmdl.sdmdl.data_prep.presence_map import PresenceMap from sdmdl.sdmdl.data_prep.raster_stack import RasterStack from sdmdl.sdmdl.data_prep.presence_pseudo_absence import...
3308070
from .base import Formatter from .markdown import MarkdownFormatter from .html import HTMLFormatter _formatters = { 'markdown': MarkdownFormatter, 'html': HTMLFormatter, } def create(format_, outfile, *a, **k): return _formatters[format_](outfile, *a, **k)
3308078
import os import pickle import time import numpy as np import pandas as pd from pylearn2.datasets import DenseDesignMatrix from pylearn2.datasets.dense_design_matrix import DefaultViewConverter from pylearn2.format.target_format import OneHotFormatter from scipy.io import loadmat from scipy.signal import firwin, filtf...
3308116
import vigra import graph as agraph show = False verbose = 1 img = vigra.readImage('12074.jpg')[120:300,0:100,:] shape = img.shape[0:2] graph, liftedGraph = agraph.liftedGridGraph(shape=shape) # get primitive edge indicator localWeightsImage = vigra.filters.structureTensorEigenvalues(img ,0.5 , 1.0)[:,:,0]*-1.0 loc...
3308127
LEAGUE_IDS = { "BSA": 2013, "BL": 2002, "FL1": 2015, "PL": 2021, "ELC": 2016, "PD": 2014, "SA": 2019, "PPL": 2017, "DED": 2003, "CL": 2001 }
3308156
import pytest from maha.processors import FileProcessor, TextProcessor from tests.processors.test_base_processor import TestBaseProcessor class TestTextProcessor(TestBaseProcessor): __test__ = True @pytest.fixture() def processor(self, multiple_tweets: str): return TextProcessor.from_text(multip...
3308219
import os from subprocess import run as _run, PIPE def run(cmd, shell=True, check=True, stdout=PIPE, stderr=PIPE): return _run(cmd, shell=shell, check=check, stdout=stdout, stderr=stderr).stdout.decode() class Subvolume(object): """ basic wrapper around the CLI """ def __init__(self,...