text
stringlengths
3.07k
12.6k
import os from collections import defaultdict from copy import deepcopy from packaging.requirements import InvalidRequirement, Requirement from ..fs import stream_file_lines, write_file_lines from .constants import NOT_CHECKS, get_agent_requirements, get_root from .utils import ( get_normalized_dependency, ge...
#!/usr/bin/env python # coding: utf-8 import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils, models from torch.autograd import Variable import os import sys sys.path.append(os.path.joi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import widgets, ModelChoiceField from django.forms.models import ModelForm from django.db.models.fields.related import ManyToOneRel from django.contrib.admin.sites import site from django.utils.html import format_html from django.utils.e...
import paraview import paraview.simple import paraview.servermanager as sm import PVBase import core.modules import core.modules.module_registry from pvconfig import QPVConfigWindow from core.modules.vistrails_module import new_module, Module, ModuleError from core.modules.module_registry import (registry, add_module, ...
"""Monte Carlo value estimation and control An interesting observation - due to the winner's curse, if our rewards are noisy we'll frequently overestimate state values. """ from typing import Dict, List, Tuple, TypeVar import numpy as np from rl_examples.discrete import DiscreteEnvironment, State from rl_examples.t...
from ...errors import TarskiError from ...fstrips import FunctionalEffect from ...fstrips.action import AdditiveActionCost, generate_zero_action_cost from ...fstrips.representation import is_typed_problem from ...syntax import Interval, CompoundTerm, Tautology, BuiltinFunctionSymbol from ... import theories from ...syn...
# coding: utf8 # intente algo como @auth.requires_login() @auth.requires_membership('Teacher') def index(): return dict() @auth.requires_login() @auth.requires_membership('Teacher') def final_practice(): assignation = request.vars['assignation'] if not assignation: redirect(URL('courses')) final_practi...
"""Utility to convert .ipynb files and their widgets to publicly viewable, interactive HTML pages. This file defines the Exporter for the NbInteract conversion utility. After installing this package, the user can run nbinteract some_notebook.ipynb To export their notebook. The above command is an alias for: ...
import sys import pytest from pytest import raises from typedpy import Structure, AllOf, AnyOf, OneOf, Integer, String, Positive, Number, NotField, Field, Array class Foo(Structure): s = String class Example(Structure): _additionalProperties = True _required = [] a = AllOf([Number(multiplesOf=5, m...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Wraps the splicer executable from https://github.com/kurtsiefer/qcrypto/tree/master/remotecrypto. Copyright (c) 2020 <NAME>, S-Fifteen Instruments Pte. Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated ...
from __future__ import print_function import re import os import errno shortcuts = {} # regex matching on key, replacement of groups on value # implement any other shortcuts that you want to use #sources shortcuts["mp([0-9]*)"] = "sqlite_file:/afs/cern.ch/cms/CAF/CMSALCA/ALCA_TRACKERALIGN/MP/MPproduction/mp{0}/jobData...
'''ResNet in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] <NAME>, <NAME>, <NAME>, <NAME> Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' import torch import torch.nn as nn import torch.nn.functional as F from lib.normalize import Normalize from torch.autograd impo...
import py from pypy.rpython.lltypesystem.llmemory import * from pypy.annotation.model import SomeAddress, SomeChar from pypy.translator.c.test.test_genc import compile from pypy.rlib.objectmodel import free_non_gc_object def test_null(): def f(): return NULL - NULL fc = compile(f, []) def test_convert...
# coding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import itertools import os import shlex import sys from pip._internal.commands import create_command from pip._internal.utils.misc import get_installed_distributions from .. import click, sync from .._compat import par...
import json import requests import typing import errors class Route(object): """ Model object representing a route in the MBTA API. """ # Attributes to request from the API. We want this to be the minimum set of fields that we'll need to reduce # network cost fields = ['color', 'text_color', ...
import copy import numpy as np from ...utils import common_utils def random_flip_along_x(gt_boxes, points): """ 沿着x轴随机翻转 Args: gt_boxes: (N, 7 + C), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C) Returns: """ # 随机选择是否翻转 enable = np.random.choice([False, True...
import get_file as f import morpher as m import tester as t import detector import get_file import time import os d=detector.detector() p=10 q1=20 q2=q1/20 def EvadeHC(): C=[] bytes=get_file.get_bytes_batch() print(len(bytes)) for bytez in bytes: ti=time.time() f = open('temp/' + str(ti)...
from Bio import SeqIO from src.inputValueException import InputValueException import os import pandas as pd import re # calculates kmer frequencies # k: kmer-length # peak: peak-position, where sequences should be aligned # selected: input files # no_sec_peak: status (-1= no structural data available, 0= False, 1= Tr...
from dataclasses import dataclass, field from unidecode import unidecode class TabelaHadoopColunaException(ValueError): pass TIPOS_CONVERSAO = { 'C': 'VARCHAR', 'CHAR': 'VARCHAR', 'TEXTO': 'VARCHAR', 'Alfanumérico': 'VARCHAR', 'I': 'INTEGER', 'INTEIRO': 'INTEGER', 'N': 'NUMBER', ...
""" Input and output for geo-specific data formats. """ import numpy as np import pandas as pd import fiona import geoviews as gv import dask.dataframe as dd import xarray as xr import cartopy.crs as ccrs from osgeo import gdal, osr def get_sampling(bounds, shape): """ Generates x/y coordinates from bounds ...
import math import KratosMultiphysics import KratosMultiphysics.FluidDynamicsApplication as KratosFluid def Factory(settings, Model): if(type(settings) != KratosMultiphysics.Parameters): raise Exception("expected input shall be a Parameters object, encapsulating a json string") return ApplyOutletProces...
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
# This is where to save audit trail stuff import csv import datetime import os import sqlite3 MESSAGE_ARCHIVE = 'archive/messages/' BLOCKS_ARCHIVE = 'archive/blocks/' JOURNAL_ARCHIVE = 'archive/journals.csv' DATABASE_ARCHIVE = 'archive/farmxero.db' def nanoFilToFil(nanoFil): return nanoFil*(10**-18) #Returns tot...
""" Pull method tools. """ from __future__ import absolute_import, division import numpy as np from pisa.utils.log import logging, set_verbosity __all__ = [] __author__ = '<NAME>' __license__ = '''Copyright (c) 2014-2020, The IceCube Collaboration Licensed under the Apache License, Version 2.0 (the "License");...
### Import Libraries ### import os import pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.layers import Dense, Input from tensorflow.keras.optimizers import Adam from tensorflow.keras.models import Model import tensorflow_addons as tfa import...
"""This module defines helpers for various endpoints.""" from decimal import Decimal from typing import Callable import codecs import time import uuid from polaris import settings import jwt from jwt.exceptions import InvalidTokenError from rest_framework import status from rest_framework.response import Response from...
# this program trains, and then outputs the CNN used in the javascript script. from tensorflow.examples.tutorials.mnist import input_data from math import floor mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import numpy as np import struct import math import tensorflow as tf sess = tf.InteractiveSessi...
from . import base class LogSection(base.SectionBase): @base.returns_single_item(base.ResponseBase) def level(self, subsystem: str, level: str, **kwargs: base.CommonArgs): r"""Changes the logging output level for a given subsystem **This API is subject to future change or removal!** .. code-block:: pyth...
# Copyright (c) 2021 <NAME> # Copyright (c) 2018 <NAME>, <NAME>, <NAME> # # Licensed under the MIT license: https://opensource.org/licenses/MIT # Permission is granted to use, copy, modify, and redistribute the work. # Full license information available in the project LICENSE file. import sys from multiprocessing impo...
#!/usr/bin/python3 # Demonstration of Simple Python Fixed-Point Module # (C)Copyright 2006-2018, <NAME> from __future__ import print_function import argparse, time from collections import OrderedDict try: import matplotlib, numpy import matplotlib.pyplot as plt HAVE_MATPLOTLIB = True except ImportError: ...
import random import urllib.request as urllib_request from django.conf import settings from django.core.exceptions import ValidationError from django.http import JsonResponse, HttpResponseRedirect from django.template.response import TemplateResponse from django.urls import reverse from django.views.decorators.cache i...
from typing import List import tensorflow as tf from tensorflow.contrib.layers import fully_connected from hotpot.model import Prediction from hotpot.nn.layers import SequencePredictionLayer, SequenceEncoder, FixedPredictionLayer, WeightedPredictionLayer, \ get_keras_initialization class BinaryPrediction(Predic...
from tkinter import * win = Tk() win.geometry("312x324") win.resizable(0, 0) win.title("Calculator") def btn_click(item): global expression expression = expression + str(item) input_text.set(expression) def bt_clear(): global expression expression = "" input_text.set("") def bt_equ...
import uuid from sqlalchemy.exc import IntegrityError from api.utils import get_next_answer_set_pk from .clr import configure_celery from celery.schedules import crontab from celery.task import periodic_task from app.extensions import db from pandas_datareader import data as pdr import pandas as pd from datetime imp...
import os.path import structures as st import numpy as np import itertools import csv def genFileName(fileName_base,catIndex): return fileName_base+'_'+str(catIndex)+'.nextflix' #write a category list into ncat files def dump(fileName_base,cats): #extracting some metadata nChannels = len(cats[0][0].channel) pLen...
"""Support Peewee ORM with asyncio.""" import typing as t from contextvars import ContextVar from collections import deque from inspect import isawaitable import peewee as pw from playhouse import db_url, pool, cockroachdb as crdb from playhouse.sqlite_ext import SqliteExtDatabase from ._compat import aio_wait, aio_s...
#!/usr/bin/env python ################################################################### # # fos_restapi.py is based on fgt_api.py by <NAME> # refactored and packaged with ftntlib by <NAME> # # A Python module to access the FortiOS REST API # ################################################################### import...
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Fields, parameters, and coercion ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Fields are typed slots which normalize and validate values passed to them, facilitating much more robust Operation usage. Parameters (aka params) are the values passed to a field. Ano...
""" Functional API endpoints separate from static views """ # stdlib import json import asyncio as aio from functools import wraps from pathlib import Path from typing import Optional # library from quart import Response, request from quart_openapi.cors import crossdomain from voluptuous import Invalid, MultipleInval...
from functools import lru_cache import numpy as np import torch as th @lru_cache(maxsize=None) def get_kernel_area(ker_loc=(0, 0), theta_c=np.pi / 12, theta=0): """ Helper function to identify kernel area after rotate on the sphere. Assume circle center: $\mathbf{c}=(x_c, y_c, z_c)$, radius degree: $\thet...
r""" test module for pair counts in s and mu bins """ from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np # load pair counters from ..npairs_s_mu import npairs_s_mu from ....mock_observables import npairs_3d # load comparison simple pair counters from ..pairs import s...
from celery.task import task from datetime import timedelta from corehq import toggles from corehq.apps.formplayer_api.smsforms.api import FormplayerInterface, TouchformsError from corehq.apps.sms.api import MessageMetadata, send_sms_to_verified_number, send_sms from corehq.apps.sms.models import PhoneNumber from core...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/4/17 13:48 # @Author : <NAME> # @File : db.py # @Role : ORM from sqlalchemy import Column, String, Integer, Text, DateTime, Boolean from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import class_mapper from datetime impor...
from sympy import Symbol, pi, symbols, Tuple, S, sqrt, asinh from sympy.geometry import Curve, Line, Point, Ellipse, Ray, Segment, Circle, Polygon, RegularPolygon from sympy.utilities.pytest import raises, slow def test_curve(): x = Symbol('x', real=True) s = Symbol('s') z = Symbol('z') # this curve ...
import cv2 import numpy as np import mxnet as mx # import datetime from skimage import transform as trans import insightface from . import img_helper arcface_src = np.array([ [38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041] ], dtype=np.float32 ) #...
import collections class BigInt: def __init__(self): self.number = [0] def skim(self): carrier = 0 for i in range(0, len(self.number)): self.number[i] += carrier head = self.number[i] % 10 carrier = (self.number[i] - head) / 10 self.number[i] = int(head) while carrier != 0: ...
import json import logging import os import requests import sys import uuid WIT_API_HOST = os.getenv('WIT_URL', 'https://api.wit.ai') WIT_API_VERSION = os.getenv('WIT_API_VERSION', '20160516') DEFAULT_MAX_STEPS = 5 INTERACTIVE_PROMPT = '> ' LEARN_MORE = 'Learn more at https://wit.ai/docs/quickstart' class WitError(Ex...
#from .input_parser import SimulationSetup import numpy as np import sys import argparse import mcdc_tnt import matplotlib.pyplot as plt def flatLinePlot(x, y, lab): for i in range(y.size): xx = x[i:i+2] yy = [y[i], y[i]] plt.plot(xx, yy, label=lab) def run(input_file, output_file=None, ha...
from __future__ import print_function import numpy as np def get_multi_metric(pred, gt, eval_label_list=None, rm_bg=False, verbose=True): """ implemented iou, dice, recall, precision metrics for each label of each instance in batch :param pred: predicted(warpped) label map Bx.... :param gt: ground ...
import multiprocessing try: from io import StringIO except ImportError: from io import StringIO from contextlib import closing import logging import connection from sink.backends.postgis import dump_schema, dump_indices, dump_statistics from sink.backends.postgis_copy import dump_data class CopyFromMessage(...
import requests import csv import json import time import datetime MAX_Page=500 cook='BIGipServerPool_app_chinabond_www=715265290.37151.0000; _pk_ses.1.0170=*; JSESSIONID=6DFA29606BC69B7DD491CA942FB2B940; _pk_id.1.0170=10c297c0f24dfa37.1546921738.4.1547037018.1547036258.' headers = { 'Cookie':cook, ...
import torch import config import torch.nn as nn ALEXNET = "ALEXNET" DENSENET121 = "DENSENET121" VGG13 = "VGG13" VGG13BN = "VGG13BN" VGG11BN = 'VGG11BN' RESNET50 = "RESNET50" RESNET101 = "RESNET101" INCEPTION_V3 = 'INVEPTION_V3' # MVCNN functions class conv_2d(nn.Module): def __init__(self, in_ch, out_ch, kern...
#!/usr/bin/env python3 import re import socket import ssl import sys import threading import time import config import debug import twitch import utility COMMANDS = [ # [r"!discord", "the official discord: ____"] ] TWITCH_MSG = re.compile(r"(:tmi\.twitch\.tv \w+ \w+ :|:\w+.tmi\.twitch\.tv \w+ \w+ |:\w+!\w+@\w+\...
import os from typing import Optional import numpy as np import tensorflow as tf from sklearn import preprocessing from fedot.core.data.data import InputData, OutputData from fedot.core.log import Log, default_log from fedot.core.operations.evaluation. \ operation_implementations.implementation_interfaces import ...
from manimlib.imports import * from math import * class fr(ThreeDScene): CONFIG = { "kone": None, "rate": None, "lines": [], "pointt": None, } def construct(self): axes = ThreeDAxes(z_min = 0, z_max = 8,) circle = Circle() sphere = ParametricSurface( ...
import dgl import math import torch as th import torch.nn as nn import torch.nn.functional as F from dgl.nn.pytorch import GraphConv, EdgeWeightNorm from ..utils import transform_relation_graph_list from . import BaseModel, register_model @register_model('GTN') class GTN(BaseModel): @classmethod def build_mod...
import tensorflow as tf import tensorflow.contrib.slim as slim import slim_model import data_loader import numpy as np import datetime import time import os FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('summary_dir', './summary', 'path to store summary') tf.app.flags.DEFINE_string( 'CKPT_RES50', './pretr...
import requests import pymongo import time from multiprocessing import Pool import requests from fake_useragent import UserAgent import time from random import randint API_KEY_TOKEN = 'TOKEN' BASE_URL = "https://api.telegram.org/bot{}/sendMessage".format(API_KEY_TOKEN) temp_user_agent = UserAgent(verify_ssl=Fal...
from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * """ qutip_conv ========== QuTiP / tncontract conversions. Functionality for converting between `qutip.Qobj` and `Tensor`. Requires `qutip`. """ import numpy as np import qutip as qt...
import numpy as np from collections import Counter import sys sys.path.append('../..') from LIB.EVAL.meteor import Meteor from LIB.EVAL.bleu import compute_bleu, diverse_bleu from LIB.EVAL.rouge import compute_rouge_L def convert_to_words(map_to_orig, question): """convert bert word pieces to normal tokens""" ...
import argparse import time import torch import torch.nn.functional as F import torch.optim as optim import numpy as np from models import GCN from sampler import Sampler_FastGCN, Sampler_ASGCN from utils import load_data, get_batches, accuracy from utils import sparse_mx_to_torch_sparse_tensor def get_args(): ...
from typing import List, Tuple import matplotlib.pyplot as plt import numpy as np import pandas as pd from IPython.display import display from scipy import stats def cat_data(df: pd.DataFrame, col_name: str) -> None: """Display some useful attributes of a categorical feature.""" print(f"Data type: {df[col_na...
# SPDX-FileCopyrightText: 2014-2020 <NAME> # # SPDX-License-Identifier: MIT # -*- coding: utf-8 -*- from __future__ import division, print_function import pytest import sys import numpy as np from symfit import ( Fit, Parameter, Variable, Model, GradientModel ) from symfit.core.minimizers import BFGS, Differenti...
"""Group of functions which produce heatmap of accumulated frequency counts. To run these functions the user will need a videofile (.tif format). WARNING: Extremely large video files (>1500 frames) or videos with high pixel resolution (512x512 array or greater) may take a couple of minutes to run depending on your com...
import utils class Prob(object): """Problem space with layer dimension, stride and dilation defined. Attributes: prob: A layer dimemsion dictionary. R, S represent the weight filter width and height. P, Q represent the output feature map width and height. C re...
""" Shogun demo <NAME> """ import numpy as np import matplotlib as mpl import pylab import util from scipy import linalg from modshogun import QDA from modshogun import RealFeatures, MulticlassLabels # colormap cmap = mpl.colors.LinearSegmentedColormap('color_classes', {'red': [(0, 1, 1), (1, .7, .7)], '...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-11-05 11:30:01 # @Author : <NAME> (<EMAIL>) # @Link : http://cs.ucsb.edu/~bolunwang import os import time import numpy as np import random import tensorflow from tensorflow import set_random_seed random.seed(123) np.random.seed(123) set_random_seed(1...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import json import os import yaml from redis import Redis """Load from files""" def load_cluster_details(cluster_name: str) -> dict: with open(os.path.expanduser(f"~/.maro/clusters/{cluster_name}/details.yml"), 'r') as fr: cluste...
""" .. module:: cosmo_hammer :synopsis: Invoke the Cosmo Hammer .. moduleauthor:: <NAME> <<EMAIL>> This module interface Monte Python with the CosmoHammer, available `publicly <http://www.astro.ethz.ch/refregier/research/Software/cosmohammer>`_ and developped by <NAME> and <NAME>, who helped me a lot creating this...
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. some functions are modified from HuggingFace (https://github.com/huggingface/transformers) copied/modified from HERO (https://github.com/linjieli222/HERO) """ import torch from torch import nn import logging logger = logging.getLogger(__name__) ...
import math from datetime import datetime try: from zoneinfo import ZoneInfo except ImportError: from backports.zoneinfo import ZoneInfo TIME_UNIT_MAP = { 'seconds': { 'label': 's', 'divisor': 1, 'threshold': 60, }, 'minutes': { 'label': 'm', 'divisor': 60, ...
# Copyright 2013, Couchbase, Inc. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
import transformers import tensorflow as tf import os import numpy as np import argparse from datetime import datetime def _int64_feature(value): """Wrapper for inserting int64 features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(int64_list=tf.tra...
from copy import deepcopy from sklearn.cross_validation import StratifiedKFold, StratifiedShuffleSplit from xgboost.sklearn import XGBClassifier import numpy as np N_FOLDS = 5 CV_NUM = 1 EVAL_METRIC = "error" EARLY_STOPPING_ROUNDS = 100 N_ESTIMATORS = 1000000 OBJECTIVE = "binary:logistic" GET_BEST_SCORE_INDEX = np.arg...
import numpy as np import math from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from src.coordinate_system_transformations import transform_2D_to_3D from src.calculate_optic_axis import calculate_optic_axis_unit_vector, calculate_r, calculate_p from src.calculate_visual_axis import calculate_vi...
import gc import syslog import logging import importlib.util import regex from Global import * import TaskScheduling def GetModule(PATH): _spec= importlib.util.spec_from_file_location("MOD", PATH) _result= importlib.util.module_from_spec(_spec) _spec.loader.exec_module(_result) return _result def...
""" examples/lego-3d.py Copyright (c) 2020, <NAME> - <EMAIL> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this lis...
from __future__ import print_function import json import kalman_filter import param_estimation import os.path import numpy import time def fit_and_filter_from_dir(dirname, trap, method='em', smooth_param=150.0): # data_filename = '../examples/data/2019_05_08_experiment/all_traps_final_analysis_output.json' #...
"""Flow instructions to be executed. The flow instructions associated with a flow table entry are executed when a flow matches the entry. """ # System imports from enum import IntEnum # Local source tree imports from pyof.foundation.base import GenericStruct from pyof.foundation.basic_types import ( FixedTypeList...
# Copyright 2014 Huawei Technologies Co. Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
import json import csv import re from utils import untokenize, convert_REC_ID_to_DD_ID from tqdm import tqdm # Load original DailyDialog data DD_data = json.load(open('TLiDB_DailyDialog/TLiDB_DailyDialog.json', 'r')) def get_DD_datum_from_RECCON_ID(REC_ID, original_DD_data): id = re.search(f"dailydialog_(.*?)_utt...
# Some useful packages from typing import Union, Tuple import time import numpy as np import pandas as pd import pprint # Tensorflow import tensorflow as tf import tensorflow_datasets as tfds # Importing the HPOptimizer and the RandomHpSearch from the AutoMLpy package. from AutoMLpy import HpOptimizer, RandomHpSearch...
# Copyright 2017 The Sonnet Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
import copy from argparse import Namespace from typing import List from ... import __default_host__ from ...enums import SchedulerType, SocketType, PeaRoleType from ...helper import random_port, get_random_identity, get_public_ip, get_internal_ip, is_valid_local_config_source def _set_peas_args(args: Namespace, head...
#!/bin/python3.8 """ DecisionTreeClassifier is a class capable of performing multi-class classification on a dataset. As with other classifiers, DecisionTreeClassifier takes as input two arrays: an array X, sparse or dense, of shape(n_samples, n_features) holding the training samples, and an array Y of int...
#!/usr/bin/python3 # Posix and Windows # Version 0.9, Python 3.6, 2018-07-03, <NAME> import sys import os import argparse from fnmatch import fnmatch FILE_CHUNK_SIZE = 512*1024 def file_content_diff(fno, fnb): with open(fno, 'rb') as f1: with open(fnb, 'rb') as f2: while True: b1 = f1....
import argparse import random from setup_dataset_utils import * def get_ecef_origin(): """Shift the origin to make the value of coordinates in ECEF smaller and increase training stability""" # Warning: this is dataset specific! ori_lon, ori_lat, ori_alt = 7.065, 46.3705, 1410 ori_x, ori_y, ori_z = pyp...
import os import re # Dictionary to get a config class based on key. This is automatically # populated on class creation by ConfigMeta. Keys are the name of the class # before Config suffix in uppercase CONFIGS = {} def first_key(d): """ Gets the first key of a dictionary :param d: Dictionary :return...
# # This file is part of pyasn1-modules software. # # Created by <NAME> # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # import sys from pyasn1.codec.der.decoder import decode as der_decode from pyasn1.codec.der.encoder import encode as der_encode from pyasn1_modules imp...
import torch import torch.nn as nn from math import log2 from utils import * class Generator(nn.Module): def __init__(self, opt): super(Generator, self).__init__() act_down = nn.LeakyReLU(0.2, inplace=True) act_up = nn.ReLU(inplace=True) image_height = opt.image_height inpu...
#!/usr/bin/python -OOOO # vim: set fileencoding=utf8 shiftwidth=4 tabstop=4 textwidth=80 foldmethod=marker : # Copyright (c) 2010, <NAME>. All rights reserved. # For licensing, see LICENSE file included in the package. """ BSON serialization and deserialization logic. Specifications taken from: http://bsonspec.org/#/sp...
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
import os import pickle from typing import List, Tuple import numpy as np import torch import torchvision.transforms as transforms from PIL import Image from randaugment import RandAugment # https://github.com/jizongFox/pytorch-randaugment from torch.utils.data import DataLoader, Dataset class CIFAR10(Dataset): ...
from model import create_model from constants import BOARD_DIM, MAX_TRAINING_SIZE, NO_OF_GAMES, SAVE_DATA_EVERY, SELF_PLAY_C_PUCT, SELF_PLAY_MCTS_ITERS, UPDATE_MODEL_EVERY from helper_methods import dihedral_trans, load_model, load_training_data from apple_chess import Board from model_path_management import best_m...
import tensorflow as tf import tensorflow.keras as keras from tensorflow.keras import layers from tf_package.ConvModel.encoder import vgg16, resnet50 def crop(o1, o2, i): """裁剪o1和o2至相同的尺寸,裁剪的宽和高取两个特征图的最小值""" o_shape2 = keras.Model(i, o2).output_shape output_height2 = o_shape2[1] output_wid...
import importlib import inspect import itertools import warnings from typing import Any, Callable, Dict, Tuple, Union from torch import _C from torch.onnx import _constants, errors __all__ = [ "get_op_supported_version", "get_ops_in_version", "get_registered_op", "is_registered_op", "is_registered...
import click import json import pandas as pd from requests.exceptions import HTTPError from os import environ from os.path import join, dirname from os import makedirs from .. import ( Knex, User, Organization, ) from .utils import use_common_state @click.group('upload') def cli_upload(): pass ov...
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
from django.views.generic import TemplateView from django.shortcuts import render, redirect, get_object_or_404 from django.http import JsonResponse from django.template.loader import render_to_string import win32com.client, datetime, pythoncom, os, re, openpyxl from django.utils import timezone from payments.models im...
"""Tests for the Roku component.""" import re from socket import gaierror as SocketGIAError from homeassistant.components.roku.const import DOMAIN from homeassistant.components.ssdp import ( ATTR_SSDP_LOCATION, ATTR_UPNP_FRIENDLY_NAME, ATTR_UPNP_SERIAL, ) from homeassistant.const import CONF_HOST, CONF_ID,...