text
stringlengths
3.07k
22.1k
import sys import torch import numpy as np import matplotlib.pyplot as plt # Prep data & splitting dataset # -------------------------------------------------------- def convert_X_for_resnet(X): X_np = X.numpy() X_np = np.tile(X_np, (1,3,1,1)) return torch.tensor(X_np) def shuffle_batch(batch, labels): ...
import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl import dgl.function as fn class MLPReadout(nn.Module): def __init__(self, input_dim, output_dim, L=2): #L=nb_hidden_layers super().__init__() list_FC_layers = [ nn.Linear( input_dim//2**l , input_dim/...
#!./.env/bin/python import libdigitone as dt import logging import argparse import time import threading # imported for threading in monitor arguement def setup(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--listen', action='store_true', help='Turns on verbose output') parser.add_argu...
import morpholib as morpho import morpholib.anim import morpholib.grid from morpholib.tools.basics import * import math, cmath # DEPRECATED! Use crossout() or crossoutPath() instead. # Returns a layer which when animated makes a colored X cross # out the box you specify. # box = a 4-item list/tuple in the s...
# recebe o nome da pasta e qual funcao deseja # entra na pasta e unzipa o arquivo # passa os dados pelo pre-processamento (ou nao) # passa os dados para o cluster # escreve o resultado # zipa os arquivos import sys import os import pandas as pd import zipfile as zf import pre_processing as pre from clustering import Cl...
import numpy as np import os import multiprocessing from PIL import Image from skimage import io pi = np.pi """ Run this program to perform the reconstruction of a MCRICM stack of images. The stack should contain the different images grouped by color and increasing INA. The simulations should previously done with Mai...
# # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # # HPProcess.py: code for processing hyperparameter settings in cmd line arguments of an app import numpy as np import copy from xtlib import utils from xtlib import constants from xtlib import errors from xtlib import file_utils from xtlib.co...
"""From raw data to evaluated model""" import pickle from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split, cross_val_score from seizurecast.models.Result import Result, Results fro...
# ON AIR sign for YouTube livestreaming # Runs on Airlift Metro M4 with 64x32 RGB Matrix display & shield import time import board import displayio import adafruit_display_text.label from adafruit_display_shapes.rect import Rect from adafruit_display_shapes.polygon import Polygon from adafruit_bitmap_font import bitma...
from django.shortcuts import render, redirect from .models import * from django.db.models import Avg from django.views import generic # class to create form based on models from . import forms from django.http import HttpResponseRedirect, HttpResponse # calculate evaluation avrg # evaluation_types: homework=h , quiz=q...
from __future__ import absolute_import, print_function, unicode_literals import logging import os from collections import OrderedDict from threading import Lock, local import six from babel.core import UnknownLocaleError from django.conf import settings from django.utils.functional import cached_property, lazy from d...
""" This is where the user interface is made using the streamlit package. """ import joblib import numpy as np import pandas as pd import streamlit as st from sklearn.compose import ColumnTransformer from sklearn.preprocessing import StandardScaler, OneHotEncoder st.title('CdSe Quantum Dots Synthesis Project - Coss...
# -*- coding: utf-8 -*- # @Author : <NAME> import numpy as np import matplotlib.pyplot as plt import scipy.io as sio from keras.utils.np_utils import to_categorical from keras.optimizers import Adam, SGD, Adadelta, RMSprop, Nadam from sklearn import metrics, preprocessing from Utils import zeroPadding, normalization, ...
import logging import pathlib import csv import re import numpy as np import scipy.io as scio import datajoint as dj from pipeline import lab from pipeline import ephys from pipeline import experiment from pipeline import ccf from pipeline import histology from pipeline.ingest import behavior as behavior_ingest fro...
import django_filters from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.utils.translation import ugettext_lazy as _ from django.template.loader import render_to_string # HTML to TXT from django.core.urlresolvers import reverse from django.core.mail im...
# -*- coding: utf-8 -*- """ Created on Tue Jul 23 16:44:09 2019 @author: BiSBII """ import math import logging import time from optimModels.utils.constantes import solverStatus from optimModels.utils.utils import MyPool from geckopy import GeckoModel from optimModels.simulation.simul_problems import GeckoSimulationP...
from pyquil.noise import add_decoherence_noise from pyquil.gates import * from pyquil.quil import Program import random random.seed() import numpy as np pi = np.pi def get_one_q_circuit(q_index, depth): """ :param q_index: index of the qubit which the circuit acts on :depth: depth of the circuit :ret...
# ------------------------------------------------------------------------------------- # Library import os import numpy as np from numpy.lib.recfunctions import append_fields, rename_fields, drop_fields from pygeogrids.netcdf import load_grid from src.hyde.algorithm.utils.satellite.hsaf.lib_ascat_generic import fil...
############################################################################## # This file is part of pysgpp, a program package making use of spatially # # adaptive sparse grids to solve numerical problems # # # # Copyr...
"""Test config.""" import os import sys from contextlib import nullcontext from unittest.mock import patch import pytest import voluptuous from viseron.config import ( NVRConfig, ViseronConfig, create_default_config, detector_enabled_check, import_motion_detection, load_config, load_secret...
#!/usr/bin/python3 import json import base64 import hashlib import sqlite3 import argparse from Crypto.Cipher import AES from collections import Counter class KakaoDbGuessUserId: @staticmethod def run(db_file): con = sqlite3.connect(db_file) cur = con.cursor() cur.execute('SELECT id, members FROM cha...
# Copyright 2019 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
""" kb_handler converts knowledge bases in various data types (txt, csv, sql) into a kb object. This kb object may then be further used for finetuning and eval """ import pandas as pd import numpy as np import pyodbc from tika import parser import argparse import re def unique_indexing(non_unique): """ Conver...
# Hardcoded plotting of the plots for the # method illustration # import os import numpy as np import gym from matplotlib import pyplot from matplotlib.patches import Ellipse import matplotlib.transforms as transforms from gmm_tools import train_ubm, adapted_gmm_distance, trajectories_to_supervector from collect_traj...
# Copyright 2019-2020, Offchain Labs, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
# Copyright (c) 2017 The Khronos Group Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
""" Use the BPL models to predict scores for upcoming fixtures. """ import os import sys from collections import defaultdict from .mappings import ( alternative_team_names, alternative_player_names, positions, ) from scipy.stats import multinomial from sqlalchemy import create_engine, and_, or_ from ...
import numpy as np import torch as t from torch import nn from torch.utils.data import Dataset,DataLoader from torch.autograd import Variable from torchvision import transforms import ipdb import tqdm import fire import os import visdom from PIL import Image from torchnet.meter import AverageValueMeter #first step: bu...
from __future__ import unicode_literals import json import unittest from xrd import XRD, Link, Property, Title, _get_text class TestXRDProperty(unittest.TestCase): def testassignment(self): xrd = XRD() xrd.properties.append('http://example.com/lang') xrd.properties.append(('h...
import logging from dataclasses import dataclass from typing import Iterator, List, Optional, Tuple, cast from hexbytes import HexBytes from moonstreamdb.models import EthereumBlock, EthereumLabel, EthereumTransaction from sqlalchemy.orm import Query, Session from web3 import Web3 from web3.types import TxReceipt log...
from bpy.props import PointerProperty, StringProperty, BoolProperty, \ EnumProperty, IntProperty, FloatProperty, FloatVectorProperty, \ CollectionProperty, BoolVectorProperty from ...rfb_utils import shadergraph_utils from ...rfb_logger import rfb_log from ... import rman_config import bpy class RendermanBl...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 from abc import ABC, abstractmethod from collections.abc import Hashable from contextlib import ContextDecorator, contextmanager from timeit import default_timer from . import instrument from .interpreter import get_interpretation, po...
from time import time import os import numpy as np import torch import torch.nn.functional as F from tqdm import tqdm from torch import nn from torch.autograd import Variable # Check for CUDA support. device = torch.device("cuda:0" if os.environ.get("CUDA_VISIBLE_DEVICES") else "cpu") CUDA_AVAILABLE = torch.cuda.i...
# -*- coding: utf-8 -*- # Copyright (c) 2016, Camptocamp SA # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # l...
#! /usr/bin/env python3 import os import shutil import re import hashlib from filegroups import typeGroups, typeList from glob import glob class Directory(object): def __init__(self, path): self._path = os.path.abspath(path) self._name = os.path.basename(self.path) self._parent = os.path...
# coding: utf-8 from pypif.obj import * from pif_csv_utils.general import * def add_uid(systm, uid): """ Adds a uid to a system :param systm: system object to add the uid to :param uid: uid to add :return: system updated with the uid info """ if systm.uid: raise ValueError( ...
import os import torch import torch.nn.functional as F import torchvision.transforms.functional as TF from torchvision.utils import save_image from math import ceil from skimage.io import imread import cv2 from glob import glob import re import numpy as np from utils import warp from model import SBMENet, ABMRNet, Syn...
#------------------------------------------------------------------------------ # Copyright 2017 Esri # 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/LICENS...
""" SSU: Steam Screenshot Utils. - Back up Steam screenshots by specifying your Steam user folder. Categorizes them into folders with the corresponding app names. (Useful when you don't have the "Save uncompressed copy" option enabled). - Sort uncompressed screenshots into folders with the corresponding ap...
import pygame class Movement: def __init__(self, board): self._board = board def update_board(self, board): self._board = board def moves(self, piece, pos, player): info = piece.name.split("_") color = info[0][0] x, y = pos if color == pl...
""" Django settings for NetDash project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os im...
#!/usr/bin/env python3 # ============LICENSE_START======================================================= # Copyright (c) 2018-2021 AT&T Intellectual Property. All rights reserved. # Copyright (c) 2019 Pantheon.tech. All rights reserved. # Copyright (c) 2020 Deutsche Telekom. All rights reserved. # Copyright (c) 2021 F...
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import cv2 import operator import utils as utl import numpy.matlib as mth from . import colorchecker as chc import PIL.Image as Image import PIL.ImageColor as ImageColor import PIL.ImageDraw as ImageDraw import PIL.ImageFont as ImageFont ...
from face_detector import FaceDetector from mark_detector import MarkDetector import numpy as np import cv2 import imutils from imutils.video import VideoStream import time def get_headpose(h, w, landmarks_2d, landmarks_3d, lm_2d_index): f = w # column size = x axis length (focal length) u0, v0 = w / 2, h / ...
import logging import os import numpy as np from pathlib import Path from copy import copy import simtools.config as cfg import simtools.io_handler as io from simtools.corsika.corsika_runner import CorsikaRunner from simtools.util import names from simtools.util.general import collectDataFromYamlOrDict __all__ = ['S...
# -*- coding: utf-8 -*- """ OLS API wrapper Original code borrowed from https://github.com/cthoyt/ols-client/blob/master/src/ols_client/client.py - Removed ontology and term methods. - Added details/parameters for all search methods TODO: check input parameters are valid TODO: handle requests.exceptions.Connection...
import tempfile import h5py import numpy as np from pyscf import lib #einsum = np.einsum einsum = lib.einsum # Ref: <NAME> <NAME>. Phys. 103, 3561 (1995) Table III # Section (a) def make_tau(t2, t1a, t1b, fac=1, out=None): #:tmp = einsum('ia,jb->ijab',t1a,t1b) #:t1t1 = tmp - tmp.transpose(1,0,2,3) - tmp.tra...
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Test layers in modules.linear. """ # =========================================================================...
import argparse import json import os import random from os.path import join, abspath from pathlib import Path import numpy as np from numpy import argmax from highway_disagreements.disagreement import save_disagreements, get_top_k_disagreements, \ disagreement, \ DisagreementTrace, State, make_same_length fr...
from __future__ import annotations from abc import ABC from typing import Any, Callable, List from tensorflow import maximum, minimum, constant, SparseTensor, cast, reshape, reduce_max, tile, Tensor, gather from tensorflow.keras.backend import to_dense from tensorflow.keras.layers import Minimum, Maximum, Dense, Dot, C...
#!/usr/bin/env python3 # # Copyright (C) 2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # import logging import os import sys from argparse import ArgumentParser, SUPPRESS import matplotlib.pyplot as plt import numpy as np def build_argparser(): parser = ArgumentParser(add_help=False) args =...
import unittest from itertools import product import torch import numpy as np import pywt from torchimage.padding.generic_pad import Padder, _stat_padding_set from torchimage.padding.utils import same_padding_width def scipy_same_padding_width(kernel_size): if kernel_size <= 1: return 0, 0 pad_beg =...
import numpy as np import pandas as pd import torch from torch.autograd import Variable from torchvision import transforms import argparse import os import sys import matplotlib.pyplot as plt import tqdm import math import random SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(S...
import os import sys from queue import Queue from capstone import * from capstone.arm64_const import * import disassembler import API from formats.constructs import * from formats.enums import * from datetime import datetime import fileinput import shutil _ADRP_TYPES = { "else": 0, "text_sec": 1, "data_sec": ...
import re import httpx import pydantic import pytest import eospyo def test_should_always_pass(): pass def test_when_instantiate_net_returns_net_object(): net = eospyo.Net(host="http://127.0.0.1:8888") assert isinstance(net, eospyo.Net) def test_when_instantiate_net_with_incorrect_host_format_then_r...
#!/usr/bin/env python """ DataExplore pluin differential expression using R Created June 2017 Copyright (C) <NAME> 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 versi...
################################################################ def build_re2c(repo_ctx): # Have we already built re2c? FIXME: check version repo_ctx.report_progress("Checking for cached re2c...") repo_ctx.file( "re2c.sh", content = "\n".join([ "#!/bin/bash", "if [...
import math import cv2 from PIL import Image, ImageDraw import matplotlib.pyplot as plt import face_recognition from collections import defaultdict import numpy as np import padding import resizing def detect_landmark(image_array, model_type = "large"): """ return landmarks of a given image array ...
# version code 7bdbe7c95e85+ coursera = 1 # Please fill out this stencil and submit using the provided submission script. from vec import Vec from mat import Mat from matutil import rowdict2mat,coldict2mat,mat2coldict from solver import solve ## 1: (Task 5.12.1) Move To Board def move2board(y): ''' Input: ...
# Copyright 2017 <NAME> # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license from __future__ import unicode_literals import os.path as op from send2trash.com...
import json from flask import Flask,abort, jsonify,request import os from flask_sqlalchemy import SQLAlchemy from urllib.parse import quote_plus from sqlalchemy import * from dotenv import load_dotenv load_dotenv() app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://icjepezldkutwl:<EM...
## coding: UTF-8 from ecpy import EllipticCurve, ExtendedFiniteField, symmetric_tate_pairing import hashlib import random # import cPickle from flask import Flask, request, redirect, url_for import dill import binascii import codecs # print "my sp",3735928559 * P # print "P isPoint : ",E.is_on_curve(P) # print "sP is...
import sys import os import logging import argparse import json import time import re import pickle as pkl from copy import deepcopy import random import numpy as np import torch import torch.nn.functional as F import progressbar from sklearn import metrics from allennlp.modules.elmo import Elmo, batch_to_ids from nlt...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
import json from typing import Any, Dict, List, Optional, Set, Tuple, Type, TypeVar import psycopg2 from envinorma.enriching import enrich from envinorma.models.am_metadata import AMMetadata, AMState from envinorma.models.arrete_ministeriel import ArreteMinisteriel from envinorma.parametrization.models.parametrizatio...
import os import shutil from copy import deepcopy import random import numpy as np import pandas as pd import torch from torch import optim from torch.optim.lr_scheduler import StepLR from tqdm import tqdm from transformers import AdamW from nltk.tokenize import TweetTokenizer import matplotlib.pyplot as plt from ut...
import abc import copy from numbers import Number from typing import List, Union from src.dimension import Dimension, DIMENSIONLESS class Base(abc.ABC): _factor = 1 @property @abc.abstractmethod def constituent_units(self) -> List: return NotImplemented @property @abc.abstractmethod...
from typing import List import copy import time class State: def __init__(self, state: List[List[int]], cost: int, heuristicCost: int, level: int, expandth_num: int): self.state = state # a 2d list keeping track of ball positions, colors(integers) and empty spots(zeros) self.cost = cost ...
import streamlit as st import os import wfdb import tkinter as tk from tkinter import filedialog import numpy as np import matplotlib.pyplot as plt from pymongo import MongoClient import gridfs st.title('This is a Huy test website') import streamlit as st import pandas as pd # Load some example data. DATA_URL = \ ...
#!/usr/bin/python # ex:set fileencoding=utf-8: from __future__ import unicode_literals """ models doctype """ from django.core.exceptions import ValidationError from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from dja...
""" Functions to run cluster inference - test """ import math import numpy as np from skimage import measure from nilearn.image import get_data, load_img from nilearn.input_data import NiftiMasker from scipy.stats import t import sanssouci as sa import pyrft as pr def find_clusters(test_statistic, cdt, b...
import json from django.forms.models import modelform_factory from django.http import HttpResponse from django.http import QueryDict from django.shortcuts import get_object_or_404 from django.template.loader import render_to_string from django.urls import reverse from django.views.generic.base import View import pyst...
""" Author: Darren Date: 12/10/2021 Solving https://adventofcode.com/2016/day/22 Rectangular storage grid where each node is surrounded by four others, i.e. L, R, U, D. We can only access data in top left (x=0, y=0). But we can also MOVE data between any adjacent nodes, if there is available capacity for such a move....
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: <NAME> (<EMAIL>) # @Date: 2020-05-26 # @Filename: __main__.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) import importlib import logging import os import sys import time import warnings from glob import glob import click import...
#-------------------------------------# # 创建YOLO类 #-------------------------------------# import colorsys import os import cv2 import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn as nn from PIL import Image, ImageDraw, ImageFont from torch.autograd import Variable ...
import datetime import io import logging import requests import numpy import pandas from typing import Dict, Tuple, Union from .. import data, preprocessing _log = logging.getLogger(__file__) def get_regions_metadata() -> Tuple[Dict[str, str], Dict[str, float]]: """ Link to regions' population: https://ww...
from . import api_facturae from . import fe_enums from . import makepdf import base64 from service import emails from infrastructure import companies from infrastructure import documents def create_document(data): _company_user = data['nombre_usuario'] _type_document = fe_enums.TipoDocumentoApi[data['tipo']...
import numpy as np import math import sys, os import random import json def intersect(box_a, box_b): A = box_a.shape[0] B = box_b.shape[0] box_a_expand = np.expand_dims(box_a[:, 2:], axis=1) box_a_expand = np.tile(box_a_expand, (1, B, 1)) box_b_expand = np.expand_dims(box_b[:, 2:], axis=0) box...
# FIXME support languages other than English import re def guess_times(fragment): result = [] for clause in fragment: if clause[1] == 'ClockTime': result.append((clause[0], clause[1], clause[2], quote(guess_clock_time(unquote(clause[3]))))) elif clause[1] == 'DayOfMonth': ...
################################################################################ # Copyright (C) 2019 drinfernoo # # # # This Program is free software; you can redistribute it and/or modify ...
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, <NAME>, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must r...
import numpy as np from bokeh.plotting import figure, Figure from bokeh.models import ColumnDataSource, LabelSet from proto.messages_robocup_ssl_geometry_pb2 import ( SSL_FieldCircularArc, SSL_FieldLineSegment, ) from proto.messages_robocup_ssl_detection_pb2 import ( SSL_DetectionBall, SSL_DetectionRobo...
"""Kai Heart Radio Scrape songs from the Marketplace latest music page and add them to a Spotify playlist. Daily command scrapes song from latest posted day. Bootstrap scrapes all songs from <pages> number of pages. Config.txt file should exit in script's directory. Config file should contain Spotify app+user credenti...
### Imported Libraries ### import time # Sleep/interrupt librariy import cv2 # OpenCV library import numpy as np # Python Math Library import os # Operating system library from PIL import Image ...
""" Main script: Train a model. """ __date__ = "January - May 2021" import datetime from collections import defaultdict import fire import json import numpy as np import os import sys from time import perf_counter import torch from src.misc import LOGGING_DIR, ARGS_FN, LOG_FN, STATE_FN, AGG_FN, INDENT from src.util...
# ---------------------------------------------------------------------------- # Title : parseNetParams # Project : Haddoc2 # ---------------------------------------------------------------------------- # File : parseNetParams.py # Author : <NAME> # Company : Institut Pascal # Created : 26-10-20...
"""Module contains that FactorAnalysis object that coordinates an entire analysis through a series of in-place data operations. Typical workflows are illustrated by the notebooks in the `./examples` folder """ import numpy as np import pandas as pd import fa_kit as fa from fa_kit.broken_stick import BrokenStick #...
import subprocess as cmd import os import sys from importlib import reload import traceback import glob import re from typing import List from pathlib import Path def list_file_by_glob(path_pattern, suffix='*.py'): res = [] if os.path.isfile(path_pattern): return [str(Path(path_pattern).absolute())] ...
# Copyright (C) 2010-2013 <NAME>. # Copyright (C) 2014-2016 Cuckoo Foundation. # Copyright (C) 2020-2021 PowerLZY. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. from __future__ import print_function import errno import json import os import s...
# -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2022 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See ful...
import random import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.backend as K import tensorflow_addons as tfa from tensorflow.keras.layers import Layer from tensorflow.python.keras.utils import tf_utils from tensorflow.python.keras.engine.input_spec import InputSpec import augtistic.ran...
import argparse from time import sleep from random import choice from urllib.parse import quote try: import requests # would fail to import if invoked from setup.py except: pass import shutil from os.path import abspath, dirname from os import environ from subprocess import call as call_, DEVNULL, check_outpu...
import h5py import lmfit import numpy as np from skimage.restoration import denoise_tv_chambolle from .core import FLImage from .meta import FLMetaDict class FLSeries(object): _instances = 0 def __init__(self, flimage_list=[], meta_data={}, h5file=None, h5mode="a", identifier=None): ...
import logging import re import numpy as np import torch from transformers import SPIECE_UNDERLINE logger = logging.getLogger(__name__) def compute_attention(sample_layer_attention, att_pooling, dim=0): # pool attention vectors across heads sample_layer_attention_pooled = None if att_pooling == 'mean': ...
def sort_files( files, split_on='_', elem_month=-2, elem_year=-1 ): ''' sort a list of files properly using the month and year parsed from the filename. This is useful with SNAP data since the standard is to name files like '<prefix>_MM_YYYY.tif'. If sorted using base Pythons sort/sorted functions, things will b...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os os.environ["CUDA_VISIBLE_DEVICES"] = "1" import numpy as np import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) model_dir = __file__[:-3] + "-log" def cnn_model_fn(features, labels, m...
""" Thompson Sampling strategies for continuous context. """ from argparse import Namespace import numpy as np from scipy.stats import norm as normal_distro from scipy.optimize import minimize from OCBO.cstrats.cts_opt import ContinuousOpt from dragonfly.utils.option_handler import get_option_specs from OCBO.util.mis...
"""Deals with metadata and icons.""" import threading import os import subprocess import re import config import mediaconf import hashlib import pickle import urllib import time from threading import Lock cacheVersion = 4 uniqueLock = Lock() counter = 0 def utf8(s): """Convert to UTF-8.""" return s.encode("...
import math import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.nn.modules import padding class InvBlockExp(nn.Module): def __init__(self, subnet_constructor, channel_num, channel_split_num, clamp=1.): super(InvBlockExp, self).__init__() self.split_len...
"""Tests for Alazar DLL API This suite of tests is expected to be executed on a Windows PC with a single Alazar board installed. """ import os import gc import logging import pytest from qcodes.instrument_drivers.AlazarTech.ATS import AlazarTech_ATS from qcodes.instrument_drivers.AlazarTech.ats_api import AlazarATS...