text
stringlengths
3.07k
22.1k
''' Support utilities for value types and various utilities for working with type names and constructor parameters. ''' import re import sys from typing import Any, AnyStr, Dict, List, Optional, Text, Tuple AnyScope = Dict[Text, Any] PARENS_START = '(' PARENS_END = ')' TEMPLATE_START = '<' TEMPLATE_END = '>' OPER...
#!/usr/bin/env/python # coding: utf-8 ''' utilities to write an exposure geo-data model into openquake-compliant nrml (xml) format. ''' import argparse import sys import pandas as pd import os import csv import json from lxml import etree #used by the nrml NAMESPACE = 'http://openquake.org/xmlns/nrml/0.5' GML_NA...
################################################################################ # BSD LICENSE # # Copyright(c) 2019-2021 Intel Corporation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # *...
#! /usr/bin/python3 import os import io import subprocess as sp import argparse import dropbox import datetime from Crypto.Cipher import DES import base64 import requests from google.cloud import logging from apiclient.discovery import build MOUNT_DIR = '/gcs_mount' DEFAULT_TIMEOUT = 60 DEFAULT_CHUNK_SIZE = 150*1024*...
import itertools from functools import partial import numpy as np import matplotlib.pyplot as plt import scipy.stats # --- Preliminaries --- # - Partitioning techniques - class BestSolutionHolder: """ Keeps in memory the best solution of a partitioning technique, is used in the function below. ...
import numpy as np import matplotlib import matplotlib.pyplot as plt from eagle_mpc.utils.tools import wayPointListToStateArray matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' matplotlib.rcParams['font.size'] = 18 # matplotlib.rc('text', usetex=True) colors = [ ...
from firedrake import * from fireshape import PdeConstraint from slepc4py import SLEPc from firedrake.petsc import PETSc import numpy as np from pyadjoint.tape import no_annotations # Load file to load initial guesses import sys sys.path.append('../utils') from vtktools import vtu RB = __import__("rayleigh-benard") ...
import os import pickle import gzip import multiprocessing from collections import Counter, defaultdict import numpy as np def _add_extra_symbols(vocab_list): vocab_list.insert(0, '<PAD>') vocab_list.append('<GO>') vocab_list.append('<EOS>') vocab_list.append('<UNK>') def make_pointers(amr, text, ...
# # Copyright(c) 2019-2020 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # import base64 import math import textwrap from datetime import datetime from aenum import IntFlag, Enum from core.test_run import TestRun from test_tools.dd import Dd from test_utils.size import Size, Unit class Permissio...
import sys import socket import psutil import subprocess import multiprocessing import threading import time import os import signal import traceback from robolearn.old_envs.gazebo_ros_env_interface import GazeboROSEnvInterface init_roscore_port = 11312 init_gzserver_port = 11347 class RosGazebo(multiprocessing.Pro...
import re from typing import Optional, Dict, List, Union import functools def select_most_frequent_shingles(matches: List[str], db: Dict[str, int], min_count_split: int, threshold: float): """Select the most freq...
#! /usr/bin python3 #ๅˆ›ๅปบๆ•ฐๆฎๅบ“็š„ไปฃ็ ๏ผš """ CREATE DATABASE BaiduResult; USE BaiduResult; CREATE TABLE KeyWords (KeywordID int PRIMARY KEY AUTO_INCREMENT, Keyword varchar(50) NOT NULL , Word varchar(50) NOT NULL )DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE KeywordsLinks (LinkID int PRIMARY KEY AUTO_INCR...
from collections import OrderedDict import torch from torch import nn import torch.nn.functional as F from torchvision.ops import misc as misc_nn_ops from torchvision.ops import MultiScaleRoIAlign from .generalized_rcnn import GeneralizedRCNN from .rpn import AnchorGenerator, RegionProposalNetwork from .roi_heads im...
import os import cv2 def is_this_existing_directory(path_dir): #return os.path.isdir(path_dir) #print('os.path.expanduser(path_dir) : ', os.path.expanduser(path_dir)) return os.path.isdir(os.path.expanduser(path_dir)) def is_video_file(fn): ext = (".3g2", ".3gp", ".asf", ".asx", ".avi", ".flv", "....
E = np.arange(5, 10000, 10) spe = build_spectra(E) sign = dict() for el in mueller.a: sign[el] = spe[el].sum() def signal(det_lat, det_lon, det_depth, rea_lat, rea_lon, P, lf, fuel): En = P * 1e6 * tau * 6.241509e12 # MeV distance = proj.dist([proj.earth_radius - det_depth, det_lon, det_lat], [proj.earth...
#!/usr/bin/env python ''' ueg_fci ======= Full Configuration Interaction (FCI) method for the uniform electron gas. This is a particularly simple implementation: little attempt is made to conserve memory or CPU time. Nevertheless, it is useful for small test calculations, in particular for investigating ideas about ...
from OpenPNM.Utilities import misc import scipy as _sp import numpy as _np import os as _os import pickle as _pickle from xml.etree import ElementTree as _ET class VTK(): r""" Class for writing a Vtp file to be read by ParaView """ _TEMPLATE = ''' <?xml version="1.0" ?> <VTKFile byte_order="...
#!/usr/bin/env python3 # MQTT Minecraft server feeder # Feeds Minecraft server via RCON with commands received via MQTT # requirements # pip3 install paho-mqtt # pip3 install mcrcon # pip3 install python-dotenv import paho.mqtt.client as mqtt from time import time, sleep import signal import socket import sys from m...
# -*- coding: utf-8 -*- """ Created on Mon Oct 15 11:16:21 2018 @author: ut """ import matplotlib as mpl mpl.use('Agg') mpl.rcParams['figure.dpi'] = 300 import math import pandas as pd import matplotlib.pyplot as plt import numpy as np plt.style.use('ggplot') import matplotlib.patches as mpatches import os colors = ['...
#!/usr/bin/python3 from getpass import getpass import importlib import json import os import sys import traceback from lib.components import alert from lib.components.eth import Rpc, web3, wei from lib.components import contract from lib.components.account import Accounts, LocalAccount from lib.components import tran...
#!/usr/bin/env python """ Sniff out DOI from newline delimited JSON (from SOLR). Workaround the fact, that there is currently no explicit DOI field in the index data. Example usage: $ zstdcat -T0 ma.json.zst | parallel --pipe -j 8 --block 10M 'python doisniffer.py -t' 0-011506326 fullrecord:marc 10.73/09...
""" Star generative model Equatorial location: u_s = [ra, dec] ~ Unif[0, 1] Reference band flux: r_s | star ~ Gamma(a_red_star, b_red_star) Colors: c_sb | star = log(brightness_b) - log(brightness_b+1) e.g. for SDSS ugriz: c_s = c_ug, c_gr, c_ri, c_iz Image-specific d...
from __future__ import annotations import numpy as np import pandas as pd import torch from torch.nn import Module, Embedding, Linear, RNNCell, CrossEntropyLoss from torch.nn.functional import softmax, relu, dropout from torch.optim import Adam from nlp_pytorch.data.base_dataset import SplitDataset from nlp_pytorch.d...
import json import global_settings as gs from collections import defaultdict def query_bigquery(query): import boto3 import google.auth from google.cloud import bigquery """ Runs a query in Google BigQuery and returns the result as a list of dicts (each line is an element in the list, and each ...
# Copyright 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """ Common infrastructure fo...
#!/usr/bin/python # -*- coding: utf-8 -*- from collections import namedtuple import numpy as np import time Item = namedtuple("Item", ['index', 'value', 'weight']) # we want to loop through all items class dfs: def __init__(self, file_location): self.iterations = 0 self.items, self.item_coun...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .get_resource_path import resource_path from PyQt5 import QtWidgets, QtCore from PyQt5.QtCore import Qt, pyqtSignal, QPoint from PyQt5.QtWidgets import ( QMainWindow, QListWidget, QLabel, QDesktopWidget, QSizePolicy, ) from PyQt5.QtGui import QPain...
# (c) FFRI Security, Inc., 2020 / <NAME>: FFRI Security, Inc. import sys from dataclasses import dataclass from typing import List, Optional, Tuple import r2pipe from keystone import KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN, Ks from r2pyapi import R2Writer from .utils import hex_as_string, u32_to_u8_array from .xta_cach...
"""PopPage is a utility for generating file/directory output from Jinja2 templates. Usage: poppage INPATH [runargs] poppage make [options] [(--string KEY VAL) | (--file KEY PATH)]... poppage check [options] poppage run [options] [(--string KEY VAL) | (--file KEY PATH)]... poppage debug [options] [(...
"""Functions to calculate three-point correlations and bispectrum. """ import numpy as np import pandas as pd from scipy.fftpack import fft, ifft2, fftshift from scipy.linalg import hankel try: from progress import getLogger except ImportError: from logging import getLogger from .helpers import is_number_like...
import numpy as np import pickle as pkl import json from . import units def read_xyz(filename, unit_conversion=units.ANGSTROM_TO_AU): """ Read xyz file of atomic coordinates. Args: filename: xyz file to read coordinates from. """ X = [] symbols = [] with open(filename, 'r') as fin...
#!/usr/bin/env python3 import argparse import collections import gym import gzip import matplotlib.pyplot as plot import numpy as np import os import random import signal import sys import torch as t import tqdm from torch.multiprocessing import Process, Pipe sys.path.append(sys.path[0] + "/..") import common ENV_NA...
import numpy as np import numerical.numpyext.linalg as ntla import numerical.numpyext as npx import numerical.numpyext.dimreduction as dr import theano import ml.gp.vcgpdm.equations as vceq import ml.gp.equations as gpeq class PartData(object): def __init__(self, Y, sequences_ind...
"""Generate tables for operation xi on the rep 196884x of the monster Operators xi and xi**2 (with xi**3 == 1) operate on unit vectors with tags B, C, T, X as defined in mm_aux.py. We divide the 759 octads occuring as indices for tag T into three groups: TG: octad 0 ... 15, 15 grey even octads T0: octad 1...
# -*- coding: utf-8 -*- import logging from grassfire.primitives import SkeletonNode, KineticVertex from grassfire.collapse import compute_collapse_time, \ compute_new_edge_collapse_event from grassfire.calc import near_zero, is_close from grassfire.vectorops import mul, add, bisector, dist from grassfire.inout i...
## Generate a full season's worth of batting Marcel projections from past years' stats from createTuple import createTuple ## gist: 778481 from writeMatrixCSV import writeMatrixCSV ## gist: 778484 def makeBatTable(r): for stat in ['AB', 'H', 'D', 'T', 'HR', 'SO', 'BB', 'SF', 'HP', 'CI']: if stat in r: p...
import asyncio from enum import Enum from sspq import * from argparse import ArgumentParser, ArgumentTypeError class OrderedEnum(Enum): def __ge__(self, other): if self.__class__ is other.__class__: return self.value >= other.value return NotImplemented def __gt__(self, other): ...
import taichi as ti ti.init(arch=ti.gpu) n_particles = 8192 n_grid = 128 dx = 1 / n_grid dt = 2e-4 p_rho = 1 p_vol = (dx * 0.5)**2 p_mass = p_vol * p_rho gravity = 9.8 bound = 3 E = 400 x = ti.Vector.field(2, float, n_particles) v = ti.Vector.field(2, float, n_particles) C = ti.Matrix.field(2, 2, float, n_particles...
import logging import os import urllib.parse from typing import Optional from fastapi import Depends, FastAPI, HTTPException, Path, Request, Response from fastapi.middleware.wsgi import WSGIMiddleware from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from flask import Flask...
# -*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms of the MIT License. from math import ceil from typing import Optional, Union, List, Dict from pymatgen.core import Composition from pymatgen.io.vasp.sets import Potcar from vise.analyzer.band_edge_properties import is_band_gap from vise.defau...
### IMPORTS ### from enum import Enum from pdb import set_trace from typing import ( AnyStr, Any ) from warnings import filterwarnings from easyyaml import load from yaml import YAMLLoadWarning from lang.util import cd_back from sys import exit as exit_ ### IMPORTS ...
import argparse from typing import Union, Tuple, List, Dict, Any import easydict import torch from torch import nn, Tensor from torchvision.ops import batched_nms from utils import box_ops from utils.model import adapt_device from . import NestedTensor from .detr import DETR, build_detr from .ds import ne...
# Copyright 2021 Research Institute of Systems Planning, 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 applica...
import discord import random import requests import datetime def recolor(str): c_str = f"```md\n" \ f"{str}\n" \ f"```" return c_str def average(list): return round(sum(list)/len(list),2) def log(author,message): date_time = datetime.datetime.now() print(f"{author} {mes...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import print_function from PIL import Image import torch import numpy as np import os.path import sys import ...
# -*- coding: utf-8 -*- """ /dms/folder/utils.py .. enthaelt Hilfefunktionen fuer Ordner Django content Management System <NAME> <EMAIL> Die Programme des dms-Systems koennen frei genutzt und den spezifischen Beduerfnissen entsprechend angepasst werden. 0.01 13.01.2007 Beginn der Dokumentation 0.02 22.0...
# Import packages. import cvxpy as cp import numpy as np import random from collections import defaultdict class AssociationGraph: def __init__(self): self.layer_sizes = None # random experiment RANDOM_SIZE = True if RANDOM_SIZE: size = random.randint(2, 10) ...
from datetime import datetime, timedelta import aiohttp import asyncio from typing import Union from .regions import APIRegion class API(): """This is our core API class with methods for interacting with Battle.net's various APIs :param client_id: A Battle.net Project Client ID - Generated at https://develop....
# -*- encoding:utf-8 -*- """ umpๅŸบ็ก€ๆจกๅ— """ from __future__ import division from __future__ import print_function from __future__ import absolute_import import functools import weakref from abc import ABCMeta, abstractmethod import numpy as np import sklearn.preprocessing as preprocessing from ..UtilBu import ABuF...
import numpy as np import pandas as pd import ipywidgets as widgets from ipywidgets import GridspecLayout, Layout from IPython.display import display from techminer.core.filter_records import filter_records ## ## ## Term extraction and count ## ## def _extract_terms(x, column): x = x.copy() x[column] = x[c...
import sys import pygame from operator import sub from matplotlib.pyplot import text import pandas as pd import random import numpy as np import math import color as c import axis as ax import palletts as p import graph_props as m def round_dig(num, base=5, dig=1): num = float(num) num = num / (math.pow(base,...
import datetime import json import time import rospy as ros from rospy_message_converter import message_converter from std_msgs.msg import String from std_srvs.srv import * from tigrillo_io.srv import Calibration, CalibrationResponse, Frequency, FrequencyResponse from tigrillo_io.msg import Sensors, Motors, Imu impo...
#PyjsBitset - Python-to-JavaScript BitSet Module #Copyright (c) 2013 <NAME> #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,...
import os from tqdm import tqdm import torch from torch import nn from torch.autograd import Variable from torch.nn import functional as F from .utils import Plotter def weights_init(m): """ Custom weights initialization as suggested in DCGAN article :param m: module :return: """ if type(m) in...
""" Create Lumerical Process File (.lbr) """ # Set up path to modules. PDK-Generator/python needs to be in sys.path import sys, os proj_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) if proj_path not in sys.path: sys.path.append(proj_path) from common.lumerical_lumapi import lumapi from commo...
"""Identify structural variants using association testing with WHAM. https://github.com/jewmanchue/wham """ import csv import os import subprocess import sys import numpy as np import toolz as tz try: import vcf except ImportError: vcf = None from bcbio import utils from bcbio.distributed.transaction import ...
#!env python3 """ Copyright 2021 <NAME>, <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 w...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2021 by <NAME>. All rights reserved. This file is part # of the Robot Operating System project, released under the MIT License. Please # see the LICENSE file included as part of this package. # # author: <NAME> # created: 2020-03-16 # modified: 2020-0...
from scipy.optimize import Bounds, LinearConstraint, minimize, minimize_scalar,fmin_powell,fmin,basinhopping from math import pi import cantera as ct import numpy as np import pickle from keras.layers import Input, Dense, Activation, concatenate from keras.models import Model from keras import losses, metrics from ke...
from lan.lan_ast import * import copy class AddToId(NodeVisitor): """ Finds the Id and replaces it with a binop that adds another variable to the id. """ def __init__(self, id, variable): self.id = id self.variable = variable def changeIdNode(self, node): if isinstance(no...
from __future__ import print_function from builtins import input import lib.wicked as WC import lib.database as DB import lib.openhub as OH import lib.copyright as CP import lib.source as SR #import lib.github as GH import lib.unique as UN import lib.pip as PP import os # noinspection PyInterpreter,PyInterpreter def ...
from tkinter import * from tkinter import messagebox import sqlite3 from PIL import ImageTk, Image login = Tk() login.title("Login") login.geometry("500x300") def quit_me(): login.quit() login.destroy() # Regresa la imagen por que el recolector de basura de python la elimina. def mostrarImagen(): glo...
"""This is where the cool functions go that help out stuff. They aren't directly attached to an element. Consequently, you need to use type annotations here. """ import ast import textwrap import types from typing import Any, List, Union import sympy from vyxal import context, lexer from vyxal.LazyList import * NU...
import sys import torch.nn as nn import torch import torch.optim as optim import argparse from module.data_module import preprocessor, analyser, feature_engineer, concat_dataset from sklearn.model_selection import train_test_split import pandas as pd import time from model import MainModel import numpy as np from tenso...
# -*- coding: utf-8 -*- """Python wrapper for timsdata.dll for reading tsf""" import numpy as np import sqlite3 import os, sys from ctypes import * if sys.platform[:5] == "win32": libname = "timsdata.dll" elif sys.platform[:5] == "linux": libname = "libtimsdata.so" else: raise Exception("Unsupported platf...
import pandas as pd import time import logging import numpy as np import torch import torch.nn as nn from torch.utils.data import TensorDataset, DataLoader from transformers import XLMRobertaConfig, XLMRobertaModel, XLMRobertaTokenizer, AdamW, get_cosine_schedule_with_warmup from utils import set_seed class MMRegress...
""" Copyright 2021 Universitat Politรจcnica de Catalunya 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 applicab...
# -*- coding: utf-8 -*- import pytest import concierge.core.exceptions as exceptions import concierge.core.lexer as lexer def make_token(indent_lvl=0): token_name = "a{0}".format(0) return lexer.Token(indent_lvl, token_name, [token_name], token_name, 0) @pytest.mark.parametrize( "input_, output_", (...
import inspect import types from . import _main as main from . import _writer as writer from ._manager import LogManager, LogSimpleManager from . import settings def loggable( log_addr='*', *, log_args=True, log_results=True, log_enter=True, log_exit=True, log_path=True, short=None, ...
import math from dataclasses import dataclass from math import floor, log10 EMOJI_SCALE = [ # negative (-50, '๐Ÿ’ฅ'), (-35, '๐Ÿ‘บ'), (-25, '๐Ÿฅต'), (-20, '๐Ÿ˜ฑ'), (-15, '๐Ÿ˜จ'), (-10, '๐Ÿ˜ฐ'), (-5, '๐Ÿ˜ข'), (-3, '๐Ÿ˜ฅ'), (-2, '๐Ÿ˜”'), (-1, '๐Ÿ˜‘'), (0, '๐Ÿ˜•'), # positive (1, '๐Ÿ˜'), (2, '๐Ÿ˜„'), (3, '๐Ÿ˜€'), (5, '๐Ÿค—'), (10,...
import argparse import os from bisect import bisect_left from random import randint from itertools import repeat from itertools import accumulate from math import sqrt import json parser = argparse.ArgumentParser() parser.add_argument('models', nargs='+', action='store', help='A list of model filenames.') parser.add_a...
""" This module provides functionality for resolving references within an instance of `oapi.oas.model.OpenAPI`. For example, the following will replace all references in the Open API document `open_api_document` with the objects targeted by the `ref` property of the reference: ```python from urllib.request import url...
# -*- coding: utf-8 -*- ''' StarGAN_v2_paddle.core.util @author: RyanHuang @github: DrRyanHuang @updateTime: 2020.8.15 @notice: GPL v3 ''' import os import json import math # import cv2 import numpy as np import paddle.fluid as fluid from paddle.fluid.dygraph.nn import Linear, Conv2D from paddle.fluid.dygraph import ...
#!/usr/bin/env python import math import rospy import cv2 from sensor_msgs.msg import Image from geometry_msgs.msg import Point from std_srvs.srv import Empty, EmptyResponse from cv_bridge import CvBridge, CvBridgeError import numpy as np # Define range of color in HSV lower_white = np.array([0, 0, ...
from datetime import date import factory from factory import fuzzy from dataactcore.models import domainModels class SF133Factory(factory.Factory): class Meta: model = domainModels.SF133 sf133_id = None agency_identifier = fuzzy.FuzzyText() allocation_transfer_agency = fuzzy.FuzzyText() ...
#!/usr/bin/env python2 """ WSI_IMPORT - uses OpenSlide library to import scanned whole-slide images into a common representation suitable for image analysis. This representation stores several fields of view (scales) and their division into small tiles in a hierarchy of folders. .../original image name/ ...
from functools import wraps, partial from typing import TypeVar import torch import numpy as np import networkx as nx TensorLike = TypeVar("TensorLike", np.ndarray, torch.Tensor) def random_seed_consistent_rng(seed=None) -> np.random.RandomState: if seed is not None: torch.manual_seed(seed=seed) ...
import discord from discord.ext import commands, tasks from external_cons import the_database from extra import utils import os from typing import List, Union, Dict import collections server_id: int = int(os.getenv('SERVER_ID')) game_text_channel_id: int = int(os.getenv('GAME_TEXT_CHANNEL_ID')) class ScheduledEvent...
import numpy as np from scipy.ndimage import uniform_filter, gaussian_filter from numpy.lib.arraypad import _as_pairs _integer_types = (np.byte, np.ubyte, # 8 bits np.short, np.ushort, # 16 bits np.intc, np.uintc, # 16 or 32 or 64 bits np.int_, np.ui...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.cnn import (build_activation_layer, build_conv_layer, build_norm_layer, constant_init, kaiming_init) from mmcv.runner import load_checkpoint from mmcv.utils.parrots_wrapper import _B...
from flask import Flask, jsonify, send_from_directory from flask_restful import reqparse from flask.ext.cors import CORS import numpy as np # Extract data from avro and csv files from pyspark.sql.functions import size, udf, unix_timestamp, max, min, rowNumber from pyspark.sql.types import IntegerType, LongType, FloatTy...
import os import sys import struct import argparse import numpy as np import pycuda.autoinit import pycuda.driver as cuda import tensorrt as trt BATCH_SIZE = 1 INPUT_H = 224 INPUT_W = 224 OUTPUT_SIZE = 1000 INPUT_BLOB_NAME = "data" OUTPUT_BLOB_NAME = "prob" EPS = 1e-5 WEIGHT_PATH = "./densenet121.wts" ENGINE_PATH =...
""" Modification of https://github.com/stanfordnlp/treelstm/blob/master/scripts/download.py Downloads the following: - Celeb-A dataset - LSUN dataset - MNIST dataset - Oxford Flowers (17) dataset - Oxford Flowers (17) simplified dataset """ from __future__ import print_function import os import sys import gzip import...
# -*- coding: utf-8 -*- """ data_generation.py - The data generation module of the project ============================================================== This module generates the requested database for each experiment, using the method 'fetch_data'. """ import numpy as np import pandas as pd import os import nibabel ...
#!/usr/bin/env python # # Ray parameter server benchmark # # python ray_ps.py --aws --num-ps=1 --num-workers=1 --size-mb=100 --iters=100 # # 1 worker, 1 ps # min: 61.61, median: 63.77, mean: 69.20 # # 1 worker, 2 ps # python ray_ps.py --aws --num-ps=2 --num-workers=1 --size-mb=100 --iters=100 # min: 49.45...
# coding=utf-8 """Face Detection and Recognition""" # MIT License # # Copyright (c) 2017 <NAME> # # This is the work of <NAME> and shanren7 remodelled into a # high level container. It's an attempt to simplify the use of such # technology and provide an easy to use facial recognition package. # # https://github.com/dav...
# pylint: disable=invalid-name import re import socket import time import pytest import requests from requests.auth import HTTPDigestAuth @pytest.mark.parametrize('extra_args', [[], ['--no-color']]) def test_output(turq_instance, extra_args): turq_instance.extra_args = extra_args with turq_instance: ...
#!/bin/env python3 import os import sys import mmap import time import struct from db_helper import DbHelper from data_point import DataPoint def get_atom_info(data): try: atom_size, atom_type = struct.unpack(">I4s", data) except struct.error: return -1, "(Unpack Error)" except Exception as e: print("Error!...
## THUCNews ๅŽŸๅง‹ๆ•ฐๆฎ้›† import sys sys.path.append("./") sys.path.append("./bert_seq2seq/") import torch from tqdm import tqdm import torch.nn as nn from torch.optim import Adam import numpy as np import os import json import time import glob import bert_seq2seq from torch.utils.data import Dataset, DataLoa...
# encoding: utf-8 import logging import subprocess from pathlib import Path import requests logger = logging.getLogger(__name__) stream_handler = logging.StreamHandler() logger.addHandler(stream_handler) def parse_tags(line, vods_clips): tags = line.split(',') for tag in tags: tag = tag.strip() ...
''' This script triggers re-running the pipeline after QA, and triggers the QA completion sequence. Run as python main.py from command line. REQUIRE python>=3.7 for asyncio. ''' import asyncio import time from pathlib import Path from autodataingest.gsheet_tracker.gsheet_functions import (find_rerun_status_tracks...
import numpy as np from numpy import linalg as la from matrixmath import randn from ltimultgen import gen_system_mult from policygradient import PolicyGradientOptions, run_policy_gradient from ltimult import dlyap_obj from matplotlib import pyplot as plt from time import time,sleep import os from utility import cre...
# ############################################################################## # This file is part of Interdiode # # # # Copyright (C) 2020 <NAME> <<EMAIL>> # # All Rights Reserved ...
from django import forms from .models import File, Upload, Zeta_Config, Download, Detail from .fields import * from .widgets import * from .common import GENRE_LIST, YEAR, any_plus from .constants import LICENSE_CHOICES, LICENSE_SOURCE_CHOICES, LANGUAGE_CHOICES, DETAIL_REMOVED class ZGameForm(forms.ModelForm): zf...
#!/usr/bin/env python3 import random from datetime import datetime, timedelta import pytz import astral import xml.etree.ElementTree as ET import requests ENGINES = ["๐Ÿš‚"] CARS = ["๐Ÿšƒ","๐Ÿš‹"] SUN = "โ˜€" MOONS = ["๐ŸŒ‘","๐ŸŒ’","๐ŸŒ”","๐ŸŒ•","๐ŸŒ–","๐ŸŒ˜"] DESERT_TILES = ["๐ŸŒต","๐ŸŒต","๐ŸŒด","๐ŸŒด","๐Ÿช","๐Ÿข","๐ŸŽ"] FOREST_TILES = ["๐ŸŒฒ","๐ŸŒฒ...
# -*- coding: utf-8 -*- """ Created on Sun Oct 4 @author: <NAME> """ import random import numpy as np import seaborn as sns import matplotlib.pyplot as plt class FrozenLake: """Environment of frozen lake. Attributes: map_idx: 0 for 4x4 map, 1 for 10x10 map. """ ...
import random from torch.distributions import Categorical from models.GAN.generator_base import GeneratorBase from utils.data_prep import * from utils.logger import * import time class BaseSendObj: def __init__(self, tag): self.tag = tag class NewAction(BaseSendObj): def __init__(self, tag, action...
# encoding = utf-8 import os import sys import time import datetime libpath = os.path.dirname(os.path.abspath(__file__)) sys.path[:0] = [os.path.join(libpath, 'lib')] import common import pan.afapi import json from kvstore import KvStoreHandler ''' IMPORTANT Edit only the validate_input and collect_events ...
#!/usr/bin/env python3 # you schould not need to do anything in here import sys #needed for executing this sript in diverent modes import subprocess as sp #needed to run mcstas import argparse import os from importlib import import_module from mcpw.mcstas_wrapper import run_mcstas...