id
stringlengths
3
8
content
stringlengths
100
981k
11581134
class WosToolsError(Exception): """ Any exception known by wostools. """ class InvalidReference(WosToolsError, ValueError): """ Raised when we try to create an article out of an invalid reference. """ def __init__(self, reference: str): super().__init__(f"{reference} does not look...
11581141
from builtins import range import logging import numpy as np import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as mcolors logger = logging.getLogger(__name__) def _cmap_discretize(cmap, N): """Return a discrete colormap from the...
11581164
import decimal import hashlib import json import subprocess import zipfile from io import BytesIO from django.conf import settings class Alignment: LEFT = 'PKTextAlignmentLeft' CENTER = 'PKTextAlignmentCenter' RIGHT = 'PKTextAlignmentRight' JUSTIFIED = 'PKTextAlignmentJustified' NATURAL = 'PKText...
11581179
from model import magic from flask import Flask, request, Response import sqlite3 import json import threading from constants import CURRENT_YEAR, DATABASE_PATH import datetime app = Flask(__name__) database_path = DATABASE_PATH @app.route('/') def index(): response = Response({}) response.headers['Access-Co...
11581188
import logging from lib.plugins import Inspector from lib.util import findTyped import json """ Description: Executs a command remotely and returns the entire result of the command as the metric Metrics: The string of the result """ class Exec(Inspector): def __init__(self, driver, command, json = False, environmen...
11581194
from apple.util.condition_tools import ConditionOpcode def make_create_coin_condition(puzzle_hash, amount): return [ConditionOpcode.CREATE_COIN, puzzle_hash, amount] def make_assert_aggsig_condition(pubkey): return [ConditionOpcode.AGG_SIG_UNSAFE, pubkey] def make_assert_my_coin_id_condition(coin_name): ...
11581224
import tensorflow as tf import numpy as np class Model(object): def __init__(self, args): self.args = args self.global_step = tf.train.get_or_create_global_step() with tf.name_scope('init_variables'): self.utterances = tf.placeholder( tf.int64, [args.batch_size...
11581226
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: # 判断速度 k 是否满足条件 def help(k: int) -> boolean: cnt = 0 for pile in piles: cnt += (pile - 1) // k + 1 return cnt <= H l, h = 1, max(piles) while l <= h: ...
11581234
import nose.tools as nt import numpy as np import theano import theano.tensor as T import treeano import treeano.nodes as tn from treeano.sandbox.nodes import gradient_normalization as gn fX = theano.config.floatX def test_gradient_batch_normalization_op(): epsilon = 1e-8 op = gn.GradientBatchNormalization...
11581298
from ._showscale import ShowscaleValidator from ._reversescale import ReversescaleValidator from ._colorsrc import ColorsrcValidator from ._colorscale import ColorscaleValidator from ._colorbar import ColorBarValidator from ._color import ColorValidator from ._cmin import CminValidator from ._cmax import CmaxValidator ...
11581335
from direct.distributed.DistributedObject import DistributedObject from GameStatManagerBase import GameStatManagerBase class DistributedGameStatManager(DistributedObject, GameStatManagerBase): from direct.directnotify import DirectNotifyGlobal notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGa...
11581370
from brancher.standard_variables import NormalVariable, DeterministicVariable import brancher.functions as BF from numpy import sin ## a = DeterministicVariable(1.5, 'a') b = DeterministicVariable(0.3, 'b') c = DeterministicVariable(0.3, 'c') d = BF.sin(a + b**2)/(3*c) ## print(d)
11581385
import requests import json from typing import List, Dict, Any, Union import logging log = logging.getLogger() def bls_api_query_v1( start: str = "2011", end: str = "2020", series_id: List[str] = ["CUUR0000SA0", "SUUR0000SA0"], ) -> Dict[str, Any]: """ Read a series from the BLS API, V1. Series ...
11581394
import copy from typing import Union, Callable, List from ..event import SimaiNote, NoteType from ..maisxt import ( MaiSxt, HoldNote as SDTHoldNote, SlideStartNote as SDTSlideStartNote, ) from ..simai import ( SimaiChart, pattern_to_int, TapNote, HoldNote, SlideNote, TouchHoldNote, ...
11581417
import dataclasses from koala.typing import * from koala.utils import to_dict JsonVar = TypeVar("JsonVar", bound='JsonMessage') __json_mapper: Dict[str, Any] = dict() def register_model(cls): global __json_mapper __json_mapper[cls.__qualname__] = cls def find_model(name: str) -> Optional[Type['JsonMessage'...
11581451
import pytest pytestmark = [pytest.mark.django_db] def test_no_invitation_when_no_room_url_is_defined(shipment, invite_to_clickmeeting, invite_to_zoomus): shipment = shipment() shipment() invite_to_clickmeeting.assert_not_called() invite_to_zoomus.assert_not_called() def test_invite_to_clickmeeti...
11581479
from abc import ABC, abstractmethod from collections import defaultdict from easydict import EasyDict from utils import import_module class BaseCommander(ABC): @abstractmethod def get_collector_task(self) -> dict: raise NotImplementedError class NaiveCommander(BaseCommander): def __init__(self...
11581494
from __future__ import print_function, absolute_import import time import torch import torch.nn as nn from torch.nn import functional as F import torch.distributed as dist from .utils.meters import AverageMeter class Trainer(object): ############################# # Training module for # 1. "NetVLAD: CNN ...
11581529
import os.path from os.path import abspath import re import sys import types import pickle from test import support import test.test_importlib.util import unittest import unittest.mock import unittest.test class TestableTestProgram(unittest.TestProgram): module = None exit = True default...
11581551
import os import os.path import sys xdg = os.getenv('XDG_CONFIG_HOME') or os.path.join(os.getenv('HOME'), '.config') conffile = os.path.join(xdg, 'pytyle3', 'config.py') if not os.access(conffile, os.R_OK): conffile = os.path.join('/', 'etc', 'xdg', 'pytyle3', 'config.py') if not os.access(conffile, os.R_OK):...
11581553
import cv2 image = cv2.imread("../assets/img.png") scale_rate = 0.5 height = int(image.shape[0] * scale_rate) width = int(image.shape[1] * scale_rate) image_resized = cv2.resize(image, (width, height)) cv2.imshow("Resized Image", image_resized) cv2.waitKey(0)
11581559
from __future__ import print_function import sys, os, numpy, h5py from pyglib.mbody.coulomb_matrix import U_J_to_radial_integrals, \ radial_integrals_to_U_J def h5save_usr_qa_setup(material, log=sys.stdout): ''' A list of questions to be answered to initialize the CyGutz job. ''' f = h5py.File...
11581674
import imp import os import sys from gpcheckcat_modules.foreign_key_check import ForeignKeyCheck from mock import * from gp_unittest import * class GpCheckCatTestCase(GpTestCase): def setUp(self): self.logger = Mock(spec=['log', 'info', 'debug', 'error']) self.db_connection = Mock(spec=['close',...
11581737
import torch import fused_layer_norm_cuda from apex.normalization import FusedLayerNorm import pyprof2 pyprof2.init() pyprof2.wrap(fused_layer_norm_cuda, 'forward') pyprof2.wrap(fused_layer_norm_cuda, 'backward') pyprof2.wrap(fused_layer_norm_cuda, 'forward_affine') pyprof2.wrap(fused_layer_norm_cuda, 'backward_affine...
11581815
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='pyeventbus', version='0.5', description='A Python EventBus', long_description=readme(), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :...
11581825
from __future__ import absolute_import import sys from unittest import TestCase from plotly.optional_imports import get_module class OptionalImportsTest(TestCase): def test_get_module_exists(self): import math module = get_module("math") self.assertIsNotNone(module) self.assertEqu...
11581869
from WhatsAppManifest import ADB, Automator from WhatsAppManifest.automator.android import AndroidContacts # Note: We need the AdbServer class (even without using SSH) so that Automator can open the internal connection. with ADB(use_ssh=False) as AdbServer: automator = Automator(adb_server=AdbServer, adb_host="127...
11581891
import os from pytest import fixture from colab_ssh.utils import expose_env_variable @fixture() def bash_rc_path(): bash_rc_path = "./.bashrc" yield bash_rc_path os.remove(bash_rc_path) def test_env_var(bash_rc_path): os.system(f"echo 'previous stuff' >> {bash_rc_path}") os.environ["COLAB_SSH_TEST_ENV_VAR"] =...
11581957
import unittest from records_mover.db.bigquery.bigquery_db_driver import BigQueryDBDriver from records_mover.records.records_format import DelimitedRecordsFormat from mock import MagicMock, Mock, patch import sqlalchemy from sqlalchemy_bigquery import BIGNUMERIC class TestBigQueryDBDriver(unittest.TestCase): @p...
11581987
import torch import torch.nn.functional as F import numpy as np import copy import pdb from collections import OrderedDict as OD from collections import defaultdict as DD torch.random.manual_seed(0) ''' For MIR ''' def overwrite_grad(pp, new_grad, grad_dims): """ This is used to overwrite the gradients wi...
11582011
import random import os import numpy as np import cv2 import torch from torchvision.transforms import functional as F from utils import ( generate_shiftscalerotate_matrix, ) class Compose: def __init__(self, transforms): self.transforms = transforms def __call__(self, img, target): for ...
11582100
import io import json import textwrap import time from docker.errors import NotFound DEFAULT_TEST_IMAGE_NAME = 'locationlabs/zzzdockertestimage' BASE_IMAGE = "alpine:3.4" def _normalize_image_id(image_id): """ The image IDs we get back from parsing "docker build" output are abbreviated to 12 hex digits. ...
11582124
from __future__ import annotations import fnmatch import re import threading from collections import OrderedDict from typing import Any, Dict, FrozenSet LANGUAGE = 'en' MINIMUM_WAIT = 60 EXTRA_WAIT = 30 EXTRA_WAIT_JOIN = 0 # Add this many seconds to the waiting time for each !join WAIT_AFTER_JOIN = 25 # Wait at leas...
11582164
import unittest from datetime import datetime, timedelta from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import IntegrityError from django.test import TestCase from django.test.client import Client from django.utils.translation import ugettext as _ from wouso.core...
11582218
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name='netCDF4-enhancement', version='0.1.2', author='<NAME>', author_email='<EMAIL>', description='Extends the default NetCDF4 driver by providing helpful' ' functionality like r...
11582221
import logging import numpy as np from . import IRCdata, IRCfollowing, addIntcos, convcheck, hessian, history, intcosMisc from . import optparams as op from . import stepAlgorithms, testB from .exceptions import AlgError, IRCendReached, OptError from .linearAlgebra import lowest_eigenvector_symm_mat, symm_mat_inv, sy...
11582232
from __future__ import absolute_import, division, print_function from telnyx.api_resources.abstract import ( CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource, ) class TelephonyCredential( CreateableAPIResource, DeletableAPIResource, ListableAPIResour...
11582234
import logging import re import json import os import tarfile import zipfile from abc import ABCMeta, abstractmethod import requests log = logging.getLogger(__name__) CHUNK_SIZE = 32768 class BaseDownloader: __metaclass__ = ABCMeta def __init__(self, target_dir): self.target_dir = target_dir ...
11582245
from typing import Any, Dict, Tuple import vapoursynth as vs from lvsfunc.misc import source from vardautomation import FileInfo, PresetAAC, PresetBD, VPath from project_module import chain, encode core = vs.core # Sources JP_BD = FileInfo(r'BDMV/GRANBLUE_FANTASY_SEASON2_7/BDMV/STREAM/00008.m2ts', (None, -24), ...
11582288
from .losses import wind_mean_squared_error from .util import agg_window,create_windowed_arr,save_multiple_graph,get_output,gather_auc_avg_per_tol,join_mean_std import matplotlib.pyplot as plt from keras.models import Sequential, Model import numpy as np import pandas as pd import os class Params(object): """ ...
11582294
import logging import sys from pathlib import Path from datetime import datetime from Pegasus.api import * logging.basicConfig(level=logging.DEBUG) PEGASUS_LOCATION = "/usr/bin/pegasus-keg" # --- Work Dir Setup ----------------------------------------------------------- RUN_ID = "black-diamond-5.0api-" + datetime....
11582313
from typing import Union import hither2 as hi def test_sorting(sorter_func, *, show_console=True, job_handler: Union[None, hi.JobHandler]=None): import sortingview as sv recording_name = 'paired_kampff/2014_11_25_Pair_3_0' recording_uri = 'sha1://a205f87cef8b7f86df7a09cddbc79a1fbe5df60f/2014_11_25_Pair_3_...
11582331
import sys import ast import re import mongoengine as me import rmc.shared.constants as c import rmc.models as m # Normalize critique scores to be in [0, 1] def normalize_score(score): return (score['A'] * 4 + score['B'] * 3 + score['C'] * 2 + score['D']) / 400.0 def clean_name(name): return re...
11582345
import numpy as np from numpy.typing import ArrayLike from scipy.interpolate import PPoly, lagrange def interp_rolling_lagrange(x: ArrayLike, y: ArrayLike, order: int) -> PPoly: x = np.asarray(x) y = np.asarray(y) # make sure x is sorted assert np.all(x[:-1] < x[1:]) assert len(x) > order if...
11582346
from Instrucciones.TablaSimbolos.Instruccion import Instruccion from Instrucciones.TablaSimbolos.Simbolo import Simbolo from Instrucciones.TablaSimbolos.Tipo import Tipo_Dato, Tipo from datetime import datetime class Now(Instruccion): def __init__(self, strGram,linea, columna): Instruccion.__init__(self,...
11582380
import pytest from add_trailing_comma._main import _fix_src @pytest.mark.parametrize( 'src', ( 'from os import path, makedirs\n', 'from os import (path, makedirs)\n', 'from os import (\n' ' path,\n' ' makedirs,\n' ')', ), ) def test_fix_from_import_no...
11582391
import logging from backend.utils.rlgarage_handler import RLGarageAPI logger = logging.getLogger(__name__) def get_car(index: int) -> str: try: return RLGarageAPI().get_item(index)['name'] except KeyError: logger.warning(f"Could not find car: {index}.") return "Unknown" except: ...
11582424
from genericpath import isfile FONTS_FOLDER = 'fonts' FONTS_ALIASES = {'lange': 'engraversmtbold', 'lange_thin': 'engr', 'patek_date': 'steelfish.regular'} def get_font_def(font_name): font_path = f'{FONTS_FOLDER}/{font_name}.ttf' if not isfile(font_path): if font_name not in FONTS_...
11582438
import sys import os import argparse import logging import json import time import cv2 import numpy as np import torch from torch.utils.data import DataLoader from torch.autograd import Variable from torch.nn import functional as F sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../') torch.manual_s...
11582485
import discord from utils import emojis from utils.funcs import get_platform_emoji from .context import Context from .exceptions import NoChoice, CannotEmbedLinks PageT = str | dict | discord.Embed class Paginator(discord.ui.View): def __init__(self, pages: list[discord.Embed | str], *, ctx: "Context", **kwarg...
11582493
expected_output = { "vrf": { "default": { "vrf_index": "0x60000000", "interfaces": { "TenGigE0/3/0/0": { "interface_index": "0xa0004c0", "enabled": { "LDP interface": { "via": "config"} ...
11582539
from __future__ import print_function import sys if not sys.argv[1:]: from subprocess import Popen, PIPE p = Popen([sys.executable, __file__, 'subprocess'], stdin=PIPE, stdout=PIPE, stderr=PIPE) out, err = p.communicate(b'hello world\n') code = p.poll() assert p.poll() == 0, (out, err, code) as...
11582542
from django.conf.urls.defaults import patterns, url, include from hyperadmin.resources.directory.resources import ResourceDirectory #gets replaced class SiteResource(ResourceDirectory): resource_class = 'resourcelisting' auth_resource = None @property def auth_resource(self): return self....
11582549
import os.path as osp import tempfile import numpy as np import pytest import torch from mmocr.models.textrecog.convertors import BaseConvertor, CTCConvertor def _create_dummy_dict_file(dict_file): chars = list('helowrd') with open(dict_file, 'w') as fw: for char in chars: fw.write(char ...
11582569
import sklearn.cluster import sklearn.metrics.cluster def cluster_by_kmeans(X, nb_clusters): """ xs : embeddings with shape [nb_samples, nb_features] nb_clusters : in this case, must be equal to number of classes """ return sklearn.cluster.KMeans(nb_clusters).fit(X).labels_ def calc_normalized_mu...
11582573
import io, os, sys def combineSubdirs(dirname, has_hdr_line): if not os.path.isdir(dirname): return print(dirname) subdirs = [dirname + '/' + x for x in os.listdir(dirname) if os.path.isdir(dirname + '/' + x)] if len(subdirs) == 0: return all_files = set(os.listdir(subdirs[0])) for subdir in su...
11582577
def isPalindrome(s): if len(s) <= 1: return ("Palindrome") return s[0] == s[-1] and isPalindrome(s[1:-1]) # give input like isPalindrome([1, 2, 2, 1])
11582638
import unittest import numpy as np import torch from rlil import nn from rlil.environments import Action from rlil.policies.deterministic import DeterministicPolicyNetwork from rlil.memory import ExperienceReplayBuffer from rlil.initializer import get_replay_buffer, get_n_step from rlil.utils import Samples class Moc...
11582647
import pytest import os from textwrap import dedent from ...preprocessors import LimitOutput from .base import BaseTestPreprocessor from .. import create_code_cell, create_text_cell @pytest.fixture def preprocessor(): return LimitOutput() class TestLimitOutput(BaseTestPreprocessor): def test_long_output(s...
11582656
from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import models.models as models import torch from torch import nn from torch.autograd import Variable import torchvision import torchvision.datasets as dsets import torchvision.transforms as tr...
11582767
from dataset import * from post_process import Post_Process_CR from visualize import * from forward import * from evaluation.eval_func import * # utils from libs.utils import _init_fn from libs.load_model import * def prepare_dataloader(cfg, dict_DB): # train dataloader if cfg.run_mode == 'train': da...
11582776
org_all_repos = """ query ($owner: String!, $endCursor: String) { organization(login: $owner) { repositories(first: 100, after: $endCursor) { pageInfo { hasNextPage endCursor } totalCount edges { node { nameWithOwner name isPrivate ...
11582789
import numpy as np from gym import utils from gym.envs.mujoco import mujoco_env class PusherMugEnv(mujoco_env.MujocoEnv, utils.EzPickle): def __init__(self): utils.EzPickle.__init__(self) mujoco_env.MujocoEnv.__init__(self, 'pusher_mug.xml', 5) def _step(self, a): vec_1 = self.get_bod...
11582791
import argparse import colour import inspect import importlib import os import sys import yaml from contextlib import contextmanager from screeninfo import get_monitors from manimlib.utils.config_ops import merge_dicts_recursively from manimlib.utils.init_config import init_customization from manimlib.logger import lo...
11582804
import enum class CurrentMediaStateValues(enum.IntEnum): """States that a TV can be.""" PLAYING = 0 PAUSED = 1 STOPPED = 2 class TargetMediaStateValues(enum.IntEnum): """States that a TV can be set to.""" PLAY = 0 PAUSE = 1 STOP = 2 class RemoteKeyValues(enum.IntEnum): """Key...
11582816
import abc from typing import ( Dict, Any, TypeVar, Sequence, NamedTuple, Optional, List, Union, Generic, ) import torch EnvType = TypeVar("EnvType") DistributionType = TypeVar("DistributionType") class RLStepResult(NamedTuple): observation: Optional[Any] reward: Optional...
11582841
from __future__ import absolute_import from __future__ import division from __future__ import print_function from easydict import EasyDict as edict import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import model_urls from torchvision.models.resnet import BasicBl...
11582877
import aiohttp import pytest @pytest.fixture(scope="function", name="http_session") @pytest.mark.asyncio def create_session(): session = aiohttp.ClientSession() yield session session.close()
11582885
from distutils.core import setup setup(name='pybilt', version='0.3.0', description='Lipid bilayer analysis toolkit.', author='<NAME>', author_email='<EMAIL>', url='http://pybilt.readthedocs.io/en/latest/index.html', packages=['pybilt', 'pybilt.bilayer_analyzer', 'pybilt.common', ...
11582915
import boto3 import decimal import json import os ALARM_NAME_PREFIX = 'InstanceAlarm:' ALARM_TEMPLATES_BUCKET = os.environ['ALARM_TEMPLATES_BUCKET'] ALARM_TEMPLATES_CACHE = {} # Maximum number of alarms to delete per API call. DELETE_ALARMS_MAX_NAMES = 100 autoscaling = boto3.client('autoscaling') cloudwatch = bot...
11582916
import uvicore from uvicore.typing import Any, Dict, Optional, List from starlette.exceptions import HTTPException as _HTTPException from uvicore.http import status # This is how you could do it, if you wanted to log #log = lambda : uvicore.log.name('uvicore.http') # See https://www.restapitutorial.com/httpstatuscode...
11583025
from .dqn import DeepQNetwork from .drqn import DeepRecurrentQNetwork from .a2c import AdvantageActorCritic
11583044
from .Base import Base from pegasus.tools import run_find_markers class FindMarkers(Base): """ Find markers using gradient boosting. Usage: pegasus find_markers [options] <input_data_file> <output_spreadsheet> pegasus find_markers -h Arguments: input_data_file Single cell data after running the de_...
11583053
import scanpy as sc import numpy as np import scipy as sp from skmisc.loess import loess from statsmodels.stats.multitest import multipletests from scipy.stats import rankdata import pandas as pd import time def score_cell(data, gene_list, gene_weight=None, suffix='', ...
11583066
from item import Item import pygame import unittest from buffalo import utils import random utils.init() class TestItem: def test_init(self): i = Item("test") assert i.name == "test" assert i.quantity == 1 #assert i.info["maxQuantity"] == 99 def test_unknown_item(self): i...
11583107
import unittest class RandomSelfTestCase(unittest.TestCase): def testRandomSelf(self): import hnswlib import numpy as np dim = 16 num_elements = 10000 # Generating sample data data = np.float32(np.random.random((num_elements, dim))) # Declaring index ...
11583155
from setuptools import setup, find_packages setup( name="simulation_based_calibration", version="0.0.1", description='PyMC3 implementation of "Simulation Based Calibration"', author="<NAME>", url="http://github.com/colcarroll/simulation_based_calibration", packages=find_packages(), install_...
11583167
import torch import itertools # At pain of messing up a good thing, also collect standard deviation (total) -- divided by total items for average def update_info_dict(info_dict, labels, preds, threshold=0.5, std=None): preds = (torch.tensor(preds) > threshold).long() labels = (torch.tensor(labels) > threshold)...
11583168
from Compiler.types import * from Compiler.instructions import * from Compiler.util import tuplify,untuplify from Compiler import instructions,instructions_base,comparison,program import inspect,math import random import collections from Compiler.library import * from Compiler.types_gc import * from operator import i...
11583218
from django import template from socialregistration.templatetags import resolve, get_bits register = template.Library() @register.tag def openid_form(parser, token): """ Render OpenID form. Allows to pre set the provider:: {% openid_form "https://www.google.com/accounts/o8/id" %} Also creates custo...
11583231
from django.test import SimpleTestCase from mock import Mock, patch from cms.serializers import LandingPageSerializer class LandingPageSerializerTestCase(SimpleTestCase): def test_serialize(self): landing_page = Mock() landing_page.fields = { 'navbar_title_value': 'a', 'n...
11583246
import torch def bbox_is_valid_vectorized(bbox: torch.Tensor): validity = bbox[..., :2] < bbox[..., 2:] return torch.logical_and(validity[..., 0], validity[..., 1])
11583265
import diffractsim diffractsim.set_backend("CPU") #Change the string to "CUDA" to use GPU acceleration from diffractsim import MonochromaticField, GaussianBeam,Lens,ApertureFromImage, nm, mm, cm F = MonochromaticField( wavelength=488 * nm, extent_x=19. * mm, extent_y=19. * mm, Nx=2000, Ny=2000,intensity = 0.2 ) ...
11583290
import socket from queue import Queue import turtle from turtle import Turtle from threading import Thread, current_thread from port import PORT serverSocket = None cmd_queue = Queue() class Move: def __init__(self, parts): self.name = parts[0] self.x = int(parts[1]) self.y = int(parts[2])...
11583298
from . import * # Declaration of models available __all__=[ 'oicr_lambda_log_distillation', ]
11583338
import _osx_support # -- Import it For Mac Users # import os -- For Windows Users from tkinter import * from tkinter import filedialog, colorchooser, font from tkinter.messagebox import * from tkinter.filedialog import * def change_color(): color = colorchooser.askcolor(title="pick a color...or else") text_ar...
11583373
import numpy as np import pytest import scipy.stats as st from sklearn.decomposition import PCA from Starfish.emulator._utils import ( get_w_hat, get_phi_squared, get_altered_prior_factors, Gamma, ) class TestEmulatorUtils: @pytest.fixture def grid_setup(self, mock_hdf5_interface): fl...
11583378
from django.contrib.contenttypes.models import ContentType from django import forms from hyperadmin.resources.models.resources import InlineModelResource class GenericInlineModelResource(InlineModelResource): model = None ct_field = "content_type" ct_fk_field = "object_id" def post_register(self...
11583383
from numpy.random import random_integers from numpy.random import randn import numpy as np import timeit import argparse import matplotlib.pyplot as plt from joblib import Parallel from joblib import delayed import multiprocessing as mp def simulate(size): n = 0 mean = 0 M2 = 0 speed = randn(10000) ...
11583387
from debpackager.packages.general_package import GeneralPackage from debpackager.utils.general import create_virtual_env, \ install_deb_dependencies import debpackager.packages.conf.configurations as cfg class Python(GeneralPackage): def __init__(self, kwargs): super(Python, self).__init__(**kwargs) ...
11583393
import asyncio import os import pytest import sys import tempfile import time import ray from ray._private.test_utils import Semaphore def test_nested_tasks(shutdown_only): ray.init(num_cpus=1) @ray.remote class Counter: def __init__(self): self.count = 0 def inc(self): ...
11583405
from collections import Counter # Score categories ONES = "ONES" TWOS = "TWOS" THREES = "THREES" FOURS = "FOURS" FIVES = "FIVES" SIXES = "SIXES" FULL_HOUSE = "FULL_HOUSE" FOUR_OF_A_KIND = "FOUR_OF_A_KIND" STRAIGHT = "STRAIGHT" LITTLE_STRAIGHT = "LITTLE_STRAIGHT" BIG_STRAIGHT = "BIG_STRAIGHT" CHOICE = "CHOICE" YACHT = ...
11583451
from gen import * from pdataset import * import numpy as np import argparse from tempfile import TemporaryFile from fg import Foreground, FGTextureType import time def save_to_file(npy_file_name, n_examples, dataset, use_patch_centers=False, e=16): #The pentomino images np_data = np.array(np.zeros(e**2)) ...
11583452
import random def roll_dice(): dice_number = random.randint(1, 6) return dice_number print("===== Welcome to Dice Rolling Simulator =====") while 1: choice = input("Do you wanna roll a dice (y/n)") if 'y' in choice.lower(): print("Rolling dice...") number = roll_dice() ...
11583483
from django.conf.urls import url from django_prometheus_metrics.views import MetricsView urlpatterns = [ url(r'^metrics$', MetricsView.as_view(), name='prometheus-django-metrics') ]
11583507
import numpy as np import pytest import sklearn import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.utils.validation import check_is_fitted from sklearn.exceptions import NotFittedError from distutils.version import LooseVersion from dirty_cat import SuperVectorizer from dirty_cat impor...
11583576
from abc import ABCMeta, abstractmethod class IperfPort: pass class TrafficStream: def __init__(self, source, destination): self.rate = None self.frame_size = 1518 self.vlan = 0 self.l4stack = None self.source = source self.destination = destination class L3D...
11583607
import torch import torch.nn as nn from torch.autograd import Variable import time import numpy as np import sys sys.path.append('../') sys.path.append('../../') sys.path.append('../../../') from table import get_occupancy_table from functions.occupancy_to_topology import OccupancyToTopology from parse_args import par...
11583612
import os import ray import sys RAY_VERSION = "RAY_VERSION" RAY_COMMIT = "RAY_HASH" ray_version = os.getenv(RAY_VERSION) ray_commit = os.getenv(RAY_COMMIT) if __name__ == "__main__": print("Sanity check python version: {}".format(sys.version)) assert ( ray_version == ray.__version__ ), "Given Ray...
11583631
from pyradioconfig.parts.ocelot.profiles.Profile_Base import Profile_Base_Ocelot from pyradioconfig.calculator_model_framework.interfaces.iprofile import IProfile from pyradioconfig.parts.ocelot.profiles.frame_profile_inputs_common import frame_profile_inputs_common_ocelot from pyradioconfig.parts.ocelot.profiles.sw_pr...