id
stringlengths
3
8
content
stringlengths
100
981k
3356362
import time import datetime import os from django.conf import settings from django.core.management.base import NoArgsCommand from amazon.models import S3UploadQueue from amazon.utils import purge_queue class Command(NoArgsCommand): help = "Uploads video to s3 and deletes it from the server." def handle_noar...
3356381
import doctest import pytest from insights.tests import context_wrap from insights.parsers import alternatives from insights.parsers.alternatives import AlternativesOutput, JavaAlternatives from insights.parsers.alternatives import PythonAlternatives from insights.core import ParseException ALT_MTA = """ mta - status...
3356382
from pybrain.rl.agents.linearfa import LinearFA_Agent from pybrain.rl.learners.valuebased.linearfa import LSPI from pybrain.rl.experiments import EpisodicExperiment from environment import Environment from tasks import LSPIGotoTask from training import LinearFATraining x_g = 10 y_g = 30 task = LSPIGotoTask(butt_dist...
3356385
from collections import defaultdict from OpenGL.GLUT import glutGet, glutKeyboardFunc, glutMotionFunc, glutMouseFunc, glutPassiveMotionFunc, \ glutPostRedisplay, glutSpecialFunc from OpenGL.GLUT import GLUT_LEFT_BUTTON, GLUT_RIGHT_BUTTON, GLUT_MIDDLE_BUTTON, \ GLUT_WINDOW...
3356472
import re from app import template_constants as CONSTANTS from flask.ext.babel import gettext as _ from flask_wtf import Form from flask_wtf.file import FileField, FileAllowed from wtforms import fields, validators, widgets from wtforms import Form as NoCsrfForm from wtforms.validators import InputRequired, DataRequire...
3356479
import pytest from schwifty.checksum import algorithms @pytest.mark.parametrize( "account_code,algorithm_name", [ ("0009290701", "DE:00"), ("0539290858", "DE:00"), ("0001501824", "DE:00"), ("0001501832", "DE:00"), ("0094012341", "DE:06"), ("5073321010", "DE:06"...
3356520
import numpy as np import random def supervised_model_cv_fit_predict(X_train_df, y_train, X_test_df, model, runs=5): y_preds = [] for i in range(runs): random.seed(i) model.fit(X_train_df, y_train) y_pred = model.predict(X_test_df) y_preds.append(y_pred) return y_preds d...
3356533
from abc import ABCMeta, abstractmethod import os from stix_shifter_utils.utils import logger from stix_shifter_utils.utils.file_helper import read_json as helper_read_json from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers class BaseResultTranslator(object, metaclass=...
3356574
import re import logging from zorro.di import has_dependencies, dependency from .xcb import Keysyms, Core from .config import Config from .commands import CommandDispatcher hotkey_re = re.compile('^<[^>]+>|.$') log = logging.getLogger(__name__) @has_dependencies class KeyRegistry(object): keysyms = dependenc...
3356586
import pytest import yaml from tests import command as cmd from tests import config as conf from tests import template as tpl @pytest.mark.e2e_cpu def test_set_template() -> None: template_name = "test_set_template" template_path = conf.fixtures_path("templates/template.yaml") tpl.set_template(template_n...
3356606
import os print("enter the path to traverse: ") root_dir=input() if os.path.exists(root_dir): dir_count=0 file_count=0 for dir_name,sub_dir_list,file_list in os.walk(root_dir): print(dir_name) print("\n found directory:",dir_name) dir_count+=1 for file_name in file_list: ...
3356636
from PyQt5.QtWidgets import QHBoxLayout, QLabel, QSizePolicy, QVBoxLayout from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton from PyQt5.QtGui import QPixmap from PyQt5.QtCore import pyqtSignal, QTimer from PIL.ImageQt import ImageQt from client.client import Client from utils.video_stream import VideoStream...
3356659
import logging import os import pathlib import re import shutil import stat import subprocess import textwrap import click # check environment before prompting class SetupCommand(click.Command): def parse_args(self, ctx, args): logging.info("Checking for prerequisites...") # command/name/require...
3356666
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import os,sys,random,time import argparse from focalloss import * start_time = time.time() maxe = 0 for i in range(1000): x = torch.rand(12800, 2) * random.randint(1, 10) x = x.cuda() l = torch.rand(12800).ge(...
3356756
import abc from typing import Any from typing import Callable from typing import Optional from typing import Union import six from . import _hooks from .context import Context from .internal.compat import contextvars from .internal.logger import get_logger from .span import Span log = get_logger(__name__) _DD_CON...
3356838
import toml from lambda_cache import __version__ def test_version(): """ Test that version in __init.py__ matches pyproject.toml file """ with open('../pyproject.toml') as toml_file: config = toml.load(toml_file) version = config.get('tool').get('poetry').get('version') assert ...
3356842
from .YtMsg_pb2 import * import math class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, o): return Point(self.x + o.x, self.y + o.y) def __sub__(self, o): return Point(self.x - o.x, self.y - o.y) def __truediv__(self, o): return Po...
3356848
import os #tensorflow os.system("pip3 install --user --upgrade pip") os.system("pip3 install --user tensorflow") #PuLP os.system("sudo apt install glpk glpk-utils") os.system("pip3 install --user pulp") #networkx os.system("pip3 install --user networkx") #tqdm os.system("pip3 install --user tqdm")
3356852
import os, glob directory = "editor" files = set(glob.glob(os.path.join(directory, "**/*"), recursive=True)) times = {file: os.stat(file)[8] for file in files} try: while True: files2 = set(glob.glob(os.path.join(directory, "**/*"), recursive=True)) for file in files: if file not in fil...
3356855
from __future__ import absolute_import, unicode_literals import os from ...util.path import Path from ...util.six import ensure_text from ..via_template import ViaTemplateActivator class NushellActivator(ViaTemplateActivator): def templates(self): yield Path("activate.nu") yield Path("deactivat...
3356869
from ..core import IslamoWesternCalendar, SAT, SUN from ..registry_tools import iso_register @iso_register('BJ') class Benin(IslamoWesternCalendar): "Benin" # Civil holidays include_labour_day = True # Christian holidays include_easter_monday = True include_ascension = True include_whit_mo...
3356897
from modules.base_module import Module class_name = "Photosalon" class Photosalon(Module): prefix = "phsl" def __init__(self, server): self.server = server self.commands = {"bph": self.buy_photo, "shph": self.share_photo} async def buy_photo(self, msg, client): if not await sel...
3356952
import numpy as np def transform(dataset, rotation_center=0, slice_start=0, slice_stop=1): # Get the current volume as a numpy array. array = dataset.active_scalars dark = dataset.dark white = dataset.white angles = dataset.tilt_angles tilt_axis = dataset.tilt_axis # Dark and white data...
3356965
import logging from django.views.generic import View from django.http import JsonResponse from ...utils.linkcheck_utils import get_url_count logger = logging.getLogger(__name__) class LinkcheckStatsView(View): """ Return the linkcheck counter stats """ # pylint: disable=unused-argument def get...
3356967
import numpy as np def load_input(file_name): """Returns the vents from input file. Vents have shape (num_vents, 2, 2) where axis 1 is the x-y coordinate and axis 2 is the start or end point of the vent. """ with open(file_name, 'r') as file: s = file.read() lines = s.splitline...
3356988
import os #os.environ["CUDA_VISIBLE_DEVICES"]="0" import numpy as np import tensorflow as tf from tensorflow.contrib.rnn import LSTMCell, GRUCell import sys import time from sklearn.metrics import f1_score import random class rnn(object): ''' rnn modular add-on for capturing case-level-context parame...
3357047
import time from struct import pack import kibra.database as db import kitools from kibra.ktask import Ktask from kibra.shell import bash DHCP_CONFIG = '/etc/dibbler/server.conf' DHCP_DAEMON = 'dibbler-server' def ntp_server_opt(addr): '''Given a server address return the HEX formatted payload of DHCPv6 toption...
3357058
import serial import sys import time def scmload(port, hexfile): with serial.Serial(port, 115200, timeout=.01) as ser: ser.read(99999) print('Opened port') ser.write(b'.\r') while not b'*' in ser.read(): pass print('Got prompt') print(ser.read(80)) ...
3357073
import pytest import packerlicious.builder as builder class TestFileBuilder(object): def test_required_fields_missing(self): b = builder.File() with pytest.raises(ValueError) as excinfo: b.to_dict() assert 'required' in str(excinfo.value) def test_source_and_content_mut...
3357079
algorithm='ddpg' env_class='Gym' model_class='LowDim2x' environment = { 'name': 'Humanoid-v2', } model = { 'state_size': 376, 'action_size': 17, 'fc1_units': 400, 'fc2_units': 300 } agent = { 'action_size': 17, 'evaluation_only': True } train = { 'n_episodes': 100000, 'solve_scor...
3357083
import sys sys.path.append( "../../util" ) sys.path.append( "../../util/bert" ) from db_meta import * def get_used_glove( vec_prop_f, set_out, target_dic ): for v_f in vec_prop_f: for t in v_f[ PF_QTOKS ]: if t in target_dic: set_out.add( t ) elif t.lower() in t...
3357099
from '../scrapper' import scrapper from '../cleaner' import cleaner from '../classifier' import classifier from '../summarizer' import summarizer def main(keywords): return True
3357116
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchquantum as tq import copy from torchquantum.macro import C_DTYPE from torchpack.utils.logging import logger from typing import List, Dict, Iterable from torchpack.utils.config import Config from qiskit.providers.aer.noise...
3357126
import os import time import platform import logging import queue import fnmatch from collections import OrderedDict from substance.monads import * from substance.logs import * from substance.shell import Shell from substance.exceptions import (SubstanceError) from substance.utils import getSupportFile from substance....
3357147
import logging import re from typing import List import pandas as pd from staramr.blast.results.AMRHitHSP import AMRHitHSP logger = logging.getLogger('PlasmidfinderHitHSP') """ A Class storing a PlasmidFinder-specific BLAST hit/HSP. """ class PlasmidfinderHitHSP(AMRHitHSP): def __init__(self, file: str, blas...
3357165
import sys import yaml from pathlib import Path from mlspeclib.mlschema import MLSchema from mlspeclib.mlschemaenums import MLSchemaTypes from mlspeclib.mlobject import MLObject from mlspeclib.helpers import ( return_schema_name, convert_yaml_to_dict, decode_raw_object_from_db, ) from mlspeclib.experimenta...
3357188
import tensorflow as tf def default_dense_kwargs(): return dict( kernel_initializer=tf.keras.initializers.VarianceScaling( scale=1 / 3, mode='fan_in', distribution='uniform'), bias_initializer=tf.keras.initializers.VarianceScaling( scale=1 / 3, mode='fan_in', distribution='...
3357191
from .activeplan import ActivePlan from .joinobserver import JoinObserver class Plan(object): def __init__(self, expression, selector): self.expression = expression self.selector = selector def activate(self, external_subscriptions, observer, deactivate): join_observers = [] f...
3357193
import random import unittest from math import exp, sqrt class Test_Distributions(unittest.TestCase): def test_seeding(self): # Python's seeding is different so we can't hard code random.seed(1) a = random.uniform(1,5) random.seed(1) b = random.uniform(1,5) self.ass...
3357215
from __future__ import print_function from __future__ import absolute_import from __future__ import division from builtins import str from past.utils import old_div import anuga import math import numpy from anuga.structures.boyd_pipe_operator import boyd_pipe_function from anuga.structures.boyd_box_operator import to...
3357293
import numpy as np # Module loading import numpy.linalg as npla from devito.tools import memoized_meth, as_tuple from devito import Function, Constant, Dimension, clear_cache from sources import PointSource, Receiver from geom_utils import AcquisitionGeometry from twri_utils import applyfilt, compute_optalpha, applyf...
3357333
from string import ascii_letters, digits, punctuation import Print def bufferToHex(buffer, start, count): accumulator = '' for item in range(count): accumulator += '%02X' % buffer[start + item] + ' ' return accumulator def bufferToAscii(buffer, start, count): accumulator = '' fo...
3357338
import json import torch import numpy as np import argparse import pickle import pandas as pd from sklearn.metrics.pairwise import cosine_similarity from tqdm import tqdm from scipy.stats import spearmanr, pearsonr from transformers import BertModel, BertTokenizer, GPT2Tokenizer, GPT2LMHeadModel torch.manual_seed(2000...
3357391
from scitools.std import * # for curve plotting def f(t): return t**2*exp(-t**2) t = linspace(0, 3, 51) # 51 points between 0 and 3 y = f(t) plot(t, y, 'r-') xlabel('t') ylabel('y') legend('t^2*exp(-t^2)') axis([0, 3, -0.05, 0.6]) # t in [0,3], y in [-0.05,0.6] title('My First Easyviz Demo') savefig('plot...
3357426
class RegionError(Exception): """ 异常基类 """ class RegionNotFoundError(RegionError): """ 无此地区 """ class RegionNoSuperiorError(RegionError): """ 此地区无上级 """ class RegionNoSubordinateError(RegionError): """ 此地区无下级 """
3357449
from urllib.parse import unquote from wptserve.utils import isomorphic_decode, isomorphic_encode import importlib sleep = importlib.import_module("resource-timing.sleep") def main(request, response): index = isomorphic_encode(request.request_path).index(b"?") args = isomorphic_encode(request.request_path[ind...
3357463
import numpy as np import zengl from matplotlib import pyplot as plt ctx = zengl.context(zengl.loader(headless=True)) size = (256, 256) image = ctx.image(size, 'r32float') triangle = ctx.pipeline( vertex_shader=''' #version 330 vec2 positions[3] = vec2[]( vec2(-1.0, -1.0), ...
3357505
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules import Transformer class SynPG(nn.Module): def __init__(self, vocab_size, em_size, word_dropout=0.4, dropout=0.1): super(SynPG, self).__init__() self.vocab_size = vocab_size self....
3357525
from pixiedust.display.app import * from pixiedust.utils import Logger @PixieApp @Logger() class AppWithLogger(): @route() def main_screen(self): self.info("Calling default route") return "<div>hello world</div>" app = AppWithLogger() app.run()
3357529
import torch import torch.distributed as dist from torch.autograd.function import Function class SyncBatchNorm(Function): @staticmethod def forward(self, input, weight, bias, running_mean, running_var, eps, momentum, process_group, world_size): input = input.contiguous() count = torch.empty(...
3357537
import functools from copy import deepcopy from abc import abstractmethod, ABCMeta from ..compare import compare class BaseMatcher(object): """ BaseMatcher implements the basic HTTP request matching interface. """ __metaclass__ = ABCMeta # Negate matching if necessary negate = False def...
3357545
from copy import deepcopy from time import time import logging from django.core.cache import cache from django.db import transaction from sympy import symbols, And, Or, Implies, Equivalent from sympy.logic.boolalg import BooleanTrue from sympy.logic.inference import satisfiable from ringapp import models log = loggin...
3357570
from contextlib import suppress from functools import lru_cache from typing import Any, Dict, Generator, List import requests from hypothesis.strategies import SearchStrategy from ...constants import DEFAULT_RESPONSE_TIMEOUT from ...models import APIOperation, Case from ._hypothesis import PARAMETERS, get_case_strate...
3357651
from appenlight_client.utils import import_module, deco_func_or_method from appenlight_client.timing import time_trace ignore_set = frozenset() def add_timing(min_duration=0.15): module = import_module('django') if not module: return from django import template def gather_template(self, *ar...
3357696
from convlab2.util.dataloader.dataset_dataloader import * from convlab2.util.dataloader.module_dataloader import *
3357709
import torch import pytest import numpy as np import stribor as st from stribor.test.base import check_inverse, check_jacobian @pytest.mark.parametrize('input_shape', [(1, 1), (2, 10), (7, 4, 5), (2, 3, 4, 5)]) @pytest.mark.parametrize('dim', [-2, -1]) def test_cumsum(input_shape, dim): np.random.seed(123) tor...
3357764
import networkx as nx import os import sys class GetNext(object): def __init__(self, params): self.f = open(params["input_file"], "r") self.is_directed = params["is_directed"] self.n = params["num_new_nodes"] @staticmethod def dict_add(d, key, add): if key in d: ...
3357785
import os from .base import IntegrationTestBase from jirafs import constants class TestCloneIssue(IntegrationTestBase): def test_cloning_issue_basic(self): issue_path = os.path.join(self.path, "issue") data = { "description": "This is a test description", "summary": "This...
3357941
import asyncio import uuid from io import StringIO from craigslist.pipeline import KafkaPipeline, MetricsPipeline from craigslist.item import CraigsListItem from utils import asyncio_test def test_kafka_pipeline(): item = CraigsListItem( url='http://test.com/', city_code='chicago', title...
3357953
import gzip import os import pickle import subprocess import unittest from bsbolt.Utils.AlignmentEvaluation import AlignmentEvaluator from tests.TestHelpers import bsb_directory, z_test_of_proportion # generate simulated reads bsb_simulate_commands = ['python3', '-m', 'bsbolt', 'Simulate', '-...
3357966
from typing import TYPE_CHECKING from bxcommon.network.abstract_socket_connection_protocol import AbstractSocketConnectionProtocol from bxgateway.connections.abstract_relay_connection import AbstractRelayConnection from bxutils import logging if TYPE_CHECKING: from bxgateway.connections.abstract_gateway_node impo...
3358035
import logging import os import time from flask import Flask, request, jsonify import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration from deeppavlov import build_model logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) logger = logging.getLogg...
3358042
import os import doodad as dd import doodad.ec2 as ec2 import doodad.mount as mount import doodad.ssh as ssh from doodad.utils import EXAMPLES_DIR, REPO_DIR # Local run mode_local = dd.mode.Local() # Local docker mode_docker = dd.mode.LocalDocker( image="python:3.5", ) # or this! Run experiment via docker on an...
3358101
import logging import logging.handlers logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logfile = logging.handlers.RotatingFileHandler( "logfile_with_rotation.log", maxBytes=10, backupCount=3 ) logfile.setLevel(logging.DEBUG) formatter = logging.Formatter( "{asctime} - {name} - {levelname} ...
3358116
import unittest import pystac from pystac.cache import CollectionCache from pystac.serialization import ( identify_stac_object, identify_stac_object_type, merge_common_properties, ) from pystac.serialization.identify import STACVersionRange, STACVersionID from tests.utils import TestCases class Identify...
3358155
import enum import time from authlib.integrations.sqla_oauth2.client_mixin import OAuth2ClientMixin from authlib.integrations.sqla_oauth2.tokens_mixins import TokenMixin from sqlalchemy import Boolean, Column, Enum, ForeignKey, Index, Integer, String, Text from sqlalchemy.orm import relationship from anchore_engine.d...
3358205
import os import sys import numpy as np from shapeworks import * success = True def setspacingTest1(): img = Image(os.environ["DATA"] + "/la1-small.nrrd") img.setSpacing([2,2,2]) compareImg = Image(os.environ["DATA"] + "/spacing2.nrrd") return np.array_equal(img.spacing(), [2.0, 2.0, 2.0]) and img.compare(c...
3358246
from __future__ import absolute_import, division, print_function, unicode_literals from cosrlib.sources import Source import requests class UrlSource(Source): """ Source that actually fetches an URL. Use with caution! """ def get_partitions(self): if self.args.get("urls"): return [{ ...
3358300
from keras_cv_attention_models.resnet_family.resnext import ResNeXt, ResNeXt50, ResNeXt101, ResNeXt50D, ResNeXt101W from keras_cv_attention_models.resnet_family.resnet_quad import ResNetQ, ResNet51Q, ResNet61Q from keras_cv_attention_models.resnet_family.resnet_deep import ResNetD, ResNet50D, ResNet101D, ResNet152D, Re...
3358309
import keras.backend as K import tensorflow as tf # def sparse_accuracy_ignoring_last_label(y_true, y_pred): # nb_classes = K.int_shape(y_pred)[-1] # y_pred = K.reshape(y_pred, (-1, nb_classes)) # # y_true = K.one_hot(tf.to_int32(K.flatten(y_true)), # nb_classes + 1) # unpacked ...
3358313
from .rule import Rule from ..global_strings import * class FirstComeFirstServeRule(Rule): '''FirstComeFirstServe is a rule for resources, rather than nodes. If patient has not been to any other resource, then this resource will 'claim' it, so if the patient ever returns to the node this resource belongs t...
3358315
import os import time from functools import partial from absl import logging import tensorflow as tf from lib import utils, dataset class Trainer(object): """ Trainer class for ESRGAN """ def __init__( self, summary_writer, summary_writer_2, settings, model_dir="...
3358325
import pytest import tensorflow as tf import numpy as np from . import mltest slim = tf.contrib.slim def _mlp_broken_builder(x): return slim.stack(x, slim.fully_connected, [10, 1]) def _mlp_correct_builder(x): net = slim.stack(x, slim.fully_connected, [10, 10]) return slim.fully_connected(net, 1, activ...
3358349
def fun_rec(x,y,A): if(A[x][y]==0): print("yup!!") def wait1(): for i in range(10000): for j in range(1000): #loop #start of real prog #fun A = [[0,0,1,0,0,0,0,0,0,1,0], [0,0,1,0,0,0,1,0,0,1,0], [0,0,1,1,1,1,1,0,0,1,0], [0,0,0,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0,0,0], #11 columns 8 rows [0,...
3358397
nombre=input("Buen dia, proporcione su nombre: ") carro=input("Que carro le gustaria rentar? ") mensaje=input("Muy bien "+ nombre.title()+ " dejeme verificar la disponibilidad de un "+ carro.title()) print(mensaje)
3358418
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name='stox', packages=['stox'], version='0.5', description='Stock Price Prediction And Analysis', long_description=long_description, long_description_content_type="text/markdown", author=...
3358456
import confu.exceptions import confu.generator import confu.schema class MixedDict(confu.schema.Dict): """ Extended confu.schema.Dict object that prevents validation of its interior objects. Use for dictionaries that do not need validation or will get validated other ways, like in Vodka plugin or ...
3358466
import numpy as np from clifford._numba_utils import generated_jit import pytest @generated_jit(cache=True) def foo(x): from clifford.g3 import e3 def impl(x): return (x * e3).value return impl # Make the test fail on a failed cache warning @pytest.mark.filterwarnings("error") def test_function...
3358475
from finmag.util.mesh_templates import Box, Sphere, Nanodisk, EllipticalNanodisk from finmag.util.meshes import mesh_info, plot_mesh_with_paraview from finmag.normal_modes.deprecated.normal_modes_deprecated import * from finmag import example from finmag import sim_with, normal_mode_simulation from math import pi impor...
3358515
from collections import OrderedDict from copy import deepcopy import time import pytest import torch from torch import nn from torchgpipe import GPipe from torchgpipe.gpipe import verify_module def test_parameters(): model = nn.Sequential(nn.Linear(1, 1)) gpipe = GPipe(model, balance=[1], devices=['cpu'], c...
3358556
from collections import OrderedDict from typing import Optional, Any class ClsDict(OrderedDict): """ ClsDict is a dict that accepts (only) types as keys and will return its values depending on instance checks rather than equality checks. """ def __new__(cls, *args, **kwargs): """ C...
3358560
import numpy as np import mxnet as mx import argparse import cv2 import time from core.symbol import P_Net20, R_Net, O_Net from core.fcn_detector import FcnDetector from core.detector import Detector from tools.load_model import load_param from core.MtcnnDetector20 import MtcnnDetector def test_net(imgfile,prefix, ep...
3358603
import tensorflow as tf import model3 as M import numpy as np import resnet import cv2 class FaceResNet(M.Model): def initialize(self): self.resnet = resnet.ResNet([64,64,128,256,512], [3, 4, 14, 3], 512) def forward(self, x): feat = self.resnet(x) return feat tf.keras.backend.set_learning_phase(True) mo...
3358620
from pyBN.inference.marginal_exact.exact_bp import * from pyBN.inference.marginal_exact.ve_marginal import *
3358634
import pyb import os import sys print("sys.path =", sys.path) if os.getcwd() == '/sd': print("### SDCard detected ###") vars = ['0', '0'] try: with open("/sd/sd_check.vars", "r") as vars_file: vars = vars_file.read().split() except: pass hard_reset_count = int(vars[0]) ...
3358636
from sklearn.ensemble import AdaBoostClassifier from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn import metrics iris = datasets.load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) print("X_train:",len(X_train...
3358646
import os import time from threading import Thread import cpuinfo import GPUtil import psutil from tensorboardX import SummaryWriter class Monitor(Thread): """Monitor Class.""" def __init__(self, log_dir, delay=1, gpu_id=0, verbose=False): """Initialize monitor, log_dir and gpu_id are needed.""" ...
3358688
import sys from adafruit_mcp3xxx.analog_in import AnalogIn from logger.Logger import Logger, LOG_LEVEL from sensors.mcp3xxx.sensor import Sensor # Tested using Sun3Drucker Model SX239 # Wet Water = 287 # Dry Air = 584 AirBounds = 43700 WaterBounds = 13000 intervals = int((AirBounds - WaterBounds) / 3) class Soi...
3358693
import os import tensorflow as tf from tensorkit.log import logger, Color class Restore(object): def __init__(self): self._var_list = None self._restore_saver = None self._restore_optimistic = False self.restore_ckpt_file = None self._inited = False def init(self, va...
3358761
import pytest def test_annotation_with_subtype( testapp, submitter_testapp, annotation_dhs, annotation_ccre_2, annotation_dataset ): testapp.patch_json( annotation_dhs['@id'], {'annotation_subtype': 'all'}, status=200) # annotation_subtype can only be submitted with...
3358770
import pandas as pd import itertools from functools import partial from fastai.callbacks import CSVLogger def get_config_df(config): df = pd.DataFrame(list(itertools.product(*config.values())), columns=config.keys()) df.index = [f'model_{i+1}' for i in range(len(df))] return df def create_experiment(nm, ...
3358805
from torch import nn from .base_models import BaseEncoderMaskerDecoder from asteroid_filterbanks import make_enc_dec from asteroid_filterbanks.transforms import mag, magreim from ..masknn import norms, activations from ..utils.torch_utils import pad_x_to_y import warnings class DeMask(BaseEncoderMaskerDecoder): "...
3358813
from quarkchain.utils import sha3_256 from quarkchain.evm import utils """ Blooms are the 3-point, 2048-bit (11-bits/point) Bloom filter of each component (except data) of each log entry of each transaction. We set the bits of a 2048-bit value whose indices are given by the low order 11-bits of the first three double...
3358832
import tornado.web class FixTasks(tornado.web.UIModule): def embedded_css(self): return """ #tasks-table, .dataTable { table-layout: fixed; } #tasks-table th:nth-child(3), .dataTable th:nth-child(3) { width: 50px !important; } #tasks-table th:nth-child(4), .dataTable th:nth-child(4) { width: 1...
3358834
from ray import workflow @workflow.step def hello(name: str) -> str: return format_name.step(name) @workflow.step def format_name(name: str) -> str: return "hello, {}".format(name) @workflow.step def report(msg: str) -> None: print(msg) if __name__ == "__main__": workflow.init() r1 = hello.s...
3358851
import numpy as np import matplotlib.pyplot as plt from sklearn import datasets #blobs n_samples = 1500 blobs = datasets.make_blobs(n_samples=n_samples, centers=4, random_state=3) # plt.scatter(blobs[0][:,0],blobs[0][:,1]) # plt.show() cluster_0_points = [] cluster_1_points = [] cluster_2_points = [] cluster_3_points...
3358854
from django.contrib import admin from core.models import EventPageContent from .models import Sponsor, Donor class SponsorInline(admin.TabularInline): model = EventPageContent.sponsors.through extra = 1 verbose_name_plural = 'Sponsors' class SponsorAdmin(admin.ModelAdmin): list_display = ('id', 'na...
3358876
from .DVGeo import DVGeometry from .DVGeoAxi import DVGeometryAxi try: from .DVGeoVSP import DVGeometryVSP except ImportError: pass try: from .DVGeoESP import DVGeometryESP except ImportError: pass
3358888
import logging import os, sys, platform import pyyjj from kungfu.yijinjing.time import * LOG_MSG_FORMAT = '[%(nanotime)s] [%(loglevel)s] [%(process)6d/%(tid)-6d] [%(pathname)s:%(lineno)d#%(funcName)s] %(message)s' LOG_FILE_DATEEXT_FORMAT = '%Y-%m-%d' LOG_LEVELS = { 'trace': logging.DEBUG, 'debug': logging.DEB...
3358892
from django.forms import * from softdelete.models import * import logging class ChangeSetForm(ModelForm): class Meta: model = ChangeSet exclude = ('content_type', 'object_id',)