text
stringlengths
3.07k
22.1k
import base64 import copy import csv import json import random import sys import time import numpy as np from tqdm import tqdm from ..utils.stream import ItemFeature from .base_reader import IMIXDataReader class LXMERTPretrainReader(IMIXDataReader): def __init__(self, cfg): self.cfg = cfg self....
import numpy as np import pickle import os import time import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from PIL import Image class ImageWriter(object): def __init__(self, data_dir, dataset, unnormalizer): self.data_dir = data_dir self.dataset = dat...
import collections import contextlib import importlib import inspect import json import os import smtplib import subprocess import sys from collections import defaultdict from collections.abc import Iterable from datetime import datetime from email.message import EmailMessage from typing import Tuple, Union import dat...
import os from psims.mzid import MzIdentMLWriter import csv import re PROTON = 1.007276466879 FIXED_PTM = [{'name':'C57', 'mass':57.021464, 'uni_id':'4'},{'name':'C58', 'mass':58.005479, 'uni_id':'6'}] def mass_to_charge_ratio(mass, z, charge_carrier=PROTON): return abs((mass + (charge_carrier * z)) / z) class ...
from enum import Enum, auto import discord from discord_interactive.link import ReactLink, MsgLink DEFAULT_PARENT_REACT = '🔙' DEFAULT_ROOT_REACT = '🔝' DEFAULT_LINK_REACTS = ['1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣'] class PageType(Enum): """ Existing type of page. The type of a page define how th...
import skimage as ski from skimage.morphology import binary_dilation, disk import numpy as np import os from scipy.spatial import distance_matrix class Evaluator(object): def __init__(self, thres=None, gt_type="mask", line_match_thres=3): # self.type = type if thres is None: # self.t...
# %% from shutil import which from subprocess import call import matplotlib.pyplot as plt import numpy as np import pandas as pd from plotly.graph_objects import Figure from ml_matrics.correlation import marchenko_pastur from ml_matrics.cumulative import cum_err, cum_res from ml_matrics.elements import ( hist_ele...
""" Filename: gridtools.py Authors: <NAME>, <NAME> Implements cartesian products and regular cartesian grids, and provides a function that constructs a grid for a simplex as well as one that determines the index of a point in the simplex. """ import numpy as np import scipy.special from numba import jit, njit from ....
""" A set of functions for needed for running training in various settings """ from MultiPlanarUNet.logging.default_logger import ScreenLogger def get_train_and_val_datasets(hparams, no_val, train_on_val, logger): """ Return all pairs of (train, validation) SleepStudyDatasets as described in the YAMLHPar...
# Pybatic (Python Batch Image Converter) Version 1.1.0 import argparse import os import sys from PIL import Image def argument_check(): """ Check whether the user run the program interactively or not. Return 0 if interactive (no arguments used). Return 1 if not interactive (user used command-line ar...
# ================================================================================ # Script Settings # ================================================================================ global MESSAGE, FILENAME, FILE_FOUND # In all settings that act as a boolean (true or false) option, 0 = false, 1 = true # Shared Set...
# # Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. # # 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; version 2 of the License. # # This program is distributed in the hope...
from __future__ import absolute_import from __future__ import print_function from six.moves import map __all__ = ['Component'] import re from .joiner import Joiner DEBUG = True parts_re = re.compile(r'%\([\w.]+\)[rs]') killline_re = re.compile(r'.*[<]KILLLINE[>].*(\n|$)') class Branch(object): """ Represents a ...
from PyQt5.QtCore import QRect, QMetaObject, qrand, QEvent from PyQt5.QtGui import QPainter from PyQt5.QtWidgets import QWidget, QVBoxLayout, QSizePolicy, QStyleOption, QStyle from .QToolWindowManager import QToolWindowAreaReference, QToolWindowManager from .QToolWindowManagerCommon import * from .QTrackingTooltip imp...
import time import can import sys from can.interfaces.interface import Bus can_interface = 'can0' # # TODO: keep sending 700/02 3e 80 # # bus = Bus(can_interface) receivers = [] def hexdump(x): return ' '.join("%02x" % y for y in bytearray(x)) class IsoTp: PAD = bytes([0x55]) def __init__(self, bus, id_source,...
""" @brief Script use to test if the environment are running correctly. The script runs the Coppeliasim container with the specified environment id and executes twice a sample task for each of the selected environment. @authord <NAME> (<EMAIL>) @date 21 Apr 2021 """ import argpar...
from __future__ import annotations from typing import ( Callable, Any, ClassVar, Dict, Iterator, Set, TYPE_CHECKING, Tuple, Type, TypeVar, Optional, ) class Permission: def __init__(self, value: int) -> None: self.value = value class Use...
# prevent bug from rasterio import os del os.environ['GDAL_DATA'] # import libs import itertools import rasterio from rasterio.mask import mask from rasterio.warp import reproject, calculate_default_transform as cdt, Resampling from rasterstats import zonal_stats from geocube.api.core import make_geocube from shape...
import numpy as np import pandas as pd from scipy import stats import statsmodels.api from .utils import isint import numba def gen_emat_rand(site_size, mean=1, sd=1): """ Generate a random energy matrix for a defined sequence length. Arbitrary values for each possible base, normally distributed around mean 1 ...
"""Data structures in Foam-Files that can't be directly represented by Python-Structures""" from __future__ import division import re import six import math import copy if six.PY3: def cmp(a,b): if a<b: return -1 elif a==b: return 0 else: return 1 clas...
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from time import sleep import pytest from openpyxl import load_workboo...
# coding=utf8 from __future__ import absolute_import, print_function, division import os from datetime import date, datetime, timedelta from functools import wraps from collections import defaultdict from flask import Flask, request, session, escape from flask import render_template, url_for, redirect, abort, flash ...
import nltk import numpy ############################################################################################################################## ### PART 1: NIKOLAOS SKAMNELOS usefull graph functions: #CREATES a graph using a fixed sized window, by spliting the original textfile into sub-textfiles # Split Fil...
import typing from typing import Any, Dict, Iterable, List, Optional, Tuple import attr from dbnd._core.errors import DatabandError from dbnd._core.parameter.constants import ParameterScope if typing.TYPE_CHECKING: from dbnd._core.task.base_task import _BaseTask from dbnd._core.parameter.parameter_definiti...
# -*- coding: utf-8 -*- # This file is part of the NEAT Project suite of libraries # Please see the LICENSE file that should have been included as part of this # package. from collections import Counter, defaultdict import matplotlib.pyplot as plt from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.token...
from django.db.models import Avg from django.shortcuts import get_object_or_404 from rest_framework import status, viewsets from rest_framework.exceptions import NotFound from rest_framework.generics import GenericAPIView from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.response impo...
from __future__ import print_function, absolute_import import re import os import sys import logging if sys.version_info[0] == 2: # pragma: no cover from ConfigParser import ConfigParser as _ConfigParser from StringIO import StringIO class ConfigParser(_ConfigParser): def read_string(self, strin...
#!/usr/bin/python import os, sys from printformats import formatting # ---allow input() to function in 2 & 3 if hasattr(__builtins__, "raw_input"): input = raw_input class Menus(): """Menu class Each Menus class instance stores a list of line item descriptions and a corresponding function object tha...
from typing import Dict, List from solvers.solver import Solver, Node, Graph from solvers.ucs import * from solvers.astar import * from solvers.rtastar import * from solvers.lrtastar import * import timeit from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam def manhat...
import os import pickle import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import torch from torch.utils.data import Dataset from file_io import Events, read_2d_spikes ######################################################### # Utility functions #############################...
from __future__ import print_function, division, absolute_import import collections import re import numpy from . import types, config, npdatetime from .targets import ufunc_db version = tuple(map(int, numpy.__version__.split('.')[:2])) int_divbyzero_returns_zero = config.PYVERSION <= (3, 0) FROM_DTYPE = { nu...
# -*- coding: utf-8 -*- """ Created on Thu Apr 12 00:49:24 2018 @author: bjwil """ a = np.matrix([['A',.2,.2,0,0,0,0,.9,.1,.1,.1,.3,0], ['C',.1,.6,0,0,0,0,.0,.4,.1,.2,.4,.6], ['G',0,0,1,1,.9,0.9,.1,0,0,0,0,0], ['T',.7,.2,0,0,.1,.1,0,.5,.8,.7,.3,.4]]) profile = { 'A': [0.2, 0.2, 0.0, 0.0, 0.0, 0.0,...
import torch import torch.nn as nn import torch.nn.functional as F from scipy.io import loadmat import numpy as np import torch_geometric as pyg from torch_geometric.data import InMemoryDataset import torch_geometric.data as tgd import torch_geometric.utils as utils from torch.autograd.function import Function...
from mapi.pst.crypto import * from mapi.pst.node import * from mapi.util.crc32 import * from mapi.util.decoder import * from mapi.util.logger import * __all__ = ['Nbt', 'BID', 'IB', 'BREF', 'HEADER', 'ROOT', 'PST_HEADER_SIZE'] PST_HEADER_SIZE = 512 + 64 PST_ROOT_SIZE = 72 PST_HEADER_SIGNATURE = b"\x21\x42\x44\x4E" PS...
import sys, random, time, hashlib import moment from geopy.distance import vincenty def getHash(post_content): strhash = "" strhash += str(post_content["type"]) st = moment.unix(post_content["start_time"]) strhash += str(st.month) + str(st.day) if(post_content["latitude"] == -1): ...
import os import random import numpy as np from tqdm import tqdm from utils import clip_dataset, put_static_first def impute_sample_1h(measures, stay_time=None): """Forward imputes with 1h resolution any stay to duration stay_time. Args: measures: Array-like matrix with succesives measurement. ...
# this is an example # # Dieses Beispiel enthält vorschläge für Formatierung # (und geht über das Niveau des start-projects hinaus). # Dieser Code kann als inspiration dienen um sich den # Aufbau eines Programms in Python vorzustellen. # # Nutzt bitte Methoden und führt dann zum Schluss diese # in dieser if Abfrage au...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 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/l...
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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...
# !/usr/local/bin/python3 from common import get_question_and_gold_answer, get_corpus_path import yaml import spacy from spacy import displacy from collections import Counter import en_core_web_sm import json import unicodedata import re from pprint import pprint from contractions import CONTRACTION_MAP #import en_cor...
import pygame import random import os pygame.font.init() WIN_WIDTH, WIN_HEIGHT = 500, 800 # IMAGES BIRD_IMG = [pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird1.png"))), pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird2.png"))), pygame.transform.scale2...
from collections import deque import numpy as np from numpy.lib.arraysetops import isin import torch import cProfile import time class NStepBuffer: def __init__(self, gamma=0.99, nstep=3): assert isinstance(gamma, float) and 0 < gamma < 1.0 assert isinstance(nstep, int) and nstep > 0 sel...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 7 12:00:03 2018 @author: max Gets the folders and creates the matlab call for the GC analyzer for segmentation. Takes as arguments the path where the folders for knockdowns are located a precoded modality parameter, -m, to select the parameter file fo...
#!/usr/bin/env python3 # # Copyright (c) 2019 Samsung Electronics Co., Ltd 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 # #...
#!/usr/bin/env python # -*- coding: utf-8 -*- import abc import datetime as dt import json import logging from collections import defaultdict from dataclasses import dataclass from pathlib import Path from typing import ( Dict, List, Literal, NewType, Optional, Tuple, TypedDict, Union, ...
import random import discord import pathlib from . import constants from .solvertools.anagram import anagrams from .solvertools.wordlist import cromulence from .utils import ciphers, external_api from .utils.registrar import WORD_SET_TESTS from redbot.core import commands COMMAND_KEYWORDS = {} def random_nature_em...
import io import os from distutils.version import StrictVersion from importlib import import_module from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.migrations.recorder import \ MigrationRecorder as DjangoMigrationRecorder from django.db.utils import Programmi...
#!/bin/env python # # Advent of Code 2020 # Day 10 # # author: <NAME> # e-mail: <EMAIL> # import sys from argparse import ArgumentParser from pathlib import Path import functools import pytest import numpy as np import collections from itertools import groupby @pytest.fixture def example_data_0(): test_data = ...
from django.conf import settings from rest_framework import serializers from .models import DeviceCategory, Device, Stream, Chart, Trigger, TriggerLog from base.base_serializers import BaseModelSerializer class DeviceCategorySerializer(BaseModelSerializer): device_count = serializers.SerializerMethodField(read_o...
""" Created on Wed Sep 07 2016 pvp version created on Sat Jan 06 2018 @author: <NAME>. Gameplay """ """ purpose: Creating a simple game to learn how to use tkinter module name: game-theory LTK-simplified moves: charge, attack, defend, ult attack, heal play-mode: player1 vs player2 game rules: > p1 = player1, p2 = p...
import numpy as np import torch from mmcv.cnn import normal_init from mmdet.core import force_fp32, multiclass_nms from mmdet.models.anchor_heads import RetinaHead from mmdet.models.losses import IoULoss from mmdet.models.losses.utils import weighted_loss, weight_reduce_loss from mmdet.models.registry import HEADS, LO...
import attr import json import pickle import copy import logging try: import yaml except ModuleNotFoundError: yaml = None from pathlib import Path, PosixPath JSON_SUFFIXES = (".json", ".jsn") YAML_SUFFIXES = (".yaml", ".yml") PICKLE_SUFFIXES = (".pickle", ".pkl", ".pcl") logger = logging.getLogger(__name_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 7 13:35:14 2020 This is a curses tool to inspect the agentData.pk files. There are two ways to start it 1. Call it with an argument python inspect_agent.py agentData.pk 2. Call it without arguments python...
import numpy as np import h5py import pandas as pd from skimage. io import imsave from keras.datasets import cifar10 from svhn_io import load_svhn import matplotlib.pyplot as plt from matplotlib.lines import Line2D EPSILON = 1e-10 def compute_entropy_scores(data, axis=-1): return np.sum(-data * np.log(data + EP...
import os, glob, sys, io import numpy as np import pandas as pd # Timeseries data import datetime as dt # Time manipulation import yaml from matplotlib.dates import date2num # Convert dates to matplotlib axis coords from matplotlib import dates from scipy import fftpack from scipy import stats fro...
import json, logging, pprint, urllib import requests from easyborrow_controller_code import settings from easyborrow_controller_code.classes.db_handler import Db_Handler from easyborrow_controller_code.classes.web_logger import WebLogger from requests.packages.urllib3.exceptions import InsecureRequestWarning request...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 20 10:24:55 2019 @author: bressler """ import SBCcode as sbc from os import listdir from os.path import isfile,join import numpy as np import matplotlib.pyplot as plt import scipy import pulse_integrator as pi from gaincalc import get_gain def NI...
import gurobipy as gurobi import matplotlib.pyplot as plt class Player: def __init__(self, index, demand_ref, supply_max, demand_max, exchange_max, connection_n, supply_a, supply_b, demand_a): self.index = index self.demand_ref = demand_ref self.supply_max = supply_max ...
import gym import time import numpy as np import numpy.random as rd import matplotlib.pyplot as plt from gym.envs.classic_control.cartpole import CartPoleEnv from tf_tools import * from cartpole_utils import plot_results,print_results import tensorflow as tf from replay_memory import ReplayMemory mini_batch_size = 20...
"""PIL/Tkinter based simulator for InkyWHAT and InkyWHAT.""" import numpy from . import inky from . import inky_uc8159 class InkyMock(inky.Inky): """Base simulator class for Inky.""" def __init__(self, colour, h_flip=False, v_flip=False): """Initialise an Inky pHAT Display. :param colour: ...
import torch import torch.nn as nn import torch.nn.functional as F import math from torch.autograd import Variable class VGG_enc(nn.Module): def __init__(self, input_channels=6): super(VGG_enc, self).__init__() in_channels = input_channels self.c11 = nn.Conv2d(in_channels, 64, kernel_size=...
# useful references # http://effbot.org/tkinterbook/entry.htm # http://effbot.org/tkinterbook/grid.htm <--- grid manager # http://effbot.org/zone/tkinter-callbacks.htm <-- passing argument to tk button # http://stackoverflow.com/questions/550050/removing-the-tk-icon-on-python-tkinter-windows # http://stackoverflow.com/...
# -*- coding: utf-8 -*- """ metalibm_core.core.random_gen Random value generation """ ############################################################################### # This file is part of metalibm (https://github.com/kalray/metalibm) ############################################################################### # MI...
#!/usr/bin/env python3 # coding: utf-8 """ Pre-release checks against precinct returns datasets. WIP. """ import logging from pathlib import Path import numpy as np import pandas as pd import plac import yaml from medsl import PRECINCT_COLS from medsl.docs import write_frequencies from medsl.metadata import Metadata...
# #! coding:utf-8 import os from astropy.time import Time from datetime import datetime as dt from numpy import arange from datetime import datetime as dt from datetime import datetime,timedelta from ligotimegps import LIGOTimeGPS from gwpy.time import tconvert fname_fmt={ # ChannelName:Format,Mustreplace<...
import copy import random from functools import partial from .base import AgentPolicy class VaccineResult(): def __init__(self, vaccine_name, agent, result, time_step, efficacy, decay_days, current_dose): self.vaccine_name = vaccine_name self.agent = agent self.result = r...
from collections import defaultdict import dimod from qiskit.optimization import QuadraticProgram from itertools import * from qiskit.optimization.converters import LinearEqualityToPenalty, IntegerToBinary, InequalityToEquality from instance_ilp import Instance_ilp # Variables for the route and cost hamiltonian def ...
from keras.layers import * from keras.models import Model from keras.layers.normalization import * from keras.regularizers import * from keras import backend as K import numpy as np MAX_FILTERS_UNTIL_COMPRESSION = 784 def _create_compression_block(x, layer_id, compression=0.5, weight_decay=0.0001): while x.get_...
# Copyright (c) 2018 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 app...
from django.contrib.auth.models import User from django.shortcuts import HttpResponse, get_object_or_404 from rest_framework import viewsets, status from rest_framework.response import Response from .serializers import ( UserSerializer, CategorySerializer, IngredientSerializer, RegionSerializer, D...
""" Copyright 2005-2018 QuantumRocket. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. """ import lib.log as log import sql.db as db import sql.db_users as db_users import sql.db_widgets as db_widgets import sql.db_things as db_things from flask i...
import os import re import numpy as np os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf from model.model_lstm import * from dirs import checkpoints_dir from model.category_list import admissible_categories as category_list checkpoint_dir = os.path.join('model', checkpoints_dir) # model params para...
"""Module consists of certain PEP8 punishment conventions in a way of defining metaclasses. Allows to examine the contents of a class at the time of definition. Once a PEP8 metaclass has been specified for a class, it gets inherited by all of the subclasses. """ import abc import re from collections import OrderedDic...
import numpy as np import math from collections import defaultdict import random # !pip3 install git+https://github.com/slremy/netsapi --user --upgrade from netsapi.challenge import * from scipy.stats import beta as beta_dist from scipy.stats import norm as norm_dist from sklearn.linear_model import SGDClassifier, Lo...
''' Device class for HLTAPI devices with ixia OS. ''' __all__ = ( 'Device', 'EmulatedDevice', ) from enum import Enum import logging try: from ats.tcl import tclstr import ats.tcl except Exception: pass from genie.decorator import managedattribute from genie.libs.conf.device.hltapi import Devic...
import deepracing_msgs.msg as drmsgs # BezierCurve, TimestampedPacketMotionData, PacketMotionData, CarMotionData, PacketHeader import geometry_msgs.msg as geo_msgs# Point, PointStamped, Vector3, Vector3Stamped import tf2_msgs.msg as tf2_msgs from sensor_msgs.msg import PointCloud2, PointField from std_msgs.msg import ...
''' Core functions of tfscripts.compat.v1: Add residuals, batch normalisation, activation, ''' from __future__ import division, print_function import numpy as np import tensorflow as tf # tfscripts.compat.v1 specific imports from tfscripts.compat.v1.weights import new_weights # constants from tfscripts.compat....
# -*- encoding:utf-8 -*- """示例ump价格特征模块""" from __future__ import division from __future__ import print_function from __future__ import absolute_import from ..TradeBu.ABuMLFeature import AbuFeaturePrice from ..MLBu.ABuMLPd import AbuMLPd from .ABuUmpBase import ump_main_make_xy, BuyUmpMixin from .ABuUmpMainBase impor...
import os import numpy as np import tensorflow as tf import env_oracle as env import time import load_trace from mpc_prunning import solving_log, solving_log_true_bw # import pool import libcomyco_lin as libcomyco os.environ['CUDA_VISIBLE_DEVICES'] = '0' S_INFO = 6 S_LEN = 8 A_DIM = 6 LR_RATE = 1e-4 DEFAULT_QUALITY =...
import os import ssl import umsgpack import asyncio import struct import websockets import libnacl.public from saltyrtc.server import ( NONCE_FORMATTER, NONCE_LENGTH, Event, Server, SubProtocol, serve, util, ) from saltyrtc.server.common import ( SIGNED_KEYS_CIPHERTEXT_LENGTH, Clie...
import numpy as np import matplotlib.pyplot as plt import scipy.sparse as sp import scipy.sparse.linalg as la from functools import partial import time from mpl_toolkits.mplot3d import Axes3D # logging stuff iterations = [] last_iter = {} norms = [] def make_L(Nx, Ny): Dx = sp.diags((Nx-1)*[1.]) Dx += sp.di...
# CREATED: 2/23/17 17:11 by <NAME> <<EMAIL>> import os import gzip import numpy as np from sklearn.metrics import accuracy_score, precision_score, recall_score from termcolor import colored import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import json def training_report(model_folder, split_i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys root_path = "/".join(os.path.realpath(__file__).split("/")[:-2]) if root_path not in sys.path: sys.path.insert(0, root_path) import csv import logging import argparse import random import numpy as np from tqdm import tqdm from torch.utils.da...
import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui import PyQt5.QtCore as QtCore class ArgDragLabel(QtWidgets.QLabel): def __init__(self, arg, parent=None, select=False): super(ArgDragLabel, self).__init__(parent) self.arg = arg self.dialog = None self.isSelected = sel...
# # 5.4 Visualizing what convnets learn # # (https://nbviewer.jupyter.org/github/fchollet/deep-learning-with-python-notebooks/ # # blob/master/5.4-visualizing-what-convnets-learn.ipynb) import os import matplotlib.pyplot as plt import numpy as np from tensorflow.keras.preprocessing import image from tensorflow.keras ...
""" Implement the following components that are used in GauGAN model. Generator (Resnet-based) Discriminator (PatchGAN) Encoder """ import tensorflow as tf import tensorflow_addons as tfa import tensorflow.keras as K from tensorflow.keras.layers import Dense from .layers import ConvBlock, Padding2D, SPADEResBlock imp...
# -*- coding: utf-8 -*- import argparse import numpy import sys # sys.path.append("./src") # from src.utils import * # from src.errorAnalysis import * from ..src.errorAnalysis import * # def tuple2str(triplet): # res = "" # for v in triplet: # res += str(v) + "_" # return res.rstrip("_") def sent2list(se...
from __future__ import annotations import asyncio import re import shutil import time from asyncio import ( ALL_COMPLETED, FIRST_EXCEPTION, AbstractEventLoop, Queue, all_tasks, create_task, current_task, get_running_loop, wait, ) from dataclasses import dataclass from datetime impor...
import copy import json import re import types from logging import error, info import requests from . import DEFAULT_ACCESS_MODE from .re import UUID_MATCH from .schema import Field, MissingField, Schema, schema_doc class NotImplemented(Exception): def __init__(self, *args, **kwargs): Exception.__init__...
import networkx as nx import numpy as np import pickle as pkl import scipy.sparse as sp import sys import torch from utils import add_self_loops, normalize_adj class Data(object): def __init__(self, adj, edge_list, features, labels, train_mask, val_mask, test_mask): self.adj = adj self.edge_list ...
import subprocess from firexapp.engine.celery import app from firexapp.testing.config_base import discover_tests from celery.utils.log import get_task_logger import datetime import os from firexapp import firex_subprocess from firexapp.common import silent_mkdir import lxml.etree as et from firexkit.result import get_...
import json import os import shlex import shutil import subprocess from dataclasses import dataclass, field from pathlib import Path from sys import platform from tempfile import NamedTemporaryFile from typing import Any, Dict, List, Optional, Set, Union from .utils import ROOT, escape_attr, info, sh, warn @dataclas...
# Copyright 2021. IoT Hub # # # 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 appl...
import datetime import re import requests import string import urllib import unidecode import numpy as np import pandas as pd from bs4 import BeautifulSoup from sklearn import metrics comm = re.compile("<!--|-->") pattern = re.compile('[\W_]+') OVERALL_PLAYER_NAME_EXCEPTIONS = { "<NAME>" : "<NAME>", "<NAME>" : "<N...
# python 3.6 """Inverts given images to latent codes with In-Domain GAN Inversion. Basically, for a particular image (real or synthesized), this script first employs the domain-guided encoder to produce a initial point in the latent space and then performs domain-regularized optimization to refine the latent code. """...
from __future__ import absolute_import import pytest from mock import patch from tests import * import basil.industry.facility as f @pytest.fixture(scope="module") def system(): url = "https://public-crest.eveonline.com/solarsystems/30002054/" return {"systemCostIndices": [{"costIndex": 0.001, ...
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2017 <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, ...
# Copyright (C) 2013 Google 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 retain the above copyright # notice, this list of conditions and the ...
''' Copyright (C) 2020-2021 <NAME> <<EMAIL>> Released under the Apache-2.0 License. Client Library for JD SnapShop https://neuhub.jd.com/dev/api/102 https://aidoc.jd.com/image/snapshop.html ''' import os import sys import requests import time import hashlib import pickle import base64 import json #import wx_sdk from t...
import glob import os import os.path import subprocess import sys from typing import Tuple, Generator import git from pymultigit.configs import ConfigOutput, ConfigDebug, ConfigGrep, ConfigPull, ConfigMain DISABLE = ".build.disable" def projects(sort: bool) -> Generator[Tuple[str, str], None, None]: """ t...