text
stringlengths
3.07k
12.6k
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is the entry point for the command-line interface (CLI) application. It can be used as a handy facility for running the task from a command line. .. note:: To learn more about Click visit the `project website <http://click.pocoo.org/5/>`_. There is als...
import argparse import logging import os import json from allennlp.commands.subcommand import Subcommand from allennlp.commands.train import train_model_from_file from allennlp.common import Params logger = logging.getLogger(__name__) # pylint: disable=invalid-name class Group_Train(Subcommand): def add_subpars...
import configparser import csv import random import time import os from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler import html # def prepare_dataset(config): # questions = open(config['q...
import _init_paths import argparse import yaml import os.path as osp from attrdict import AttrDict import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from datasets.mini_imageNet import MiniImageNet from utils.samplers import CategoriesSampler from m...
#============================================================================== # arbiters_test.py #============================================================================== # This file contains unit tests for the arbiters collection models. from pymtl import * from pclib.test import TestVectorSimulator from...
import os import pickle import queue import time import unittest from bsbolt.CallMethylation.CallValues import CallMethylationValues from bsbolt.CallMethylation.CallVector import CallMethylationVector from tests.TestHelpers import bsb_directory, z_test_of_proportion bsb_index = os.path.exists(f'{bsb_directory}tests/...
import sys import os import re import MaRQ def is_number(string): try: float(string) return True except ValueError: return False def triple_pattern_to_sparql(pattern): if pattern['predicate'] == 'a': return pattern['subject'] + ' ' + pattern['predicate'] + ' <' + pattern[...
import time, threading from datetime import timezone from datetime import datetime from dateutil import tz import calendar from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_gps_v2 import BrickletGPSV2 from tinkerforge.bricklet_oled_128x64 import BrickletOLED128x64 from tinkerforge.bricklet...
#!/usr/bin/env python """Takes GPS values and converts and publishes X/Y ENU coordinates""" from __future__ import print_function from __future__ import division import math import rospy from sensor_msgs.msg import NavSatFix from geometry_msgs.msg import Point, Pose, PoseStamped from std_msgs.msg import Header from...
''' Created on Jul 8, 2014 @author: <NAME> <y.zhalnerovich{at}gmail.com> ''' from xml.dom import minidom class AndroidManifest: def __init__(self, pathAndroidManifest): self.pathAndroidManifest = pathAndroidManifest self.xml = minidom.parse(pathAndroidManifest) self.packageName = self.getEl...
# !/usr/bin/env python3 import multiprocessing import os import sys import time from past.builtins import raw_input import botocore import pyodbc import requests from requests import ReadTimeout import ASFFMapper as Mapper import DatabaseConnector from datacollectorapiMOD import client from CloudHandlers.AzureDataCo...
# Copyright 2019 British Broadcasting Corporation # # 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 a...
from twisted.python import log from buildbot.status.builder import WARNINGS from buildbot.steps.shell import ShellCommand try: import cStringIO StringIO = cStringIO except ImportError: import StringIO class LintStep(ShellCommand): """ A L{ShellCommand} that generates summary information of errors ...
""" Grid display. Displays a rectangular grid of cells, organized in rows and columns with row 0 at the top and growing down, column 0 at the left and growing to the right. Uses the simple graphics module provided by Zelle, which in turn is built on the Tk graphics package (and which should therefore be availabl...
import json from collections import OrderedDict from tqdm.auto import tqdm import torch import pytorch_lightning as pl from transformers import ( BertTokenizer, BertForQuestionAnswering, get_constant_schedule_with_warmup, get_constant_schedule, ) from ..utils.util import accuracy_precision_recall_f1 ...
# Copyright 2016 United States Government as represented by the Administrator # of the National Aeronautics and Space Administration. All Rights Reserved. # # Portion of this code is Copyright Geoscience Australia, Licensed under the # Apache License, Version 2.0 (the "License"); you may not use this file # except in c...
from abc import ABC, abstractmethod from xml.dom import minidom from xml.etree.ElementTree import Element, SubElement, Comment, tostring from harvestmouseapp.mvc_model.model import MouseList import json class GenericMouseViewer(ABC): """ This is the Mouse Model Adapter Class. Subclass must implement the t...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging from placethings.config.wrapper.config_gen import Config from placethings.definition import Unit from placethings.demo.utils import ConfigDataHelper from ...
# -*- coding: utf-8 -*- import os import sys sys.path.insert(0, '../utils') import numpy as np from numpy import array import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import time from copy import deepcopy import cv2 from utils_geom import * # from utils_plot import * def sav...
import os import random import requests from utils import Config, FileNames, Important, WebsiteData, log def others(request, query): thecatapi_url_list = [] thecatapi_usage = False dogceo_url_list = [] dogceo_usage = False nekoslife_url_list = [] nekoslife_usage = False if WebsiteData.se...
# 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 file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# -*- coding: utf-8 -*- """ Created on Sat Nov 9 15:46:52 2019 @author: <NAME> """ ''' In this script I functions for easy use of following 1. convolution 2. pooling 3. back convolution 4. back pooling ''' import numpy as np #---------------Single Layer/channel Conv 1st filter-------------------...
""" An example drawing a huge map to offscreen then view that map form different actor viewpoints. This example is using the lower level rendering API in arcade. """ import random from typing import Tuple import arcade from arcade.gl import geometry class ActorMap(arcade.Window): def __init__(self): su...
# search.py # --------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # A...
import time from comm import * from cluster import * from flow_control import * from jobgen import * from plot_utils import * class EdgeCloud(): def __init__(self, listen_ip_l, max_delay): self.max_delay = max_delay self.commer = Commer(listen_ip_l, self.handle_msg) self._id = self.commer._id input("Enter f...
# Copyright 2016 Red Hat, 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 agre...
import subprocess import os import logging import threading import time if __name__ == '__main__': import exceptions else: from chiptools.common import exceptions log = logging.getLogger(__name__) def iterate_tests(test_suite_or_case): """Iterate through all of the test cases in 'test_suite_or_case'."""...
import json import os import shutil from config import Config from mss import mss from utils.misc import close_down_bnet_launcher, close_down_d2 def get_d2r_folder() -> str: """ Get D2r folder try to find pre-set D2r folder :param config: the general config possibly containing 'saved_games_folder' ...
from os.path import dirname, abspath from tinydb import TinyDB, where from typing import List from distance import levenshtein from jellyfish import jaro_winkler_similarity from functools import lru_cache parent_directory = dirname(dirname(dirname(abspath(__file__)))) lemmas_path = parent_directory + "/resources/lemma...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ extract features from question texts """ import sys import os import csv import traceback import warnings import tqdm import scipy.stats import sklearn.metrics.pairwise import numpy as np import pandas as pd import multiprocessing import ctypes from collections import...
import functools import os import numpy as np import tensorflow as tf def build_model_specification(inputs, model_fn, loss_fn, optimizer, reuse=False): specification = inputs with tf.variable_scope('model', reuse=reuse): logits = model_fn(specification['images']) loss = loss_fn(specification['la...
#!/usr/bin/env python # # Copyright (c) 2018 Via Technology Ltd. All Rights Reserved. # Consult your license regarding permissions and restrictions. """ Software to merge Eurocontrol APDS data and a days merged trajectories. """ import sys import os import errno import pandas as pd from uuid import UUID from pru.traje...
production = False class Data: """ip信息""" homework_name = '作业流程自动测试' work_name = '测试作品' test_field_file_name = 'hey' test_field_output = 'Hello World!' material_name = 'test1' password_for_edu = '<PASSWORD>' password_for_uniTeach = '<PASSWORD>' username_for_uniLab = '15208451940...
from __future__ import print_function import argparse from math import log10 import torch import torch.nn as nn import torch.optim as optim from torch.optim.lr_scheduler import StepLR, MultiStepLR from torch.utils.data import DataLoader from model import SpatialSpectralSRNet from data import get_patch_training_set, ge...
from abc import ABC, abstractmethod from typing import Any from synthesis.synthesizer.tf_to_torch.torch_enumerator import * from synthesis.synthesizer.tf_to_torch.torch_decider import * from synthesis.synthesizer.synthesizer import * from synthesis.synthesizer.tf_to_torch.torch_spec import * from autotesting.auto_test_...
import os import sys from typing import Any, Tuple import networkx as nx def _import_graph_tool(): # Naively assume everything is set up try and see if can just be imported try: import graph_tool as gt return gt except ModuleNotFoundError: pass # Note: graph-tool installs to ...
from __future__ import unicode_literals from django.template.defaultfilters import slugify from django.db import models from django.core.validators import validate_comma_separated_integer_list class Contact(models.Model): TEAM = 'team' PERSON = 'person' TYPE_OPTIONS = ( (TEAM, 'Team'), (PE...
""" Returns histogram bin counts for a given array of values. """ from __future__ import print_function import numpy import pyferret # The following is just to circumvent to call to pyferret.get_axis_info for testing DOING_UNIT_TEST = False def ferret_init(id): """ Initialization for the stats_histogram Fer...
import os import sys import glob from PIL import Image from tqdm import tqdm DATASETS = ['IC15', 'IC13', 'HRSC2016', 'DOTA', 'UCAS_AOD', 'NWPU_VHR' , 'GaoFenShip', 'GaoFenAirplane', 'VOC'] def bmpToJpg(file_path): for fileName in tqdm(os.listdir(file_path)): newFileName...
""" A naive implementation of blocked Cholesky using Numba kernels on CPUs. """ import numpy as np from numba import jit, void, float64 import math import time from parla import Parla, get_all_devices from parla.cuda import gpu from parla.cpu import cpu from parla.function_decorators import specialized from parla.t...
from logging import getLogger from django.conf import settings from django.utils.six import text_type from api.api_views import APIView # noinspection PyProtectedMember from api.fields import get_boolean_value from api.exceptions import NodeIsNotOperational, PreconditionRequired, ObjectNotFound, GatewayTimeout from a...
import numpy import h5py import pandas as pd from os import listdir from scipy.stats import kurtosis,moment,skew,entropy,gmean,median_absolute_deviation,gstd from re import search from warnings import filterwarnings filterwarnings('ignore') numpy.seterr(divide='ignore',invalid='ignore') class feat_extract: ...
import functools import json import os from hfutils.arg_parser import TestArguments from hfutils.constants import TASK_TO_LABELS from hfutils.loader import DatasetLoader, ModelLoader from hfutils.plot import distplot from numpy import random from packaging.version import parse import torch from transformers.data.data_c...
import os import argparse import numpy as np from torch.backends import cudnn from loader import get_loader, get_model from feature_extractor import FeatureExtractor from graph_constructor import GraphConstructor from solvers import Solver_ATMR from evaluator import Evaluator def evaluate(config): # Data loader ...
"""Vehicle class definitions.""" from typing import Final, List, Optional, Union from ..base import Cached, ImageMixin, Named from ..census import Query from ..models import VehicleAttachmentData, VehicleData from .._rest import RequestClient from .._proxy import InstanceProxy, SequenceProxy from ..types import Local...
# -*- encoding: utf-8 -*- """ License: MIT Copyright (c) 2019 - present AppSeed.us """ # Python modules import os, logging # Flask modules from flask import render_template, request, url_for, redirect, send_from_directory, jsonify from flask_login import login_user, logout_user, current_user, lo...
# Copyright 2018 <NAME>. 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 or agree...
import numpy as np from keras.preprocessing.image import random_rotation, apply_transform, transform_matrix_offset_center, random_zoom, load_img from scipy.ndimage.morphology import distance_transform_edt from scipy.ndimage.measurements import label import PIL from matplotlib import pyplot as plt def morphological_we...
import numpy as np import functools import gym import numpy as np from torch import nn import pfrl from pfrl.agents import PPO as ppo from pfrl import experiments from pfrl import utils as pfutils import logging import torch import copy import utils class MyEnv(gym.Env): def __init__(self, env): self.a...
from typing import Union import discord from discord.ext import commands from PyDiscordBot.utils import MessagingUtils, ModUtils, DataUtils class Management(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() @commands.guild_only() @commands.has_permissions(administra...
#!/usr/bin/env python3 """ The HubShare main application. """ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from datetime import datetime import logging import os from urllib.parse import urlparse from jinja2 import Environment, FileSystemLoader from tornado.http...
#!/usr/bin/python3 from xcffib import connect, xproto from xcffib.xproto import MotionNotifyEvent, ConfigWindow, GetPropertyType from ewmh import EWMH from sys import argv, exit import pynput from pynput.mouse import Button from time import sleep import cProfile def get_mouse_position(mouse): def on_move(x, y): ...
import math import RegExService import random import numpy from functools import reduce import sys import getopt alfa = 2 beta = 5 sigm = 3 ro = 0.8 th = 80 fileName = "E-n22-k4.txt" iterations = 100 ants = 25 def generateGraph(): capacityLimit, graph, demand, optimalValue = RegExService.getData(fileName) ve...
""" Most of this modeling came from https://github.com/stefanfoulis/django-packageindex Thanks to all those who contributed. """ import xmlrpc from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.postgres.fields import JSONField from . import conf try: basest...
import sys import numpy as np import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F from relnet.agent.fnapprox.gnn_regressor import GNNRegressor from relnet.utils.config_utils import get_device_placement sys.path.append('/usr/lib/pytorch_structure2vec/s2v_lib') from py...
# Copyright 2013 <NAME> # # 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 writing, softw...
""" Djukebox Views """ from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.conf import settings from django.db import transaction from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.view...
import jieba # pre = 'G:\\bigdata\\badou\\00-data\\' pre = 'F:\\00-data\\' mode_path = pre + 'out\\hmm\\hyj_hmm.model' filter_val = 0.02 # 频次为0的默认无穷小概率 min_prob = -100000.0 # 1.加载模型 with open(mode_path, 'r', encoding='utf-8') as f: # 初始状态概率 pi = eval(f.readline()) # 状态转移概率 A = eval(f.readline()) # ...
# import shutil import torch # import torch.nn as nn # import torch.optim as optim import numpy as np # import torchvision from torchvision import datasets, models, transforms # import argparse # import time # import os, sys # import copy # from torch.optim.lr_scheduler import MultiStepLR, ReduceLROnPlateau # from tens...
import logging import pathlib import typing as t from collections import defaultdict from starlette.types import ASGIApp, Receive, Scope, Send from connexion.apis.abstract import AbstractSpecAPI from connexion.exceptions import MissingMiddleware from connexion.http_facts import METHODS from connexion.lifecycle import...
import pytest try: import niswitch from niswitch.errors import DriverError except ImportError: pytest.skip("niswitch not found", allow_module_level=True) from qcodes_contrib_drivers.drivers.NationalInstruments.PXIe_2597 import NI_PXIe_2597 as PXIe_2597 # NOTE: if running tests in parallel, a lock file sho...
from pyparsing import * import string import re # # This module contains a parser for a simple query language that can encode # in value of a URL query parameter without the need to encode any characters. # # There are six comparison operators: # # ~eq~ - string or numeric equals in the case of string equals * can...
from abc import ABCMeta, abstractmethod from struct import pack from binascii import hexlify from database.db0 import db0, ConstDB, Channel from userver.object.const import FieldDevice, ClassType, FieldGroup, MAX_FRMPAYLOAD_LENGTH from utils.log import Logger, Action, Resource from utils.errors import AppSKeyAbsence, S...
# Copyright 2017 Rackspace # 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 applic...
import numpy as np from matplotlib import pyplot as plt import scipy.io.wavfile as wav from numpy.lib import stride_tricks import wave import os """ short time fourier transform of audio signal """ def stft(sig, frameSize, overlapFac=0.5, window=np.hamming): win = window(frameSize) hopSize = int(frameSize - np...
# -*- coding: utf8 -*- # Copyright 2011 <NAME> # # Copyright 2008 <NAME> # Copyright 2008 <NAME> # # This file is derived from Kochief project. # # Kochief is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eit...
import json with open('Data/data-text-classification/recipes.json') as f: Recipes = json.load(f) Ingredients = ['\n'.join(v['Ingredients']) for r,v in Recipes.items()] Procedures = ['\n'.join(v['Procedure']) for r,v in Recipes.items()] ''' Confusion Matrix Code ''' import numpy as np import matplotlib ...
import os import time import gym import keras.optimizers from keras import backend as K from keras.layers import Dense import numpy as np import pandas as pd import tensorflow as tf from tqdm import tqdm from dqn_lib import DQNAgent os.environ['PYTHONHASHSEED'] = '0' seed = 17 np.random.seed(seed) tf.set_random_seed(...
from os.path import join, isfile from keras.callbacks import (Callback, ModelCheckpoint, CSVLogger, ReduceLROnPlateau, LambdaCallback, LearningRateScheduler) from keras.optimizers import Adam, RMSprop, SGD, TFOptimizer from rastervision.common.optimizers.yello...
""" Model classes. Useful for bindings. """ from __future__ import annotations # standard libraries import asyncio import operator import typing # third party libraries # none # local libraries import weakref from . import Event from . import Observable from . import Stream from .ReferenceCounting import weak_p...
# -*- coding: utf-8 -*- # # Copyright (c) 2018 <NAME>. # All rights reserved. # # Copyright (c) 2018-2020 <NAME> <<EMAIL>>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistr...
# -*- coding: utf-8 -*- __all__ = [ 'calculate_periods', 'eigenvalues_sorted', 'find_cyclic_classes', 'find_lumping_partitions', 'gth_solve', 'rdl_decomposition', 'slem' ] ########### # IMPORTS # ########### # Standard from itertools import ( chain as _it_chain ) from math import (...
import codecs import datetime as dt import os import re from configparser import ConfigParser from xml.etree import ElementTree as et from bs4 import BeautifulSoup as bs from progress.bar import IncrementalBar from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec ...
""" <NAME> <EMAIL> 21-Apr-2018 <NAME> <EMAIL> 26-Nov-2018 General utilities available to the filter and internal functions. """ import contextlib import numpy as np from numpy.random import normal as sample1d from gym_tools.map_generator import FieldMap from matplotlib import animation as anim def wrap_angle(angl...
from unittest import TestCase from func_prog.pipe import ( func_pipe, pipe_class, chain_pipe, map_pipe, filter_pipe, reduce_pipe ) def add_1(value): return value + 1 def add_tuple_1(values): return tuple([v + 1 for v in values]) def sum_all(x, y, z): return x + y + z class TestFuncPipe(...
from typing import List import numpy as np import torch import torch.nn.functional as F import torchvision.transforms as transforms from core.transforms import centercrop_transform from data_loader import ImagerLoader, default_loader class ImageLoaderSineCosine(ImagerLoader): """ ImageLoader of LSTM model. ...
import numpy as np import fvcore.nn.weight_init as weight_init import torch from torch import nn from torch.nn import functional as F from detectron2.layers import Conv2d, ShapeSpec, get_norm from detectron2.utils.registry import Registry ROI_BOX_HEAD_REGISTRY = Registry("ROI_BOX_HEAD") ROI_BOX_HEAD_REGISTRY.__doc__ ...
from flask import Flask, request, jsonify, send_from_directory, redirect, url_for, session from flask.helpers import flash from functools import wraps from configparser import ConfigParser from lib import Analyze from lib import CoursePrerequisites import os def login_required(f): @wraps(f) def decorated_func...
#!/usr/bin/env python import time import rospy from statek_hw.srv import SetMotorParams from statek_hw.srv import SetImuParams from statek_hw.srv import SetOdomParams from statek_hw.srv import SetMotorParamsRequest from statek_hw.srv import SetImuParamsRequest from statek_hw.srv import SetOdomParamsRequest def send_m...
import numpy as np from scipy import optimize import sys from astropy import modeling from itertools import chain from nuclear.ejecta import Ejecta from nuclear.nuclear_data import DecayRadiation from scipy import stats from collections import OrderedDict import pandas as pd from astropy import units as u import p...
import pandas as pd import matplotlib.pyplot as plt import numpy import sklearn.neighbors from sklearn import metrics from sklearn.cluster import KMeans, DBSCAN from sklearn.decomposition import PCA """ ## 3. Clustering Let's then run a hierarchical clustering algorithm (it will take a while) to see how the data is...
import torch import cv2 import os import struct import time from torchsummary import summary from unet import UNet import numpy as np import torch.nn.functional as F from torchvision import transforms #torch.backends.cuda.matmul.allow_tf32 = False #torch.backends.cudnn.allow_tf32 = False def tofile(img, file_path = "...
# encoding: utf-8 # # Imports from __future__ import unicode_literals from wrapt import decorator from inspect import isclass from mongoengine import Document, EmbeddedDocument from mongoengine import StringField, DateTimeField, GenericReferenceField, DynamicField, EmbeddedDocumentField from .exc import CacheMiss f...
from __future__ import annotations import numpy as np import pandas as pd from sklearn import datasets from IMLearn.metrics import mean_square_error from IMLearn.utils import split_train_test from IMLearn.model_selection import cross_validate from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ...
# Copyright 2010 Isotoma Limited # # 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 writing...
# -*- coding: utf-8 -*- from inspect import Parameter from collections import OrderedDict import tempfile import pytest from unittest.mock import Mock, patch from django.core.cache import caches from dashboard.libs import cache_tools locmem_cache = caches['caching-test'] empty = Parameter.empty def echo(*arg, **k...
from datetime import datetime from prettytable import PrettyTable from covid19 import printer, logger, helpers def global_parser(DETAILS): try: x = PrettyTable(padding_width=3) rangebi = printer.Rangebi() # parsing country details last_updated_on = DETAILS['lastupdatedtime'] ...
import numpy as np LATTICE_TOL = 1e-10 def compare_position(x1, x2): return (np.abs(x1-x2) < LATTICE_TOL).all() def get_lattice_geometry(lattice_type, lx, ly, unit_cell_mult=1): if lattice_type == 'triangle': x = np.array([1.0, 0.0]) basis = x[:, None] * np.arange(unit_cell_mult)[None, :] ...
import torch import random import math import numpy as np from torch import nn, Tensor from torchaudio import transforms as T from typing import Tuple ####################################################### ## Voice Activity Detector class VoiceActivityDetector(nn.Module): def __init__(self): super().__i...
# -*- coding: utf-8 -*- """Implementation of early stopping.""" import dataclasses import logging from dataclasses import dataclass from typing import Any, Callable, List, Mapping, Optional, Union import numpy from .stopper import Stopper from ..evaluation import Evaluator from ..models.base import Model from ..tra...
import itertools import xml.etree.cElementTree as ET import requests if __name__ == "__main__" and __package__ is None: # fix the path so this can be run from the commandline import os from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) if os.getenv('DJANGO_...
from sympy import * import utils class Gate(object): """Gate class for quantum operations. Attributes: name (str): name of the gate indexes (int or list of ints): indexes to perform the quantum gate on gate (sympy Matrix): gate operation template (str): template for OpenQASM c...
# Copyright 2017, bwsoft management # # 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 wr...
""" .. Copyright (c) 2014-2017, Magni developers. All rights reserved. See LICENSE.rst for further information. Module providing custom data types. Routine listings ---------------- ClassProperty(property) Class property. ReadOnlyDict(collections.OrderedDict) Read-only ordered dict. """ from __f...
import time from PIL import Image from django.contrib.auth.models import User from django.shortcuts import render from django.http import HttpResponseRedirect, Http404, JsonResponse from django.urls import reverse from .forms import TopicForm, EntryForm from .models import Topic, Entry from django.contrib.auth....
import os import enum import re #分析安装包大小 outPath = "/Users/luph/Documents/sizetj/tmp/" #输出目录 appPath = "/Users/luph/Desktop/yymp/Payload/YYMP.app" cmpPath = "" # TagType = Enum('TagType', ('up', 'down', 'add','other')) class TagType(enum.IntEnum): Add = 4 Up = 3 Down = 2 Del = 1 Other = 0 clas...
import collections def invert_dict(d): ''' Get the anti-dict, where the keys become the values and the values become the keys. Example ------- >>> from littletools.dict_tools import * >>> d = { ... 1:[1,2,3], ... 6:[3,4,1] ...
# import hardcoded information from fileserver import sys sys.path.append(r'\\fileserver.valuecare.local\Algemeen\Automatisch testen\Python') from parameters import HardCodedParameters # import other dependencies from pandas import DataFrame class Instelling: def __init__(self, klant_code: str): self.klan...
""" MIT License Copyright (c) 2019-2021 naoTimesdev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publi...
# Standard Library import os import time from datetime import datetime # Third Party import numpy as np import pytest import tensorflow as tf from tensorflow import keras from tests.core.utils import check_tf_events, delete_local_trials, verify_files # First Party from smdebug.core.modes import ModeKeys from smdebug....