id
stringlengths
3
8
content
stringlengths
100
981k
11583646
import subprocess import numpy as np import argparse import torch from torch import optim, nn from two_FC_layer_model_Audio import Two_FC_layer import os import time import gc from collections import Mapping, Container from sys import getsizeof import h5py from torch.utils.data import DataLoader, Dataset from pytorchto...
11583649
import sys import json import os import logging from logging.config import dictConfig from flask import Flask from flask_cors import CORS from flask_restful import reqparse, abort, Api, Resource from flask import request, jsonify import base64 import yaml import argparse import textwrap sys.path.append...
11583683
from typing import Dict import torch import pickle MAX_SIZE_LIMIT = 65533 def update_d1_with_d2(d1: Dict, d2: Dict): # update d1 with d2 if d2 is None: return for k, v in d2.items(): d1[k] = d1.get(k, v) def object_to_byte_tensor(obj, max_size=4094): """Encode Python objects to PyTorc...
11583711
import pandas as pd import torch from PIL import Image, ImageFile from torch.utils.data import Dataset import os device = torch.device("cuda:0") ImageFile.LOAD_TRUNCATED_IMAGES = True class CollectionsDataset(Dataset): def __init__(self, csv_file, root_dir, num_classes, image_size, folds=None, transform=None): ...
11583791
class Solution: def generate(self, numRows: int) -> List[List[int]]: pascal = [] for i in range(numRows): if i == 0: array = [i + 1] #start the array by inserting the first array pascal.append(array) #append array to result list else: ...
11583819
import domoticz from devices.light.on_off import OnOffLight class DimmerLight(OnOffLight): MAX_BRIGHTNESS = 100 def create_device(self, unit, device_id, device_name): return domoticz.create_device(Unit=unit, DeviceID=device_id, Name=device_name, Type=244, Subtype=73, Switchtype=7) def set_bright...
11583824
from pinyin import get_pinyin def dummy_test(): assert get_pinyin('你好', 'ni3 hao3') if __name__ == "__main__": print(get_pinyin("你好?中文!中文的,符号"))
11583870
from pybrain.rl.agents.linearfa import LinearFA_Agent from pybrain.rl.experiments import EpisodicExperiment from environment import Environment from tasks import LinearFATileCoding3456BalanceTask from training import LinearFATraining from learners import SARSALambda_LinFA_ReplacingTraces task = LinearFATileCoding3456...
11583903
import os import torch import datasets import translation_models.model as tmm import translation_models.help_fun as transl_hf import onmt import model_manager import quantization import copy import functools import quantization.help_functions as qhf import helpers.functions as mhf cuda_devices = os.environ['CUDA_VISIB...
11583927
from django.http import HttpResponse from django.core.exceptions import ValidationError from django.db import transaction from systems.models import System from core.range.utils import range_usage from core.search.compiler.django_compile import compile_to_q from core.range.ip_choosing_utils import ( integrate_rea...
11583931
from __future__ import absolute_import, print_function, unicode_literals import datetime import os import pickle import sys import traceback from io import open from fabric.api import env, execute from fabric.operations import sudo from github import UnknownObjectException from memoized import memoized_property from...
11583935
from trading_ig.config import config import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # if you need to cache to DB your requests from datetime import timedelta import requests_cache from getting_realtime_data.data_retrieval import Data_Retrieval from sending_orders.order_management i...
11583938
import contextlib import itertools import numpy as np import os import sys try: import pycocotools.coco import pycocotools.cocoeval import pycocotools.mask as mask_tools _available = True except ImportError: _available = False import fcis def eval_instance_segmentation_coco(generator): """Ev...
11583971
from .expr import Expr class LeafExpr(Expr): """Leaf expression base class.""" def has_return(self): return False LeafExpr.__module__ = "pyteal"
11584012
class AddAuthTokenMiddleware(object): """ Adds auth_token cookie to response """ def process_response(self, request, response): if hasattr(request, 'user') and request.user and request.user.is_authenticated(): auth_token = request.user.auth_token if auth_token: ...
11584013
import msvcrt #检测键盘输入 def kb_hitchk(): Kb_hit =msvcrt.kbhit() if Kb_hit : Kb_return = ord(msvcrt.getch()) else : Kb_return = 0 return Kb_return #前端显示名称 config_webtitle = '' #前端底部页面信息 config_webinfo = '' #需监控前端设备地址列表文件,csv后缀,格式 "设备名称,设备地址,设备端口" config_ipfile = './static/ip.csv' #超时时间,建议默...
11584018
import argparse import torch import torch.nn.functional as F from torch.nn import Linear as Lin from torch_geometric.nn import SplineConv, radius_graph, fps, global_mean_pool from points.datasets import get_dataset from points.train_eval import run parser = argparse.ArgumentParser() parser.add_argument('--epochs', ty...
11584025
import cv2 import matplotlib import numpy as np from matplotlib import pyplot as plt # * syn where to set this # must use 'Agg' to plot out onto image matplotlib.use("Agg") #### def fig2data(fig, dpi=180): """Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it. Args: ...
11584040
from typing import Optional, Tuple import aiohttp.web from kopf._cogs.clients.auth import APIContext, authenticated from kopf._cogs.structs.credentials import ConnectionInfo @authenticated async def fn( x: int, *, context: Optional[APIContext], ) -> Tuple[APIContext, int]: return context...
11584063
import pulsar client = pulsar.Client('pulsar://localhost:6650') msg_id = pulsar.MessageId.earliest reader = client.create_reader('test', msg_id) while True: msg = reader.read_next() print("Received message '{}' id='{}'".format(msg.data(), msg.message_id())) client.close()
11584076
from securityheaders.checkers import Finding, FindingType, FindingSeverity from securityheaders.models import ReferrerPolicy from securityheaders.checkers.referrerpolicy import ReferrerPolicyChecker class ReferrerPolicyInsecureChecker(ReferrerPolicyChecker): def check(self, headers, opt_options=dict()): f...
11584094
import numpy as np import pandas as pd from DeepTCR.DeepTCR import DeepTCR_SS import seaborn as sns import matplotlib.pyplot as plt import matplotlib matplotlib.rc('font', family='Arial') DTCRS = DeepTCR_SS('reg_mart1',device=2) alpha = 'CAVNFGGGKLIF' beta = 'CASSWSFGTEAFF' input_alpha = np.array([alpha,alpha]) input...
11584188
import logging import coloredlogs import argparse import functools log = logging.getLogger("main") exception = log.exception info = log.info debug = log.debug error = log.error warn = log.warning def get_arg(arg): try: parser = argparse.ArgumentParser() parser.add_argument("--log", help="log hel...
11584247
import tensorflow as tf from tensorflow.contrib.framework.python.ops import arg_scope from tensorflow.contrib.framework.python.ops import add_arg_scope import numpy as np from functools import partial from net.ops import random_sqaure, Margin, fixed_bbox_withMargin, bbox2mask from net.ops import confidence_driven_mask...
11584320
from __future__ import print_function import os import subprocess import glob import time import py_compile import sys from unittest import TestCase class TestExamples(TestCase): def setUp(self): os.chdir("examples") def tearDown(self): if os.path.basename(os.getcwd()) == "examples": ...
11584323
import re __product__ = "HTML5" __description__ = ( "HTML5 is a markup language used for structuring and presenting " "content on the World Wide Web. It is the fifth and current major " "version of the HTML standard." ) def search(html, **kwargs): html = str(html) plugin_detection_schema = ( ...
11584332
from copy import deepcopy from typing import Dict, List, Any, Union from ..config import fill_default, is_algorithm_distributed from ..pl_logger import LocalMediaLogger from ..dataset import DatasetResult, RLDataset, log_video, determine_precision from ..launcher import Launcher, DistributedLauncher from machin.frame.a...
11584349
import torch from torch import nn class BitShift(nn.Module): def __init__(self, direction): if direction not in ("LEFT", "RIGHT"): raise ValueError("invalid BitShift direction {}".format(direction)) self.direction = direction super().__init__() def forward(self, X, Y): ...
11584350
import numpy import util from chainer import cuda from chainer import function from chainer.utils import type_check def _as_mat(x): if x.ndim == 2: return x return x.reshape(len(x), -1) class QuantizedLinearFunction(function.Function): def check_type_forward(self, in_types): ...
11584359
from django.test import TestCase from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Group, AnonymousUser from django.db import models from guardian.testapp.tests.conf import skipUnlessTestApp from guardian.testapp.tests.test_...
11584382
def get_valid_actions(env, roll): a = env.game.get_valid_plays(env.colors[env.agent_selection], roll) return a def to_bar(action, roll): if action == 25: # bar if roll < 0: # white return ('bar', 24 - abs(roll)) else: # black return ('bar', abs(roll) - 1) els...
11584438
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name='mkdocs-add-number-plugin', version='1.2.1', description='MkDocs Plugin to automatically number the headings (h1-h6) ' 'in each markdown page and number the nav.', ...
11584453
import tensorflow as tf from tf_rbdl.liegroup import * from tf_rbdl.kinematics import * @tf.function def id(theta,dtheta,ddtheta,g,pidlist,Mlist,Glist,Slist): """ Inverse dynamics. Note that nbody == nq, since body only contains movable link. Parameters ---------- theta (tf.Tensor): J...
11584484
try: from logging import NullHandler except ImportError: # Python 2.6 from logging import Handler class NullHandler(Handler): def emit(self, record): pass from six import indexbytes try: from ssl import SSLError except ImportError: class SSLError(Exception): pass ...
11584493
import os from onsset import SettlementProcessor from pandas import DataFrame,Series,cut from pandas.testing import assert_frame_equal, assert_series_equal from pytest import fixture class TestSettlementProcessor: @fixture def setup_settlementprocessor(self) -> SettlementProcessor: csv_path = os.p...
11584541
import faceutils as futils from smart_path import smart_path from pathlib import Path from PIL import Image import fire import numpy as np import tqdm from collections import defaultdict import pickle from config import config import dlib from multiprocessing import Pool from functools import partial import os.path ...
11584552
import torch from torch import nn import torch.nn.functional as F from torch.nn.parameter import Parameter import math from torch.autograd import Variable from torchvision.ops import box_iou class GraphConvolution(nn.Module): """ Simple GCN layer, similar to https://arxiv.org/abs/1609.02907 """ def _...
11584584
import os def find_egg_info_dir(dir): while 1: try: filenames = os.listdir(dir) except OSError: # Probably permission denied or something return None for fn in filenames: if (fn.endswith('.egg-info') and os.path.isdir(os.path.j...
11584588
import os import sys from setuptools import setup if sys.version_info[0] != 3: raise RuntimeError('Unsupported python version "{0}"'.format( sys.version_info[0])) def _get_file_content(file_name): with open(file_name, 'r') as file_handler: return str(file_handler.read()) def get_long_descripti...
11584693
from fractal import IFS code = [ [0.195, -0.488, 0.344, 0.443, 0.4431, 0.2452, 0.2], [0.462, 0.414, -0.252, 0.361, 0.2511, 0.5692, 0.2], [-0.637, 0, 0, 0.501, 0.8562, 0.2512, 0.2], [-0.035, 0.07, -0.469, 0.022, 0.4884, 0.5069, 0.2], [-0.058, -0.07, -0.453, -0.111, 0.5976, 0.0969, 0.2] ] ifs = IFS(...
11584738
import numpy as np import argparse from tqdm import tqdm import yaml from attrdict import AttrMap import torch from torch.autograd import Variable from torch.utils.data import DataLoader from data import TestDataset from utils import gpu_manage, save_image from models.gen.unet import UNet def predict(config, args):...
11584803
import os import unittest from unittest.mock import patch from configue.yaml_loader import YamlLoader class TestYamlLoader(unittest.TestCase): def setUp(self): os.environ["my_var"] = "my_value" os.environ["my_int_var"] = "10" os.environ["my_bool_var"] = "false" os.environ["my_list...
11584805
import os import random import time import warnings import json import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.multiprocessing as mp import torch.utils.data import torch.utils.data.distributed import torc...
11584806
import os import numpy as np import cv2 import torch.nn as nn import torch.nn.functional as F import torch import math import time from typing import List from visualDet3D.networks.utils import DETECTOR_DICT from visualDet3D.networks.backbones import resnet from visualDet3D.networks.lib.coordconv import CoordinateConv ...
11584821
from lxml import html from pprint import pprint # noqa API_URL = "https://www.eccourts.org/api/get_posts/" def clean_text(text): try: return html.fromstring(text).text except Exception: return text def emit_attachment(context, post, attachment): meta = { "title": clean_text(att...
11584841
import fnmatch import os def is_dir(path: str) -> bool: return isinstance(path, str) and os.path.exists(path) and os.path.isdir(path) def is_file(path: str) -> bool: return isinstance(path, str) and os.path.exists(path) and os.path.isfile(path) def get_file_extension(path: str) -> str: return os.path.splitext(...
11584896
import pytest from django_performance_testing.queries import classify_query @pytest.mark.parametrize('sql', [ 'QUERY = u\'SELECT "auth_group"."id", "auth_group"."name" FROM "auth_group"\' - PARAMS = ()', # noqa 'QUERY = \'SELECT "auth_group"."id", "auth_group"."name" FROM "auth_group"\' - PARAMS = ()', # no...
11584898
from airdraw.config import BaseConfig class AppConfig(BaseConfig): NAME = 'airdraw' VERSION = (0, 1, 0) WINDOW_WIDTH = 1024 WINDOW_HEIGHT = 768 CANVAS_BACKGROUND_COLOR = '#000000'
11584899
import bottle class Plugin(object): '''Bottle plugin to handle SSL client certificates.''' name = 'one.infinit.ssl-client-certificate' api = 2 key_dn = 'SSL_CLIENT_DN' key_ok = 'SSL_CLIENT_VERIFIED' def __init__(self): pass def apply(self, callback, route): def wrapper(*args, **kwargs): ...
11584919
import argparse import os import sys from .mapping import AttackMapping def parse_args(): args = argparse.ArgumentParser(prog="attack-lookup", description="MITRE ATT&CK Lookup Tool", formatter_class=argparse.ArgumentDefaultsHelpFormatter) args.add_argument("-v", "--version", default="v10.1", help="ATT...
11584975
import torch import torch.nn as nn import rdkit.Chem as Chem import torch.nn.functional as F from fuseprop.nnutils import * from fuseprop.mol_graph import MolGraph from fuseprop.rnn import GRU, LSTM class MPNEncoder(nn.Module): def __init__(self, rnn_type, input_size, node_fdim, hidden_size, depth): super...
11585008
import contextlib import shutil import tempfile @contextlib.contextmanager def tempdir(): temp = tempfile.mkdtemp() yield temp shutil.rmtree(temp)
11585033
import numpy as np import codecs import cv2 import matplotlib.pylab as plt import read_data import config train_images_dir = config.train_images_dir train_labels_dir = config.train_labels_dir save_images_dir = "train_images/resize_images/" save_labels_dir = "train_images/resize_ground_truth/" def test_main(): ima...
11585051
import os import time def map_maybe(f, lst): return [f(x) if x is not None else None for x in lst] def measure(f): t0 = time.time() result = f() duration = time.time() - t0 return duration, result def one_based_range(n): return range(1, 1 + n) def show_duration(duration): if duration...
11585100
from pathlib import Path import torch import numpy as np from torchvision import transforms as trans import json class Config(object): data_path = Path('data') coco_path = data_path/'coco2014' anno_path = coco_path/'annotations' train_path = coco_path/'train2017' val_path = coco_path/'val2017' ...
11585112
from lightbus import Api, Event, Parameter from lightbus.creation import create bus = create() class AuthApi(Api): user_registered = Event(parameters=[Parameter("username", str)]) class Meta: name = "auth" def check_password(self, username: str, password: str): return username == "admin...
11585135
from mkreports import md def test_list(): basic_text = ( md.H1("First header") + md.H2("Second header") + md.P("This is a paragraph") ) assert basic_text.body.format_text(" ", "a") == ( "\n\n# First header\n\n## Second header\n\nThis is a paragraph\n\n" )
11585143
from credmark.cmf.engine.model_unittest import ModelTestCase, model_context class ExampleEchoTest(ModelTestCase): @model_context(chain_id=1, block_number=12345) def test_echo(self): # sanity check that the context is as expected self.assertEqual(self.context.block_number, 12345) # r...
11585186
import datetime import binsync.data from . import ui_version if ui_version == "PySide2": from PySide2.QtWidgets import QVBoxLayout, QGroupBox, QWidget, QLabel, QTabWidget, QTableWidget, QStatusBar from PySide2.QtCore import Signal elif ui_version == "PySide6": from PySide6.QtWidgets import QVBoxLayout, QG...
11585198
import greenlet from .hubs.hub import get_hub __all__ = ['Timeout', 'with_timeout'] _NONE = object() # deriving from BaseException so that "except Exception as e" doesn't catch # Timeout exceptions. class Timeout(BaseException): """Raise `exception` in the current greenthread after `timeout` seconds. Whe...
11585222
import pytest from ....order.tests.benchmark.test_order import FRAGMENT_AVAILABLE_SHIPPING_METHODS from ....tests.utils import get_graphql_content @pytest.mark.django_db @pytest.mark.count_queries(autouse=False) def test_retrieve_shop(api_client, channel_USD, count_queries): query = ( FRAGMENT_AVAILABLE_...
11585236
import numpy as np import pandas as pd from contextlib import contextmanager import time import logging @contextmanager def timing(name): t0 = time.time() yield log_out = 'Fragment [{}] done in {:.2f} s\n'.format(name, time.time() - t0) print(log_out) logging.info(log_out) def get_indiv_imp...
11585241
from typing import Iterable from testplan.report import TestReport class ParseSingleAction: def __call__(self) -> TestReport: pass class ParseMultipleAction: def __call__(self) -> Iterable[TestReport]: pass class ProcessResultAction: def __call__(self, result: TestReport) -> TestRepor...
11585249
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer from hazelcast.protocol.builtin import StringCodec from hazelcast.protocol.builtin import EntryListCodec from hazelcast.protocol.builtin import DataCodec # hex: 0x0D1100 _REQUEST_MESSAGE_TYPE = 856320 # hex: 0x0D1...
11585252
from django.urls import re_path from rest_framework.routers import DefaultRouter from apps.vadmin.system.views import DictDataModelViewSet, DictDetailsModelViewSet, \ ConfigSettingsModelViewSet, SaveFileModelViewSet, MessagePushModelViewSet, LoginInforModelViewSet, \ OperationLogModelViewSet, CeleryLogModelVie...
11585258
class Doc2Tester: def __init__(self, mod, doc, node): self.mod = mod self.doc = doc self.node = node self.exdefs = [] self.set_out([]) self.test_names = {} self.condition_exprs = {} self.condition_methods = {} self.document_metas = [] s...
11585262
from logtacts.settings import * import fakeredis CACHES['default']['OPTIONS']['REDIS_CLIENT_CLASS'] = "fakeredis.FakeStrictRedis"
11585288
import os.path as osp import torch.distributed as dist from mmcv.runner import DistEvalHook as BaseDistEvalHook from mmcv.runner import EvalHook as BaseEvalHook from torch.nn.modules.batchnorm import _BatchNorm class EvalHook(BaseEvalHook): """Please refer to `mmcv.runner.hooks.evaluation.py:EvalHook` for detail...
11585308
import logging import os import sys import splunk.admin as admin import cloudformation_templates_schema import urllib import base_eai_handler import log_helper if sys.platform == 'win32': import msvcrt # Binary mode is required for persistent mode on Windows. msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY...
11585333
if "bpy" in locals(): import importlib importlib.reload(ycd) else: from . import ycd import bpy
11585351
from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation a = np.load('../datasets/toyData/valData.npy') a = np.random.randn(10,3,25) * 50 # index = 50 """ numframes = 100 numpoints = 25 fig = plt.figure() scat = plt.scatter() ani = anima...
11585357
from .config import sample_data from .context import pandas_ta from unittest import skip, TestCase from pandas import DataFrame class TestOverlapExtension(TestCase): @classmethod def setUpClass(cls): cls.data = sample_data @classmethod def tearDownClass(cls): del cls.data def se...
11585377
import torch from SpatialExtractor.BaseCNN_4FeatureGetting import BaseCNN from SpatialExtractor.Main_4FeatureGetting import parse_config def make_spatial_model(): config = parse_config() model = BaseCNN(config) model = torch.nn.DataParallel(model).cuda() ckpt = './SpatialExtractor/weights/DataParallel...
11585441
import json import ast from .ConnectionProperty import ConnectionProperty from .DeadlineUtility import ArrayToCommaSeparatedString class Jobs: """ Class used by DeadlineCon to send Job requests. Stores the address of the Web Service for use in sending requests. """ def __init__(self, conne...
11585476
import requests from requests.auth import HTTPBasicAuth, HTTPDigestAuth import xmltodict try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin import json def response_parser(response, present='dict'): """ Convert Hikvision results """ if isinstance(response, (lis...
11585477
import yt # target file file = 'Data_000000' # load data ds = yt.load( file ) ad = ds.all_data() # filter data if required # ref: https://yt-project.org/docs/dev/analyzing/filtering.html#cut-regions dense = ad.cut_region( ['obj["Dens"]>1.0e2'] ) # calculate center-of-mass cm = dense.quantities.weighted_average_quan...
11585478
import sys from xrspatial import __main__ as m from unittest.mock import patch import pytest # test_args include copy-examples, fetch-data, or examples (does both) @pytest.mark.skip(reason="meant only for internal use") def run_examples_cmds(*cli_cmds): """ Run conda package cli commands to download examples ...
11585494
from calendar import timegm from datetime import datetime from typing import Dict, List, Optional, TypeVar from uuid import uuid4 import pytest from _pytest.monkeypatch import MonkeyPatch from fastapi import FastAPI, HTTPException from fastapi.encoders import jsonable_encoder from starlette.status import ( HTTP_20...
11585514
import random import numpy as np # tabular Q-learning where states and actions # are discrete and stored in a table class QLearner(object): def __init__(self, state_dim, num_actions, init_exp=0.5, # initial exploration prob final_exp=0.0, # final...
11585580
from __future__ import print_function import sys import random import os from builtins import range import time sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.kmeans import H2OKMeansEstimator from h2o.grid.grid_search import H2OGridSearch class Test_PUBDEV_2980_kmeans:...
11585582
import os, copy, torch from torch.utils.data import Dataset, DataLoader import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torch.nn.functional as F from torch.autograd import Variable from collections import OrderedDict import torchvision from torchvision import datasets, mo...
11585612
from maneuvers.strikes.double_touch import DoubleTouch from maneuvers.dribbling.carry_and_flick import CarryAndFlick from maneuvers.maneuver import Maneuver from maneuvers.strikes.aerial_strike import AerialStrike, FastAerialStrike from maneuvers.strikes.close_shot import CloseShot from maneuvers.strikes.dodge_str...
11585622
from datetime import datetime from django.test import TestCase from simple_history.signals import ( post_create_historical_record, pre_create_historical_record, ) from ..models import Poll today = datetime(2021, 1, 1, 10, 0) class PrePostCreateHistoricalRecordSignalTest(TestCase): def setUp(self): ...
11585638
class BinTree: ''' Root: integer value Left: BinTree Right: BinTree if left and right are both None, the tree is a leaf (an ending node) ''' def __init__(self, root, left, right): self.root = root self.left = left self.right = right ''' Converts the Binary Tr...
11585666
from torch.utils.data import DataLoader from ..util import barit, DirectoryDataset, LoadedDataset from ..hdr.io import imread from .opts import fetch_opts def _custom_get_item(self, index): if self.train: img, target = self.train_data[index], self.train_labels[index] else: img, target = self.te...
11585667
class AlternationConverter(object,IValueConverter): """ Converts an integer to and from an object by applying the integer as an index to a list of objects. AlternationConverter() """ def Convert(self,o,targetType,parameter,culture): """ Convert(self: AlternationConverter,o: object,targetType: Typ...
11585718
import tensorflow as tf from games.connect_4 import Connect4GameSpec connect_4_game_spec = Connect4GameSpec() def create_convolutional_network(): input_layer = tf.input_layer = tf.placeholder("float", (None,) + connect_4_game_spec.board_dimensions() + (1,)) ...
11585720
import cv2 import threading from copy import deepcopy from screen import convert_screen_to_monitor, grab from typing import Union from dataclasses import dataclass import numpy as np from logger import Logger import time import os from config import Config from utils.misc import cut_roi, load_template, list_files_in_fo...
11585732
import uclasm nodelist, channels, adjs = \ uclasm.load_edgelist( "example_data_files/example_edgelist.csv", src_col=0, dst_col=1, channel_col=2, header=0) nodes = nodelist.node labels = nodelist.label # Use the same graph data for both template and world graphs tmplt = ucl...
11585754
from unittest import TestCase import os from vcr import VCR import pytest from click.testing import CliRunner import pyicloud_ipd from icloudpd.base import main from icloudpd.authentication import authenticate, TwoStepAuthRequiredError import inspect vcr = VCR(decode_compressed_response=True) class AuthenticationTes...
11585776
import numpy as np # arr_outcomes = np.load('../processed_data/arr_outcomes.npy', allow_pickle=True) """Use 8:1:1 split""" p_train = 0.80 p_val = 0.10 p_test = 0.10 n = 11988 # original 12000 patients, remove 12 outliers n_train = round(n*p_train) n_val = round(n*p_val) n_test = n - (n_train+n_val) Nsplits = 5 for ...
11585791
import time from metadrive import TopDownMetaDriveEnvV2 if __name__ == '__main__': env = TopDownMetaDriveEnvV2(dict(environment_num=10, frame_stack=10, frame_skip=3)) o = env.reset() start = time.time() action = [0.0, 0.1] print(o.shape) for s in range(10000): o, r, d, i = env.step(act...
11585794
import io import os import re import sys from jinja2 import Environment, PackageLoader, select_autoescape from primehub import PrimeHub from primehub.cli import create_sdk, main as cli_main from primehub.utils.decorators import find_actions, find_action_method env = Environment( loader=PackageLoader("primehub.ex...
11585797
from __future__ import absolute_import from itertools import chain from six.moves import range, reduce import os import re import numpy as np import tensorflow as tf import codecs import sys from tqdm import tqdm import pickle import logging class Dataset(): def __init__(self, data='data/tasks_1-20_v1-2/en/',ts_num...
11585802
import numpy as np import scipy import scipy.sparse as sp from igraph import Graph, VertexCover def __reset_diagonal(A, sparse): ''' input: matrix ouput: matrix object with diagonals set to 0 ''' if sparse: A = A - sp.dia_matrix((A.diagonal()[scipy.newaxis, :], [0]), shape=A.shape) el...
11585823
import json import unittest from subprocess import check_output import tempfile import fixtures class SkinferScriptTest(unittest.TestCase): script = 'skinfer' def test_end_to_end_simple_run(self): # given: _, filename = tempfile.mkstemp() with open(filename, 'w') as f: f.wr...
11585830
import datetime import uuid from typing import Optional, Union from unittest import TestCase import jsons from jsons import ( SerializationError, DeserializationError, UnfulfilledArgumentError, ) class TestUnion(TestCase): def test_dump_optional_primitive(self): class C: def __ini...
11585843
import io import sys from setuptools import setup, find_packages from shutil import rmtree if sys.argv[:2] == ["setup.py", "bdist_wheel"]: # Remove previous build dir when creating a wheel build, # since if files have been removed from the project, # they'll still be cached in the build dir and end up ...
11585849
import pybithumb con_key = "81dd5f25e5daa70b2fff603901d2c09c" sec_key = "82333efegeg9eg3e77c573weg34af17a" bithumb = pybithumb.Bithumb(con_key, sec_key) krw = bithumb.get_balance("BTC")[2] orderbook = pybithumb.get_orderbook("BTC") asks = orderbook['asks'] sell_price = asks[0]['price'] unit = krw/float(sell_price) ...
11585856
import rospy import rospkg import argparse import bisect import numpy as np import pylab as pl import time import logging import pickle import os import progressbar from planner_comparison.plan_scoring import * from planner_comparison.RosbagInterface import * # Deep motion planner from deep_motion_planner.tensorflow...