text
stringlengths
6.04k
39.5k
#! /usr/bin/env python """ Simple json 2 autoprocotol encoder. Example: cat example.json | apEncoder.py | transcriptic analyze Copyright (C) 2016 cweiland Function gibsonAssembly is completely based on Scott Beckers gibsonAssembly code, see: https://github.com/scottbecker/transcriptic101/tree/master/gibson_assembly...
# -*- coding: utf-8 -*- """ @file @brief Fonctions, classes pour résoudre un puzzle à 9 pièces disposé en carré 3x3. Voir :ref:`l-puzzle_girafe`. """ import time import os from pyquickhelper.loghelper import fLOG from ..helpers.pygame_helper import wait_event, empty_main_loop class PuzzleGirafeBord: """ Défi...
# Copyright 2021 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 to...
# -*- coding: utf-8 -*- """ utils/parsers.py is for classes that parse an API and populate fake data for use in requests """ import logging import random from prance import ResolvingParser from .base import ImplementationError from .constants import DataType, ARRAY_MIN, ARRAY_MAX from .fake_data import MilMoveData fr...
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this f...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division from subprocess import call import matplotlib.pyplot as plt import pandas as pd import numpy as np import argparse import pprint import json import sys import os print(sys.version, file=sys.stderr) print('Numpy version:', n...
import itertools from datetime import timedelta import arrow import flask import hashlib import requests import requests_cache import simplejson as json from flask import make_response, request, current_app, jsonify from flask_cache import Cache from functools import update_wrapper from simplekv.fs import FilesystemSt...
def build_encoder(inputs , num_labels,feature1_dim=256): """ Build the Classifier (Encoder) Model sub networks Two sub networks: 1) Encoder0: Image to feature1 (intermediate latent feature) 2) Encoder1: feature1 to labels # Arguments inputs (Layers): x - images, feature1 - feature1 laye...
# Import modules import pytest import xarray as xr import numpy as np from numpy.testing import (assert_allclose, assert_array_almost_equal, assert_array_equal) # From OceanSpy from oceanspy import open_oceandataset, OceanDataset from oceanspy.compute import (gradient, divergence, curl, ...
# Copyright (C) 2017 Belledonne Communications SARL # # This program 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; either version 2 # of the License, or (at your option) any later version. # # This program i...
""" Define the models to use """ import tensorflow as tf from tensorflow import keras import efficientnet.tfkeras as efn EFFICIENT_NET_INPUT_SHAPE = (224, 224, 3) class VAE(tf.keras.Model): """ Variational autoencoder """ def __init__(self, input_size, latent_dim, enc_dim, dec_dim, human_3d_size=48): ...
# -*- coding:utf-8 -*- import gc import glob import json import os import random import torch from os.path import join as pjoin from collections import Counter from rouge import Rouge from others.logging import logger from others.tokenization import BertTokenizer from others.vocab_wrapper import VocabWrapper def gr...
import matplotlib.pyplot as plt import csv import numpy as np import os def column(matrix, i): return [row[i] for row in matrix]; def getJobName(job): if job == "Foraging" : return job; elif job == "FeedLarvae": return job; else: return "Other"; def getJobHatch(job): if job == "Foraging" : return '//...
# -*- coding: utf-8 -*- """ templatetk.jscompiler ~~~~~~~~~~~~~~~~~~~~~ This module can compile a node tree to JavaScript. Not all that can be compiled to Python bytecode can also be compiled to JavaScript though. :copyright: (c) Copyright 2011 by <NAME>. :license: BSD, see LICENSE for mo...
############################################################################### from functools import partial from math import sqrt from copy import deepcopy import operator, sys import json import pandas as pd import numpy as np from scipy.io import arff from sklearn.model_selection import train_test_split from skle...
import unittest from anxcor.xarray_routines import XArrayXCorrelate, XArrayConverter, XArrayRemoveMeanTrend, XArrayTaper,\ XArrayProcessor, XArrayBandpass import os from anxcor.containers import AnxcorDatabase import glob from anxcor.core import Anxcor import pandas as pd import scipy.signal as sig import numpy as...
# -*- coding: utf-8 -*- ''' Clasificador basado en la técnica de los vecinos más cercanos AUTOR: <NAME> REVISOR: <NAME> ÚLTIMA MODIFICACIÓN: 22/11/2018 El artículo de Wikipedia sobre 'Vecinos más cercanos': https://es.wikipedia.org/wiki/K_vecinos_m%C3%A1s_pr%C3%B3ximos La técnica de vecinos más cercanos...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import pytest from ..aca_image import ACAImage, centroid_fm im6 = np.arange(6**2).reshape((6, 6)) im8 = np.arange(8**2).reshape((8, 8)) def test_init(): # Init from Python list of lists a = ACAImage([[1, 2], [3, 4]]) asse...
#!/usr/bin/env python #copied from https://github.com/ablab/viralVerify/ import os, errno import sys import argparse import collections from math import log from math import exp import csv import operator import time import datetime import fastaparser def parse_args(args): ###### Command Line Argument Parser pa...
""" Downloads and converts files to various formats. """ import os import re from ftplib import FTP import gzip from urllib.parse import urlparse import requests import subprocess import yaml GENE_LIST_HOST = 'hgdownload.cse.ucsc.edu' DOWNLOAD_URL_CHUNK_SIZE = 16 * 1024 def download_and_convert(config, update_progre...
#!/usr/bin/python # # This program reads the angles from the acceleromteer, gyroscope # and mangnetometer on a BerryIMU connected to a Raspberry Pi. # # This program includes two filters (low pass and median) to improve the # values returned from BerryIMU by reducing noise. # # The BerryIMUv1, BerryIMUv...
# coding=utf-8 from __future__ import absolute_import, unicode_literals import email from email.header import decode_header, Header from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formatdate, make_msgid from ...
import sys sys.dont_write_bytecode = True import math import utils #import utils.py from numpy.linalg import inv import tf import tf2_ros import os import cv2 from cv_bridge import CvBridge import rospy import rosbag import progressbar from tf2_msgs.msg import TFMessage from datetime import datetime from std_msgs.msg i...
import random import numpy as np import pyDOE from scipy.interpolate import interp1d class BaseRobotSequences(object): """ Basic control sequences for open loop control :param m: number of actuators :param u0: default "resting" control np array :param umax: max control of each actuator, with resp...
# -*- coding: utf-8 -*- """ Contains the crawling logic. """ from __future__ import unicode_literals, absolute_import import base64 import logging import sys import time from pylinkchecker.bs4 import BeautifulSoup import pylinkchecker.compat as compat from pylinkchecker.compat import (range, HTTPError, get_url_open,...
import sys from dataset_utils.data_iterator import * sys.path.append('../..') from optimizers.optim import SGD_C, SGD, Adam_C, Adam, RMSprop, RMSprop_C import numpy as np import argparse import os import submitit from pathlib import Path from datetime import datetime import wandb from filelock import FileLock import...
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ##...
# -*- coding: utf-8 -*- import datetime import io import os import sys import time import urllib import matplotlib.pylab as plt import numpy as np import pandas as pd import seaborn as sns from keras.layers import LSTM, Activation, Dense, Dropout from keras.models import Sequential from PIL import Image os.environ['TF...
from flask import render_template, flash, redirect, request, session from flask.helpers import url_for from flask_login import current_user, login_user from flask_login.utils import login_required, logout_user from flask_migrate import current from werkzeug.urls import url_parse from wtforms.fields.core import StringFi...
import os import logging import collections import yaml import numpy as np import scipy import torch from mathtools import utils, torchutils, metrics logger = logging.getLogger(__name__) def make_event_assembly_transition_priors(event_vocab, assembly_vocab): def isValid(event, cur_assembly, next_assembly): ...
import torch import torch.nn.functional as F import numpy as np import cv2 import torch.nn as nn """ Robust Charbonnier loss. """ def charbonnier_loss(delta, alpha=0.45, epsilon=1e-3): # alpha is r in paper; epsilon is eta loss = torch.sum(torch.pow(torch.mul(delta, delta) + torch.mul(epsilon, epsilon), alph...
#! /usr/bin/env python import sys, os from enum import Enum ################### HELPERS ########################### def read_fields(f, fields): header={} for (flen, fname, ftype) in fields: header[fname]=ftype.from_bytes(f.read(flen), byteorder=endianness()) return header def endianness(): return 'big' ...
# Copyright (c) 2013, Bantoo and <NAME> and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe import datetime from frappe.utils import flt, cint, getdate, now, date_diff from erpnext.stock.utils import update_included_uom_in_report, is_reposting_item_...
# GUI Super Wonder Captain.py # import io # Provides to use IO import datetime # Provides datetime access. import hashlib # Provides to use hash codes import json # Provides to use json import os # Provi...
import os import random from collections import defaultdict import numpy as np from copy import deepcopy import tensorflow as tf from nlafl import fashionMnist_sample from nlafl.fashionMnist_models import FLServer from nlafl.fashionMnist_models import FederatedClient from nlafl import common # Disable gpu os.environ...
import numpy as np from math import sqrt from enum import Enum def dis(a,b): dx=a[0]-b[0] dy=a[1]-b[1] return sqrt(dx*dx+dy*dy) dragon_init_quality=200 dragon_init_pos=np.array([0.5,0.5]) flight_horizon=0.01 ground_horizon=0.01 #agent self prob l_biomas=0.0 s_biomas=0.0 #eaten prob l_eaten_prob=0.75 s_eat...
from time import sleep import math from PIL import Image import worldedit from static import ref_strings from modules.__init__ import Command, FileIOModule from utils import downloader, message_utils # 以下为从 code connection 里复制的代码,原为js # 进行了一些修改 # 方块颜色值 colors = [ ['concrete', 0, 0xcfd5d6], ['concrete', 1, 0...
from __future__ import division import sys sys.path.append('..') from lib.rng import py_rng, np_rng from lib.data_utils import shuffle, list_shuffle from lib.vis import grayscale_grid_vis, color_grid_vis, rgba_grid_vis import functools from multiprocessing import Pool import numpy as np import scipy.misc import os f...
#!/usr/bin/env python # encoding: utf-8 # Copyright 2012 <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 ap...
# -*- coding: utf-8 -*- """ (C) <NAME> 2017 Currently trying to reproduce parts of "Models relevant to excess heat production in Fleischmann-Pons experiments", Hagelstein & Chaudhary Requires Python 3.5 or higher. """ import numpy as np from itertools import product import matplotlib.pyplot as plt from scipy.optimize...
# Copyright (c) 2015-2019 by the parties listed in the AUTHORS file. # All rights reserved. Use of this source code is governed by # a BSD-style license that can be found in the LICENSE file. import warnings import numpy as np from scipy.constants import arcmin import healpy as hp from ..mpi import use_mpi, MPISh...
#-*- coding: utf-8 -*- """ revision process for: "tertiaryElectricityConsumption_1092915978" "tertiaryElectricityConsumption_7104124143" "gasConsumption_1092915978" "gasConsumption_5052736858" "gasConsumption_3230658933" "gasConsumption_7104124143" "gasConsumption_8801761586" """ import calendar from d...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import datetime import unittest import webapp2 import webtest from google.appengine.api import users from dashboard import stats from dashboard import tes...
import os import re import queue import asyncio import threading from mailtk.data import Mailbox, ThreadInfo, Flag, namedtuple from imapclient import IMAPClient import email import imapclient from mailtk.util import decode_any_header from mailtk.accounts.base import AccountBase class ThreadMessage(namedtuple.abc): ...
# -*- coding: utf-8 -*- """Workchain to compute a band structure for a given structure using Quantum ESPRESSO pw.x.""" from aiida import orm from aiida.common import AttributeDict from aiida.plugins import WorkflowFactory from aiida.engine import WorkChain, ToContext, if_ from aiida_quantumespresso.calculations.functi...
# from model_api.abstract_model_api import AbstractModelAPI from __future__ import division, unicode_literals import argparse import io from itertools import chain import h5py import numpy as np import onmt import onmt.ModelConstructor import onmt.io import onmt.modules import onmt.translate import torch from onmt.io...
""" A Learned Representation of Artistic Style, Domulin et.al. Currently only a single node training loop is implemented. Using the standard_v100 config, 40000 steps can be trained in roughly ~3 hours NOTE: the magenta implementation has a batch size of 16, and trains for 40000 steps. Here, each batch is trained with...
import math import uuid from datetime import datetime from functools import reduce from _decimal import Decimal, ROUND_HALF_UP from django.db import models from django.db.models import Sum, DecimalField, F from django.db.models.signals import pre_delete from django.dispatch import receiver from django.utils import tim...
# coding: utf8 from __future__ import unicode_literals import pytest import numpy from hypothesis import given, settings from numpy.testing import assert_allclose from .. import strategies from thinc.neural.ops import NumpyOps, CupyOps, Ops MAX_EXAMPLES = 10 OPS_CLASSES = [NumpyOps] if CupyOps.xp is not None: ...
import argparse import matplotlib.pyplot as plt from dyna_q import DynaQ from dyna_q_plus import DynaQPlus from dyna_maze import DynaMaze from dyna_maze_part import DynaMazePartitioned from models import FullModel from tabular_q import TabularQ from utils import sample, to_arr import seaborn as sns import numpy as np f...
""" MDS admin socket scrubbing-related tests. """ import json import logging import errno import time from teuthology.exceptions import CommandFailedError import os from tasks.cephfs.cephfs_test_case import CephFSTestCase log = logging.getLogger(__name__) class TestScrubControls(CephFSTestCase): """ Test basi...
""" MediaWiki translator, aimed at Wikipedia/WikiBooks type of web pages. Syntax defined by http://en.wikipedia.org/wiki/Help:Wiki_markup and http://en.wikipedia.org/wiki/Help:Displaying_a_formula. The prefix m in the name mwiki distinguishes this translator from gwiki (googlecode wiki). Not yet implemented: mwiki_ref...
""" @license: MIT @repository: https://github.com/semontesdeoca/MNPR _ _ _ _ _ __ ___ __ _| |_ ___ _ __(_) __ _| | _ __ _ __ ___ ___ ___| |_ ___ | '_ ` _ \ / _` | __/ _ \ '__| |/ _` | | | '_ \| '__/ _ \/ __|/ _ \ __/ __| | | | | | | ...
"""show_mpls.py JUNOS parsers for the following commands: * show mpls lsp name {name} detail * show mpls lsp name {name} extensive """ import re # Metaparser from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Any, Optional, Use, Schema from genie.metaparser.util.exceptions...
#pylint: disable-all """ E.g., nb201: python evaluation.py -t deiso /home/eva_share_users/foxfi/surgery/nb201/results_derive/deiso_plateaulr_seed202020/*.yaml --save /home/eva_share_users/foxfi/surgery/nb201/results_derive/deiso_plateaulr_seed202020_stat.pkl """ import os import argparse import yaml import numpy as np...
# -*- coding: utf-8 -*- # Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <<EMAIL>> # Copyright (c) 2014-2018 <NAME> <<EMAIL>> # Copyright (c) 2014 <NAME> <<EMAIL>> # Copyright (c) 2014 Google, Inc. # Copyright (c) 2014 <NAME> <<EMAIL>> # Copyright (c) 2015 <NAME> <<EMAIL>> # Copyright (c) 2016 <NAME> <<EMAIL>> # ...
import collections import functools import logging import sys import time import types import weakref import tensorflow as tf def main_loop(sess=None, sess_creator=None, ops=(), hooks=None): if sess is None: sess = MonitoredSession(sess_creator, hooks=hooks) else: sess = wrap_session_with_hoo...
"""Git specific support and addon.""" import argparse import os import re import shlex import subprocess from collections import defaultdict, deque from dataclasses import dataclass from datetime import datetime from functools import partial from itertools import takewhile from pathspec import PathSpec from pkgcore.e...
#!/usr/bin/env python3 # encoding: utf-8 import os import numpy as np from copy import deepcopy from collections import deque from mlagents_envs.environment import UnityEnvironment from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel from mlagents_envs.side_channel....
""" Define apertures to use for on-sky integrations. ---- .. include license and copyright .. include:: ../include/copy.rst ---- .. include common links, assuming primary doc root is up one directory .. include:: ../include/links.rst """ import os import numpy import time from scipy import signal from shapely.g...
# coding: utf-8 import math import numpy as np import torch from torch import nn # BERT用にLayerNormalization層を定義します。 # 実装の細かな点をTensorFlowに合わせています。 class BertLayerNorm(nn.Module): """LayerNormalization層 """ def __init__(self, hidden_size, eps=1e-12): super(BertLayerNorm, self).__init__() se...
# -*- coding: utf-8 -*- #* Copyright (c) 2020 Intel Corporation import os,sys,copy,json import subprocess import datetime import time import shlex import glob import multiprocessing #parse json file with open("release.json","r") as load_f: load_dict = json.load(load_f) load_f.close() with open("deb.json","r") as loa...
# coding: utf-8 # # Exploring the NHC Advisories and Sea Surface Height during Hurricane Irma # # # This notebook aims to demonstrate how to create a simple interactive GIS map with the National Hurricane Center predictions [1] and the observed sea surface height from CO-OPS [2]. # # # See https://tidesa...
#!/usr/bin/env vpython3 # # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import collections import functools import logging import re import subprocess import sys DEX_CLASS_NAME_RE = re.c...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from typi...
import re import errno import subprocess import time import os import platform from collections import deque from collections import namedtuple import inspect import json import shlex import socket from datetime import datetime from sys import stdout from sys import exit import traceback ##############################...
import sys, os import pickle import numpy as np import mahotas import getLogDistributions as gLD import matplotlib.pyplot as plt import matplotlib as mpl from skimage import measure import scipy.ndimage as nd def pixels_at_edges(cluster, with_diagonal=True): """ Finds the pixels at the edges of a compact clust...
'''generic limbs. Offsets, etc.''' import maya.cmds as cmds import mpyr.lib.rigmath as mpMath import mpyr.lib.rig as mpRig import mpyr.lib.joint as mpJoint import mpyr.lib.nurbs as mpNurbs import mpyr.lib.attr as mpAttr import mpyr.rig.limb.limbBase as limbBase class WorldOffset(limbBase.Limb): '''A character's r...
""" Functions: find_bfrm_bin find_bfrm_normalize find_bfrm_project get_default_parameters init_parameters read_model clean_model read_clean_model get_affy_row_name is_affx """ import os, sys def find_bfrm_bin(default_path=None): import config search_paths = [ default_path, config.bfrm...
# # STEP Part 21 Parser # # Copyright (c) 2011, <NAME> (<EMAIL>) # Copyright (c) 2014, <NAME> (<EMAIL>) # # All rights reserved. # # This file is part of the StepClassLibrary (SCL). # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condition...
from llama import Llama from . import _util as util import discord from discord.ext import commands import re import datetime import operator import traceback from threading import Timer class Pinning(commands.Cog): # Roles that are allowed to pin messages # key: server id | value: set of role ids allow...
import math import torch.nn as nn import torch.nn.functional as F import torch from timm.models.layers import variance_scaling_ def make_cross_attention_mask(query_mask, kv_mask): batch_size, query_len = query_mask.shape _, key_len = kv_mask.shape mask = torch.einsum("bi,bj->bij", (query_mask, kv_mask))...
# Created By: <NAME> # Created On: 2008-05-29 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.htm...
#!/usr/bin/python import yaml import boto3 import os import pprint import time import speech_recognition as sr import uuid import logging from speaker.speaker import Speaker from botocore.exceptions import ClientError class LexSlotManager: def __init__(self, **kwargs): self.client = boto3.client('lex-mode...
#!/usr/bin/env python # Copyright 2017 ARC Centre of Excellence for Climate Systems Science # author: <NAME> <<EMAIL>> # # 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.apach...
import torch from typing import Callable, Iterable, Tuple from torch import nn from torch.optim import Optimizer from torch.nn import functional as F from transformers import AutoModel from torch.optim.lr_scheduler import LambdaLR from math import log, pi, exp import numpy as np import random from scipy import linalg a...
### cpx-basic-square-duosynth v1.2 ### CircuitPython (on CPX) two oscillator synth module (needs some external hardware) ### Duophonic velocity sensitive synth with pitch bend and mod wheel ### and ADSR control ### Wiring ### A0 Ana0 ### A1 Osc1 ### A2 VCS1 ### A3 VCA2 ### A6 Osc2 ### GND and 3V3 to power exter...
import os import argparse import collections from collections import defaultdict import json import librosa import numpy as np from iterstrat.ml_stratifiers import MultilabelStratifiedShuffleSplit def parse_label_file(filename, classes_list): """Read the events timestamps from a label file (.txt) produced by Cl...
import base64 import hmac import json import sys from datetime import datetime from hashlib import sha256 from typing import Dict, Any from urllib.parse import urlencode from vnpy.api.rest import RestClient, Request from vnpy.event import EventEngine from vnpy.trader.constant import Status, Direction, PriceType from v...
#!/usr/bin/python # Classification (U) """Program: mail_2_rmq.py Description: Process an email message and send it to the proper RabbitMQ queue. Usage: -M options: email_alias: "| /path/mail_2_rmq.py -c file -d path -M [-y flavor_id]" cat email_file | /path/mail_2_rmq.py -c ...
import os import nni import copy import torch import argparse import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.utils import utils from model import NetworkCIFAR as Network import genotypes from data_loader import get_cifar import pandas as pd from model_factory import creat...
from pathlib import Path from typing import List, Optional import tensorflow as tf from zookeeper import ComponentField, Field, factory from larq_zoo.core.model_factory import ModelFactory class AttentionMatchingLossLayer(tf.keras.layers.Layer): """Layer that adds a loss and a metric based on the difference is ...
import os import sys import numpy as np from itertools import compress import matplotlib matplotlib.use('pdf') import matplotlib.pyplot as plt import importlib import argparse import tensorflow as tf import multiprocessing as mp import pickle import visualization import provider import utils import time BASE_DIR = os....
from threading import Lock, Thread from typing import Optional, TYPE_CHECKING, Dict, Callable import telegram from telegram import Chat, InputMediaPhoto, InlineKeyboardButton, InlineKeyboardMarkup, Update, Message, TelegramError from telegram.ext import Updater, Filters, BaseFilter, CallbackQueryHandler, CallbackConte...
# -*- coding: utf-8 -*- """ Created on Wed May 30 11:44:17 2012 @author: proto """ from copy import deepcopy from lxml import etree import pygraphviz as pgv import re from random import randint from pyparsing import Word, Suppress, Optional, alphanums, Group, ZeroOrMore from collections import Counter def parseReacti...
from .. import stage as st import visa import time import Gpib def find_stages( num_gpib_ports_check=10, gpib_device_nums_check=4, timeout_gpib_read_ms=100 ): gpib_stages_found = [] rm = visa.ResourceManager("@py") for gpib_port_num in range(num_gpib_ports_check): for gpib_device_num in range(...
#!/usr/bin/python # Copyright 2020 Makani Technologies LLC # # 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 applicabl...
# Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions for parsing pprof, CWP data and Chrome OS groups files.""" from collections import defaultdict import csv import os import re SEPAR...
import sys,os import re from typing import Dict, List, Optional, Set, Callable from collections import defaultdict, Counter import torch from allennlp.common.checks import ConfigurationError from allennlp.nn.util import get_lengths_from_binary_sequence_mask from allennlp.data.vocabulary import Vocabulary from allennl...
"""Provide alarm management. """ import sys import collections import datetime import logging log = logging.getLogger('msiempy') from . import NitroDict, NitroList, FilteredQueryList from .event import EventManager, Event from .__utils__ import regex_match, convert_to_time_obj, dehexify __pdoc__={} class AlarmManag...
import copy from typing import Optional, List import torch import torch.nn.functional as F from torch import nn, Tensor from .MultiheadAttention import DeformableHeadAttention, generate_ref_points class Transformer(nn.Module): def __init__(self, d_model=512, nhead=8, ...
from collections import Counter import random def get_wordlevel_reprs(speechreps, word_align): """ extract subsequence of 'repr' that corresponds to a particular word function expects input to be of dimension 2: (timesteps, hidden_size) """ start_fraction = word_align['start'] / word_align['utt_dur...
from collections import deque import numpy as np import math, random, logging from concurrent.futures import ProcessPoolExecutor, as_completed import multiprocessing as mp from collections import defaultdict from time import time from utils import * def generate_similarity_network(file_list, workers): t0 = time...
""" Copyright (c) 2020 Intel 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 agreed to in writin...
import math import random from copy import deepcopy from os.path import basename import cv2 import numpy def resample(): return random.choice((cv2.INTER_LINEAR, cv2.INTER_CUBIC)) def resize(image, image_size): h, w = image.shape[:2] ratio = image_size / max(h, w) if ratio != 1: shape = (int...
#!/usr/bin/env python ''' Script that constructs the documentation for piles. Usage: .. code-block:: none docpiles.py path/to/piles ''' __authors__ = '<NAME>' __copyright__ = 'Copyright 2015, Piles Contributors' __credits__ = [] __license__ = '3-clause BSD' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' impor...
from typing import NamedTuple, List, Tuple, Set, FrozenSet, Dict, Optional, Union, Generic, TypeVar from typing import Deque from itertools import chain from collections import deque from enum import Enum, auto T = TypeVar("T") T1 = TypeVar("T1") T2 = TypeVar("T2") class Shift(NamedTuple): state :int class Redu...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys if sys.version_info[0] > 2: from tkinter import * import tkinter.ttk as ttk import tkinter.filedialog as tkFileDialog from tkinter.messagebox import * else: import ttk from T...
""" Epistemic uncertainty query strategy """ # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> import warnings import numpy as np from scipy.interpolate import griddata from scipy.optimize import minimize_scalar, minimize, LinearConstraint from sklearn import clone from sklearn.linear_model import LogisticRegressi...
""" Reworked code based on http://trevorius.com/scrapbook/uncategorized/pyqt-custom-abstractitemmodel/ Adapted to Qt5 and fixed column/row bug. TODO: handle changing data. Taken from : https://gist.github.com/nbassler/342fc56c42df27239fa5276b79fca8e6 """ import sys from typing import Any, Callable, Dict, List, Union...