text
stringlengths
3.07k
22.1k
""" Script file to train the model """ import os import numpy as np import argparse from tqdm import tqdm import torch.optim as optim from utils.logging.tf_logger import Logger from torch.optim.lr_scheduler import ReduceLROnPlateau from model_archs.models import CombinedModelMaskRCNN from utils.text_utils import get_t...
#!/usr/bin/python3 from queue import Queue ############## # Load input # ############## class Character: def __init__(self, idx, x, y, kind, elf_attack_power, grid): self.idx = idx self.x = x self.y = y self.kind = kind # Reference to the rest of the game self.g...
# coding:utf-8 import os from typing import List, Union from pathlib import Path import numpy as np import torch from PIL import Image from torch import Tensor, nn from torch.nn import functional as F from torch.nn import init from utils.box_utils import draw, rescale_bbox from utils.augmentation_utils import ToTensor...
#!/usr/bin/python3 # -*- encoding: utf-8 -*- """ BLEHeartRateLogger ~~~~~~~~~~~~~~~~~~~ A tool to log your heart rate using a Bluetooth low-energy (BLE) heart rate monitor (HRM). The tool uses system commands (hcitool and gatttool) to connect to the BLE HRM and parses the output of the tools. Data ...
from datetime import datetime, timedelta import numpy as np import time from GpsDataAnalyzer import utils MEAN_DISTANCE_THRESHOLD = 100 def find_lineup(set1, set2): """ Optimized algorithm to find the approximate time offset between two GPS data sets. This algorithm assigns the data set that starts late...
import pickle import time import os import json import urllib from PIL import Image import numpy as np import fasteners import torch import torch.nn as nn import torchvision.models as models import torchvision.transforms as transforms import flickrapi class OpenImageClassifier(): def __init__(self, class_id, i...
import os from typing import Callable, Tuple, List, Optional, Dict, Any import xml.etree.ElementTree as ET from PIL.Image import Image import torch from torchvision.datasets.utils import verify_str_arg from .detection_dataset import DetectionDataset from cv_lib.utils import log_utils VOC_MEAN = [0.485...
# Project for Applied Databases # Author: <NAME> import pymysql import datetime import pymongo import keyboard conn = None #create a variable for the connection to the MySQL database set to None for default # Connection to the datbase def connect():# makes a connection to a database global conn # make the vari...
import tracemalloc def knapsack_space_optimized_dp(value_set, weight_set, total_weight): """Space optimized version of `knapsack_dp`. Here we conciously know that we only need two rows to compute the True/False""" # Creating only two rows. dp_table = [[0 for _ in range(total_weight + 1)] for _ in ran...
"""Command definitions.""" from __future__ import absolute_import, division, print_function from abc import ABCMeta, abstractmethod from builtins import ( # noqa: F401 # pylint: disable=redefined-builtin,unused-import bytes, dict, int, range, str, super, ) import json import os import re imp...
#!/usr/bin/python # -*- coding: UTF-8 -*- import os import sys import json import sqlite3 import subprocess # SQLite3 aggregate 类 class Concatenate(): def __init__(self): self.itemList = [] def step(self, value): # print 'step(%r)' % value self.itemList.append(value) def finaliz...
# -*- coding: utf-8 -*- import numpy as np import cv2 from pathlib import Path from moviepy.editor import VideoFileClip from IPython.display import HTML def calibrateCamera(nx,ny,imgPath): objPts = [] #3D points in object plane imgPts = [] #2D points in image plane objP = np.zeros((6*9,...
"""Easy install Tests """ from __future__ import absolute_import import sys import os import shutil import tempfile import site import contextlib import tarfile import logging import itertools import pytest import mock from setuptools import sandbox from setuptools.compat import StringIO, BytesIO, urlparse from setu...
import datetime import time import re from email.utils import formatdate # rfc822 import markdown from wmk_utils import slugify __all__ = [ 'date_to_iso', 'date_to_rfc822', 'date', 'date_short', 'date_short_us', 'date_long', 'date_long_us', 'slugify', 'markdownify', 'truncat...
import serial #Talks to the serial port on the ATMEGA Chip import serial.tools.list_ports #Used to real all possible COM Ports import time #Used to delay reading from serial to avoid overflow errors. import re #Used for searching the list of all current processes import psutil #Used to gather all running tasks and thei...
# encoding: utf-8 """ rdfsSubject.py rdfsSubject is similar to rdfsSubject but includes more processing and *magic* based on an `RDF Schema`__ __ ::http://www.w3.org/TR/rdf-schema/ Created by <NAME> on 2008-05-14. Copyright (c) 2008 Openvest. All rights reserved. """ import re import logging from weakref import Weak...
from math import comb import numpy as np from functools import lru_cache as cache, cached_property from collections import namedtuple from typing import Union, Iterable from rfidam.protocol.responses import TagFrame from rfidam.protocol.protocol import Protocol from rfidam.baskets import BasketsOccupancyProblem @ca...
############################################################################# # Copyright 2019 <NAME> # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not ...
import base64 import json import datetime import os import zipfile import boto3 # DEFINE WHITELIST & RULESET LOCATION # Define the Bucket prefix where the ruleset.zip and whitelist are posted in the Compliance Account. BUCKET_PREFIX = 'compliance-engine-codebuild-source' ORIGINAL_ZIP_RULES = 'ruleset.zip' ORIGINAL_ZIP...
#!/usr/bin/env python3 from collections import namedtuple from datetime import datetime, timedelta from math import ceil from dom import Document from pysvgi import Circle, Line, Svg, Text class DatetimeUtil: """Adds some additional methods to the standard datetime class""" # tuple as generated by datetime...
# # Author: <NAME> # Date: 2016 # import os from isceobj import createDemImage from iscesys.DataManager import createManager def createDem(usnwe, info, insar, demStitcher, useHighResOnly=False, useZeroTiles=False): """ Create a dem object given a user specified snwe lat, lon bounding box (usnwe), a frame ...
import json, re, logging, traceback, jieba, zlib, binascii, math import numpy as np from utils import clean_query, is_name, normal_qeury, n_gram_words, is_alphabet_string, SPECIAL_WORDS from seg_utils import Tokenizer t = Tokenizer() def get_info(origi_dict, key, *args, flag=False): res = [] try: ...
import ROOT import os import json import PlotUtils import config import inspect MACRO_ROOT = os.path.dirname(os.path.abspath(__file__))+"/../" POT_FILE = MACRO_ROOT+"configs/POT.json" #SCALE_FILE = MACRO_ROOT+"background_fit/scale.json" DEFAULT_TREE="MasterAnaDev" def loadJSON(path): with open(path,"r") as pl: ...
import numpy as np import torch from torch.utils.data import Dataset import matplotlib.pyplot as plt from tqdm import trange import os import cv2 from pycocotools.coco import COCO from pycocotools import mask from PIL import Image, ImageFile # ImageFile.LOAD_TRUNCATED_IMAGES = True import cv2 from torch.uti...
import argparse import glob import json import os import time from multiprocessing import Pool from pathlib import Path import ftfy import numpy as np import tensorflow as tf from lm_dataformat import Reader from tokenizers import Tokenizer from transformers import GPT2Tokenizer, GPT2TokenizerFast from tqdm import tqd...
# import argparse import csv # import datetime # import difflib # import os # import pprint import re import time # import timeit # import warnings from time import sleep # import matplotlib.pyplot as plt # import matplotlib.ticker as ticker import numpy as np import pandas as pd import requests from bs4 import Beauti...
from __future__ import annotations import sys from typing import Tuple, Union, Iterable, Final, final, Optional, Dict, Annotated, List from abc import abstractmethod, ABC from pkg_resources import resource_filename vec3 = Union[str, Iterable] vec4 = Union[str, Iterable] def to_glsl_vec(vec, n: int) -> str: if n...
import time import random import itertools # import gc import os import sys import datetime import numpy as np import yaml import pickle from operator import itemgetter from optparse import OptionParser from sklearn.model_selection import KFold from sklearn.metrics import roc_curve, auc, average_precision_score sys....
from exception.ConvertException import ConvertException import hashlib import time from service import File import os from OCC.Extend.DataExchange import read_iges_file, read_step_file, read_stl_file, write_stl_file from service.stl2gltf import stl_to_gltf from service.GltfPipeline import gltf_pipeline, obj2gltf, fbx2g...
#!/usr/bin/env python import time from math import radians from service_router import * from locomotion import * from demonstration import * class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() ...
"""This module holds classes related to graphs. This module contains the `Vertex`, `VertexAttributeError`, `Graph`, and `GraphVertexError` classes. `Vertex` represents a graph vertex. `VertexAttributeError` is an error raised by `Vertex`. `Graph` represents a directed graph. `GraphVertexError` is an error raised by `G...
# encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> """ # based on: # https://github.com/XingangPan/IBN-Net/blob/master/models/imagenet/resnext_ibn_a.py import math import logging import torch.nn as nn import torch.nn.functional as F from torch.nn import init import torch from ...layers import IBN from .build im...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import defaultdict import argparse import cv2 # NOQA (Must import before importing caffe2 due to bug in cv2) import glob import logging import os import...
#!/usr/bin/python # -*- coding: utf-8 -*- """ рассветать COMP женись """ import requests as rq import bs4 import json import random as rd import os from copy import deepcopy from time import sleep import pprint import pymorphy2 as py stress_char = "ре́с"[2] not_found = "@" morph = py.MorphAnalyzer() def normal_form...
import os import cv2 import numpy as np import torch import torchvision import argparse import matplotlib.pyplot as plt import pandas as pd # distributed training import torch.distributed as dist import torch.multiprocessing as mp from torch.nn.parallel import DataParallel from torch.nn.parallel import DistributedDa...
"""Automates Python scripts formatting, linting and Mkdocs documentation.""" import ast import importlib import re from collections import defaultdict from pathlib import Path from typing import Union, get_type_hints def automate_mkdocs_from_docstring( mkdocs_dir: Union[str, Path], mkgendocs_f: str, repo_dir: Pa...
import cvxpy as cvx import numpy as np import matplotlib matplotlib.use('tkagg') from matplotlib import pyplot as plt plt.rc('figure', figsize=[10, 6]) class ControlModel(object): """ Models used to find optimal investment strategies. """ def __init__(self): pass def run(self, data): ...
from discord.ext import commands import discord import traceback import sys class HelpCommand(commands.HelpCommand): def get_base_embed(self): ctx = self.context bot = ctx.bot em = discord.Embed( title=f"You asked for help? Fine. Here you go.", color=discord.Color....
import pandas as pd import numpy as np import math, statistics, functools import matplotlib.pyplot as plt from sklearn.metrics.cluster import adjusted_rand_score def read_csv_input(filename): df = pd.read_csv(filename, header = None).to_numpy() y = df[:, [0]] X = df[:, range(1, df.shape[1])] return X, y def ...
import typing as t from decimal import Decimal from . import exchanges from .data_types import ( CryptoBalance, CryptoData, MarketBuy, MarketBuyStrategy, SupportedExchanges, ) from .user import User from .utils import log def calculate_market_buy_preferences( target_index: t.List[CryptoData],...
"""Test cross-mesh resharding.""" import time import unittest from jax import xla from jax.core import Var from jax._src.abstract_arrays import ShapedArray from jax.interpreters.pxla import (Chunked, NoSharding, Replicated, ShardedAxis, ShardingSpec, spec_to_indices) import jax.numpy...
import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo import copy __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/...
from asdl import const # For const.NO_INTEGER from asdl import py_meta from osh.meta import RUNTIME_TYPE_LOOKUP as TYPE_LOOKUP class part_value_e(object): StringPartValue = 1 ArrayPartValue = 2 class part_value(py_meta.CompoundObj): ASDL_TYPE = TYPE_LOOKUP.ByTypeName('part_value') class StringPartValue(part_v...
from ctypes import Structure, c_uint8, c_uint16, c_int16, c_uint32, c_int32, c_uint64, c_float, c_double, sizeof import io import numpy as np from copy import copy __all__ = ['parse', 'Actor', 'Frame'] class Read: def __init__(self, f): self._f = f def _r(self, t): return t.from_buffer_copy(...
"""X86-32 Processors""" from compilertools.processors import ProcessorBase as _ProcessorBase __all__ = ["Processor", "Cpuid"] class Processor(_ProcessorBase): """x86-32 CPU""" def __init__(self, current_machine=False): _ProcessorBase.__init__(self, current_machine) self._default["os_supports...
import os from keras.models import Model as KerasModel from keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, BatchNormalization, Dropout, Reshape, Concatenate, LeakyReLU from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator from ...common_config import DICT_LABELS...
import math as m def vincenty(lat1_deg,lon1_deg,az_deg,distance): """ Given a starting point on the earth and a bearing/distance, calculate the ending point Inputs: lat1_deg -- Latitude on Earth's Surface (deg) lon1_deg -- Longitude on Earth's Surface (deg) az_deg -- Azimuth (bearing) from pt1 to...
from __future__ import print_function import array import atexit import errno import gc import logging import _multiprocessing import os import pwd import random import signal import socket import struct import sys import threading import time import traceback def preload(): import argparse import base64 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013-2014 DNAnexus, Inc. # # This file is part of dx-toolkit (DNAnexus platform client libraries). # # 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 c...
import curses import os import platform import time from contextlib import contextmanager from _curses import error as CursesError from typing import Any, Callable, Dict, Generator, List, Optional, Type from .context import BoundingRectangle, RenderContext from .component import Component, DeferredInput from .input i...
# coding: utf-8 import os from flask import Flask from flask import redirect from flask import url_for from flask import g from flask import request from flask import send_from_directory from flask import flash from flask import Markup from flask import render_template from werkzeug import Request import leancloud f...
from async_mcrcon.async_mcrcon import MinecraftClient import asyncio import re import json5 import sys import os import base64 import requests import time from shutil import copyfile from PIL import Image, ImageOps from PIL.PngImagePlugin import PngInfo from io import BytesIO async def player_markers(conf): conf ...
# -*- coding: utf-8 -*- # Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved. # Please refer to our terms for more information: # # https://www.sqreen.io/terms.html # """Condition evaluator.""" import operator from collections import deque from functools import wraps from logging import getLogger fr...
import re import subprocess import os.path import csv import json import gc import syllables from datetime import datetime from torch.cuda import empty_cache from datasets import load_dataset ## Some basic utilities for GPU mgmt, saving, etc # plundered from: https://github.com/huggingface/transformers/issues/1742 d...
""" tkSidViewer class - a graphical user interface for SID based on tkinter. # created on 20150421 # first official release 20150801 2017/09/01: add vertical lines on the plot for each monitored station """ import tkinter as tk import tkinter.messagebox as MessageBox import tkinter.filedialog as FileDialog import m...
""" # main training script Reviewed and tested by You-Yi on 07/07/2020. Edition history: Organized and documented by You-Yi on 05/18/2020. Increments upon train_good_corr_3_vals_goodF.py on 09/29/2019 by Rui. Reorganized as baseline deep_F. Authors: <NAME>, <NAME> """ import argparse import yaml imp...
import platform from ctypes import POINTER, c_int, c_ushort, cdll, sizeof from ctypes.wintypes import HANDLE from typing import Iterable from dataclasses import dataclass from enum import IntEnum, Enum from pathlib import Path from .errors import ( ADSampleRateOutOfRange, ADSampleRateRoundToNearest1000, Co...
import os import re import argparse import numpy as np from sklearn.metrics import confusion_matrix from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.neural_network import MLPClassifier import matplotlib.pyplot as plt feature_list = [] feature_dict = {} def confusion(true, pr...
# 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...
""" Sequence preprocessing functionality. Extends sklearn transformers to sequences. """ import numpy as np from sklearn.base import ClassifierMixin, BaseEstimator, TransformerMixin, clone from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.pipeline import make_pipeline from sklearn.prepro...
import tkinter as tk import tkinter.font as tkf from src.utils import * class MainPage(tk.Frame): def __init__(self, master, main_frame): super().__init__(master, bg='white') self.left_page = StatPage(self, main_frame) self.left_page.grid(row=0, column=0, sticky='n') label = tk.L...
import json from django.urls import reverse from django.contrib import messages from django.utils.encoding import force_text from django.contrib.auth import login, logout from django.utils.http import urlsafe_base64_decode from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import Lo...
#!/usr/bin/python # encoding:utf-8 import RPi.GPIO as GPIO import board import adafruit_dht import time import requests import base64 import json import hmac import hashlib import calendar from urllib import parse from enum import Enum, unique from datetime import datetime """ @Author <NAME> @School Coventry Uni...
import findspark findspark.init() from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.sql.functions import udf from pyspark.sql.types import StringType from pyspark.sql import SparkSession, Row from pyspark.sql.types import * from pyspark.ml.linalg import * from pyspark.ml impor...
# app/robo_advisor.py import requests import dotenv import json import datetime import csv import os from dotenv import load_dotenv import plotly.graph_objects as go import operator # LOAD .ENV ---------------------------------------------------------------------- load_dotenv() api_key = os.environ.get('ALPHAVANTA...
import os import shutil import errno from avalon import api, io from avalon.vendor import filelink from reveries.common import str_to_objectid class PublishInstance(object): def __init__(self): pass def publish(self, instance): context = instance.context if not all(result["success...
import sys import os import psutil import argparse import signal import threading from utils import config from utils import listener from utils import http_proxy from gui import main_ui from gui import add_service from gui import delete_service from gui import main_ui as gui from PyQt5 import QtCore, QtGui, QtWidge...
import abc import warnings from functools import update_wrapper import numpy as np from typing import Callable, Any, Tuple, Union from gym import Env _RewardFunctionT = Callable[[Env, np.ndarray, np.ndarray, np.ndarray], float] _RewardFunctionWithArgsT = Callable[[Env, np.ndarray, np.ndarray, np.ndarray, Any], float...
''' ################################################################ # Layers - Modern convolutional layers (deprecated) # @ Modern Deep Network Toolkits for Tensorflow-Keras # <NAME> @ <EMAIL> # Requirements: (Pay attention to version) # python 3.6+ # tensorflow r1.13+ # We store the failed versions of APIs for .c...
import os, tkinter, pypyodbc, tkinter.messagebox import sys, csv, datetime # sys.path.append(r"\\usmasvddeecs\eecs\S&F\Courses\IT305\libraries") import dbUtils as db pypyodbc.lowercase = False tk = tkinter.Tk() displayFrame = tkinter.Frame(tk) displayFrame.pack() cdtDict = {} sections = [] sec = "" debug = 1 # Set ...
import datetime import uuid from django import forms from django.core.exceptions import ValidationError from .models import Category, Grant from contacts.models import AccomplishmentInstrument, Contact instance_id = "10602" class MinGrantForm(forms.ModelForm): """ Defines the minimum viable Grant/proposal ...
import difflib import json import pickle from fuzzywuzzy import fuzz from address_book import AddressBook, Record from notes import NoteRecord from sort_folder import sort_folder_command def main(): print(f"COMMAND LINE INTERFACE\nYour Personal Assistant\n" + "=" * 23) print("If you wont to read ...
#!/usr/bin/env python3 import argparse import base64 import codecs import time import json import broadlink from broadlink.exceptions import ReadError, StorageError TICK = 32.84 TIMEOUT = 5 IR_TOKEN = 0x26 def auto_int(x): return int(x, 0) def to_microseconds(bytes): result = [] # print bytes[0] # 0...
#!/usr/bin/env python3 import glob import re import contextlib import os import platform import sys import shutil import subprocess import tarfile import zipfile from os.path import join, abspath, dirname, exists, basename import click import cryptography.fernet # ZipFile and tarfile have slightly different APIs. Fi...
''' Created on 15 Jan 2013 @author: kreczko - sum up the b-tag multiplicity bins - sum up the different samples ''' #rootpy very slow #from rootpy.io import File from rootpy.logger import logging from ROOT import TFile, gROOT from argparse import ArgumentParser from tools.file_utilities import make_folder_if_not_exi...
import argparse import time import numpy import netket as nk from flowket.utils.jacobian import predictions_jacobian as get_predictions_jacobian from flowket.layers import ToComplex64, ToComplex128, ComplexConv1D from flowket.deepar.layers import PeriodicPadding from flowket.layers.complex.tensorflow_ops import lncosh...
"""Converts Tiny ImageNet data to TFRecords file format. * Reference: TensowFlow example code for converting ImageNet data to TFRecords file format - Link: https://github.com/tensorflow/models/blob/master/research/inception/inception/data/build_imagenet_data.py """ # Imports import numpy as np from scipy.ndimage...
import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import torch.nn.functional as F import numpy as np import copy from collections import namedtuple import random from n_puzzle import N_puzzle class hidden_unit(nn.Module): def __init__(self, in_channels, out_channels...
import numpy as np import pandas as pd from typing import List from dataclasses import dataclass from anml.parameter.parameter import Parameter from anml.parameter.prior import Prior from anml.parameter.processors import process_all from anml.parameter.spline_variable import Spline, SplineLinearConstr from anml.parame...
""" This file contains functions to upgrade transformers """ ################################################################################################################## # Created April 16, 2018 by <NAME> (<EMAIL>) # Copyright (c) 2018 Battelle Memorial Institute. The Government retains a paid-up nonexclusive,...
""" Greenlet BottleNeck profiler. Measures time precisely using "greenlet.settrace" to pause/continue counting time on switch from/to original greenlet. May count wall-clock time too. Also counts step calls and context switches. Usage: gbn_attach() gbn('step1') step1() gbn('step2') step2() w...
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter from torch._jit_internal import weak_module, weak_script_method from ..registry import BACKBONES from torch.nn.modules.batchnorm import _BatchNorm @weak_module class Swish(nn.Module): def __init__(self, tra...
# # (c) Copyright 2015 Hewlett Packard Enterprise Development LP # (c) Copyright 2017-2018 SUSE 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-...
import datetime import googleapiclient.errors import necrobot.exception from necrobot.gsheet import sheetutil, sheetlib from necrobot.speedrun import categories, speedrundb from necrobot.user import userlib from necrobot.botbase.command import Command from necrobot.botbase.commandtype import CommandType from necrobot...
import re def restore_text(text): text = re.sub('=', '', text) text = re.sub(',', '', text) text = ' '.join(text.split()).strip() return text def split_bs_text_by_domain(bs_text, bsdx_text): res_text_list = [] bs_text = bs_text.strip('<sos_b>').strip('<eos_b>').strip() bsdx_text = bsdx_text...
import json import argparse import os import numpy as np import shutil parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default='Yahoo_letor', choices=['Yahoo_letor', 'MSLR_30k_letor']) parser.add_argument('--click_setting', type=str, default='PBM', choices=['PBM', 'UBM', 'BDCM']) parser....
"""Recurrent networks ==================== """ # %% # There are two different approaches to using BackPACK with RNNs. # # 1. :ref:`Custom RNN with BackPACK custom modules`: # Build your RNN with custom modules provided by BackPACK # without overwriting the forward pass. This approach is useful if you want to # ...
# -*- coding: utf-8 -*- import sys import random import time from PIL import Image import argparse import os.path import pickle import subprocess from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from ppadb.client import...
import importlib import os import re import subprocess DEFAULT_ORGANIZATION_NAME = 'tao-cpp' DEFAULT_LOGIN_USERNAME = 'fpelliccioni' DEFAULT_USERNAME = 'tao' DEFAULT_REPOSITORY = 'tao' def branch_to_channel(branch): if branch is None: return "stable" #"staging" if branch == 'dev': return "test...
import numpy as np import scipy.spatial import pygame import tflite_runtime.interpreter as tflite import sys, os class TrussGameAI: def __init__(self, window_size=(900, 900), force=100000): pygame.init() pygame.display.init() pygame.display.set_caption("Truss game AI") self.screen ...
from . import ModelBuilder def inception_v3(input_size=299, num_classes=1000, softmax=False): mb = ModelBuilder("InceptionV3_{}".format(input_size)) input_shape = (1, 3, input_size, input_size) x = mb.set_input_tensor(tensor_shape=input_shape) Conv2d_1a_3x3 = mb.Conv(x, 3, 32, k=3, stride=2) Conv2...
from typing import DefaultDict import numpy as np import torch import argparse import os import math import gym import sys import random import time import json from collections import defaultdict from pathlib import Path # import dmc2gym import copy from tqdm.auto import tqdm from rich import print import utils from...
import numpy as np from striped_c_tools import pairs as make_pairs from QAFilters import Filterable def make_segments(size_array): if len(size_array) == 0: return np.array([], dtype=np.int) s = np.empty((len(size_array), 2), dtype=np.int64) np.cumsum(size_array, out=s[:,1]) # segment ends ...
#! /usr/bin/env python import maple import maple.utils as utils import maple.audio as audio import time import numpy as np import pandas as pd import shutil import sqlite3 import datetime import sounddevice as sd import matplotlib.pyplot as plt from pathlib import Path from scipy.io.wavfile import read as wav_read f...
#!/usr/bin/env python3 -u # !/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import sys from itertools import chain import torch from fairse...
""" Some useful functions """ from __future__ import division import numpy as np # A series of variables and dimension names that Salem will understand valid_names = dict() valid_names['x_dim'] = ['west_east', 'lon', 'longitude', 'longitudes', 'lons', 'xlong', 'xlong_m', 'dimlon', 'x', 'lon_3...
''' RC8000 Save Tapes ----------------- ''' import autoarchaeologist import autoarchaeologist.generic.hexdump as hexdump class Fields(): def __init__(self, src, spec, header=None): self.fields = [] self.fmtd = [] self.spec = spec self.header = header def wrd(r): ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import itertools import pyparsing from mpl_toolkits import mplot3d def linegraph(type, dims, component_names, colors_list): ''' Plot the explained variance across dimensions using the model results @params: ...
#!/usr/bin/python """Regenerate tests for only the files that have changed.""" import argparse import jinja2 import logging import os import shutil import subprocess TOP_LEVEL_EXCLUDES = ["docs", "hack", "kfdef", "stacks", "tests"] # The subdirectory to story the expected manifests in # We use a subdirectory of test...
""" train_xcept.py Train the Xception network to classify HV towers and substations Modified on: 3/24/2020 by <NAME> (<EMAIL>) """ import os from os import path as op from functools import partial from datetime import datetime as dt import pickle import pprint import numpy as np # import tensorflow as tf from tenso...