text
stringlengths
3.07k
12.6k
# 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...
import uvicorn import argparse import os import collections import multipart_stream args = None EMPTY_RESPONSE = { 'type': 'http.response.body', 'body': b'' } def gen_header(status=200, content_type=None, custom_headers=[]): obj = { 'type': 'http.response.start', 'status': status, ...
import os from dataclasses import asdict, dataclass, field, fields from logging import getLogger from typing import ClassVar, Dict, List, Union, cast, no_type_check from . import LOGGER_NAME logger = getLogger(LOGGER_NAME) @dataclass class AbstractConfig: config_root: ClassVar[str] = "base" def __post_init...
# This is where the classes and objects are defined import random class Game: def __init__(self, difficulty, length, cave_map): self.cave_map = cave_map self.difficulty = difficulty self.length = length class Condition: def __init__(self, name, damage, ac_reduction, dura...
import os import numpy as np import hf from hf.builders.dataset_builder import DatasetBuilder def do_preprocessing(dataset, indices): label_seg_utils = dataset.kitti_utils.label_seg_utils print("Generating label segs in {}".format(label_seg_utils.label_seg_dir)) # Generate all mini-batches, this can ...
""" Benchmark presigned zarr uploads using dummy data. The time taken to complete the upload is included, so if the API server is calculating checksums that will factor into the performance. At the time this was written a temporary API server was stood up that did not calculate checksums specifically to determine how ...
import matplotlib.pyplot as plt import numpy as np # globals MIN_REQUEST = 0 MAX_REQUEST = 199 IORequests = [] head_ptr = 0 # 53 # outputs sequence = [] total_head_mov = 0 def calc_head_mov(): total = 0 for i in range(1, len(sequence)): total += abs(sequence[i] - sequence[i - 1]) return total ...
from datetime import date as pydate from datetime import datetime from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, \ SubmitField, HiddenField, IntegerField, \ SelectField, FormField, widgets, FileField, \ TextAreaFi...
import os from base64 import b64decode, b64encode from enum import Enum from ..core.Simple import Simple from ... import helper class TmplType(Enum): table = "0" base64 = "1" html = "3" text = "4" scheme = "6" extension = "9" # todo добавить остальные типы макетов и их сериализацию clas...
import tensorflow as tf import numpy as np # 一个字典,隐射一个数字到其二进制的表示 # 例如 int2binary[3] = [0,0,0,0,0,0,1,1] int2binary = {} # 最多8位二进制 binary_dim = 8 # 在8位情况下,最大数为2^8 = 256 largest_number = pow(2, binary_dim) # 将[0,256)所有数表示成二进制 binary = np.unpackbits( np.array([range(largest_number)], dtype=np.uint8).T, axis=1) # ...
# -*- coding: utf-8 -*- """ @author: datamonday """ import math import numpy as np from sklearn.preprocessing import MinMaxScaler, StandardScaler #################### 说明 ########################## # 为了可读性, 所有numpy和math库的函数均使用.x()调用, # # 这种方式在实际测试中相比直接函数x()调用耗时 # #################################################...
from sklearn import datasets import matplotlib.pyplot as plt import numpy as np from math import ceil from math import sqrt import pandas as pd np.random.seed(0) def load_data(): boston = datasets.load_boston() X = boston.data y = boston.target features = boston.feature_names retur...
#!/usr/bin/env python # Copyright 2017 Johns Hopkins University (author: <NAME>) # Apache 2.0 """ This script prepares the training and test data for CIFAR-10 or CIFAR-100. """ from __future__ import division import argparse import os import sys parser = argparse.ArgumentParser(description="""Converts train/test d...
""" Code for serializing a modulestore XBlock to OLX suitable for import into Blockstore. """ import logging import os from collections import namedtuple from lxml import etree from . import adapters log = logging.getLogger(__name__) # A static file required by an XBlock StaticFile = namedtuple('StaticFile', ['name...
import gc import time import diffrax import equinox as eqx import fire import jax import jax.experimental.ode as experimental import jax.nn as jnn import jax.numpy as jnp import jax.random as jrandom import torch import torchdiffeq class FuncTorch(torch.nn.Module): def __init__(self): super().__init__() ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 14 14:45:53 2022 @author: fatemehmohebbi """ from Bio import Phylo import networkx as nx import numpy as np import pandas as pd from scipy import sparse import scipy.special as sc import matplotlib.pyplot as plt import pydot from networkx.drawing.n...
import os import pdb import random from random import randrange import gin import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import torch from loader.episode import Episode from meta_dataset.data import config from meta_dataset.data import dataset_spec as dataset_spec_lib from meta_dataset.dat...
__author__ = 'H' bl_info = { 'name': 'Caffe-Gui-Tool', 'author': '<NAME>', 'location': 'Node view - Properties panel', 'category': 'Node View' } # To support reload properly, try to access a package var, # # if it's there, reload everything if "bpy" in locals(): import imp imp.reload(IOwritepro...
# Import libraries import cv2 import numpy as np import os from PIL import Image, ImageEnhance import shutil def Cria_dir(y): # Funcao responsavel pela criacao # de diretorios baseados em um diretorio base (base_dir) # Define o diretório base base_dir = os.path.dirname(__file__) # Cria um novo diretório ca...
from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import shutil import random import numpy as np from glob import glob import cv2 def preprocess(image): # use ImageNet preprocessing (since ResNet is trained on it) #scale to 256 #center ...
import csv import os def menu(username="@harshmall", products_count=100): # this is a multi-line string, also using preceding `f` for string interpolation menu = f""" ----------------------------------- INVENTORY MANAGEMENT APPLICATION ----------------------------------- Welcome {username}! There are {products...
import logging import subprocess import tempfile import typing import const import models import schemas import os import re import util _LOGGER = logging.getLogger(__name__) class WGAlreadyStartedError(Exception): pass class WGAlreadyStoppedError(Exception): pass class WGPermissionsError(Exception): ...
from sstcam_simulation.data import get_data from sstcam_simulation.utils.photon_incidence_angles import PhotonIncidenceAnglesSiPM import numpy as np import pandas as pd from matplotlib import pyplot as plt from astropy import units as u from scipy.interpolate import interp1d from IPython import embed def interpolate_...
import pandas as pd import itertools as it import seaborn as sns import numpy as np from pymea import matlab_compatibility as mc from matplotlib import pyplot as plt from matplotlib import mlab as mlab import random from datetime import datetime, timedelta from pymea import supplement_to_plotting as psupp import math f...
# This script is part of HSDFinder, which shall be put in the same directory with HSDFinder.py from collections import defaultdict import re import os FILE_ROOT = "" class Pfam: def __init__(self, name, ftype, pf, domain1, value, ipr, domain2): self.name = name self.ftype = ftype self....
import pygame as pg import copy import time from typing import Tuple from collections import namedtuple class MyRect: def __init__(self, size: Tuple[int, int], pic = None, func = None, border_colour = (0,0,0), line_colour = (255,255,255), colour ...
import sys import time import random import uuid from datetime import datetime from memsql_loader.util import apsw_helpers, apsw_sql_utility, super_json as json from memsql_loader.util.apsw_sql_step_queue.task_handler import TaskHandler from memsql_loader.util.apsw_sql_step_queue.time_helpers import unix_timestamp de...
import numpy as np from collections import defaultdict import matplotlib.pyplot as plt def fitness(individual_gen: np.ndarray, target_gen: np.ndarray): """ Calculates the fitness of an individual. :param individual_gen: Individual gen. :param target_gen: T...
import asyncio import inspect import json from dataclasses import dataclass from typing import Any, AsyncIterator, Awaitable, Dict, Sequence from gql.subscription import PROTOCOL, MessageType, OperationMessage from graphql import ExecutionResult, GraphQLError, GraphQLSchema, format_error, parse, subscribe from starlet...
# Main file import cProfile import io import os import pstats import sys sys.path.insert(0, 'src/dt') sys.path.insert(0, 'src/parsing') sys.path.insert(0, 'src/split') from parser import parse_timeprof as parse from dt_sklearn import DT_sklearn from dt_linear import DT_linear from entropy import Split_entropy from au...
import pandas as pd import bokeh.plotting as bp from bokeh.models import HoverTool, ColumnDataSource, Legend """ Adapted from https://stackoverflow.com/a/40231779 """ tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, ...
from __future__ import unicode_literals from django.contrib.auth.forms import AuthenticationForm from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, HTML, Field # from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions from authtools im...
""" Programming Project 12 <NAME> 15863 """ import cmath from cmath import sin, cos, exp from math import sqrt, pi, asin from random import random import numpy as np N = 3 psi = np.ndarray((2 ** N, 1), complex) # N-qubit register comp_state = 0 for i in range(2 ** N): if i == comp_state: psi[i] = 1 ...
# Copyright 2018 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
import cv2 import numpy as np from procgen import ProcgenEnv from .utils import ImgProcessor from .base import BaseEnv class _Procgen(BaseEnv): """Procgen environment. Args: name (str): name of environment in Procgen games. render (bool): parameter that determine whether to render. g...
from queue import Queue from Poem.poem import models as poem_models from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication class Tree(object): class Node: def __init__(self, nodename): self._nodena...
# modify from sklearn (0.22.1) import numpy as np from .utils.multiclass import type_of_target from .utils.validation import check_consistent_length, column_or_1d, assert_all_finite from .utils.extmath import stable_cumsum def precision_recall_curve(y_true, probas_pred, pos_label=None, sam...
"""The machinery behind the constraints honoring reporting and enforcement.""" import enum from operator import attrgetter from typing import Callable, Dict, List, Type from pytest import ExitCode, PytestWarning from .constraints import ConstraintsGroup MAGIC_MARK = "honors" OPT_MARKDOWN_REPORT = "honors_report_mar...
import cv2 from cv2.ximgproc import thinning import numpy as np from myPackage import tools as tl from os.path import join, basename, splitext, altsep, exists from numba import jit @jit def cleanImage(bin_img, name, plot= False, path= None): print("Cleaning image...") n = 3 n_2 = 3 iter = 2 #3 iter...
""" Copyright 2020 The OneFlow 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 applicable law or agr...
import matplotlib import matplotlib.pyplot as plt import numpy as np __all__ = [ "cartesian", "barycentric", "contour", "contourf", "scatter", ] def cartesian(points): """Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the ...
import pandas as pd import matplotlib.pyplot as plt import numpy as np plt.style.use('ggplot') #### make a funcion that lets you specify a few parameters and calculates the payoff # S = underlying price # K = strike price # Price = premium paid for option def long_call(S, K, Price): # Long Call Payoff = max(un...
from __future__ import absolute_import from __future__ import unicode_literals import math import six from django.db import models from corehq.apps.products.models import SQLProduct from corehq.form_processor.models import TruncatingCharField @six.python_2_unicode_compatible class StockReport(models.Model): form_...
''' Converted from Plexon.h by ctypesgen on 2012-06-04 ''' from ctypes import * # /home/james/code/bmi3d/riglib/plexon/docs/Plexon.h: 410 class struct_PL_FileHeader(Structure): pass struct_PL_FileHeader.__slots__ = [ 'MagicNumber', 'Version', 'Comment', 'ADFrequency', 'NumDSPChanne...
# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ) # # 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 #...
import datetime import platform import signal import sys import time from argparse import ArgumentParser import pprint from typing import NamedTuple from urllib.parse import urlparse import threading from queue import Queue try: from elasticsearch import Elasticsearch except: print( "ERROR: elasticsear...
from flask import g, make_response, request, url_for from . import ussd from .airtime import Airtime from .practitioner import SelectPractice from .deposit import Deposit from .home import LowerLevelMenu from .register import RegistrationMenu from .utils import respond from .withdraw import WithDrawal from ..models im...
# # Copyright (c) 2015-2019 <NAME> <tflorac AT ulthar.net> # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE...
import json import os #pip install git+https://github.com/ericsomdahl/python-bittrex.git from bittrex.bittrex import Bittrex, API_V2_0, API_V1_1, BUY_ORDERBOOK, TICKINTERVAL_ONEMIN import sys import os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) import Config my_bittrex ...
import numpy as np import numba import umato.distances as dist from umato.utils import ( tau_rand_int, adjacency_matrix, clip, rdist, ) def get_CE(P, Y, d_squared, a, b): Q = pow(1 + a * d_squared ** b, -1) loss = -P * np.log(Q + 0.001) - (1 - P) * np.log(1 - Q + 0.001) return loss.sum() /...
#!/usr/bin/env python # Copyright 2019 Xilinx 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 ...
import argparse import collections import logging import sys import threading import epics import pandas logger = logging.getLogger(__name__) class Bridge: """ A simple class that maps model variables from a CSV file with their equivalent real Process Variables (PVs) from the real machine. Paramete...
import os import re import sys import glob from utils import Translator with open('key.txt') as file: lines = file.readlines() for line in lines: if not '#' in line: key = line.strip(); translator = Translator(key=key) def vid_down(url): os.system("youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m...
# Adopted from https://github.com/mit-han-lab/once-for-all: # Once for All: Train One Network and Specialize it for Efficient Deployment # <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # International Conference on Learning Representations (ICLR), 2020. # ------------------------------------------------------------------ # Ma...
""" Copyright 2019 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distribut...
#!/usr/bin/env python3 import sys import os import re import argparse import json from delphin.interfaces import ace from delphin.mrs import xmrs, simplemrs, penman from delphin.mrs.components import var_sort from delphin import itsdb Triple = penman.penman.Triple codec = penman.XMRSCodec(indent=2) def run(args): ...
import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.nn import init from network import utils as utils class MultiAttn(nn.Module): def __init__(self, in_dim, head_num=10): super(MultiAttn, self).__init__() self.head_dim = in_dim // head_num self....
#!/usr/bin/python3 from threading import Semaphore, Thread from time import sleep from random import random,choice pisos = [i for i in range(0,5)] # Nombres y apellidos: De la lista del semestre 2019-1 nombres = ["Alberto", "Alejandro", "Andrew", "Ángel", "Anibal", "Ascary", "Blaise", "Brenda", "Cristian", ...
#! /usr/bin/env python # <NAME> # February 14, 2018 # Vanderbilt University """ Compilation of useful functions and definitons for ECO, RESOLVE A and B galaxy redshift surveys """ __author__ =['<NAME>'] __copyright__ =["Copyright 2017 <NAME>, eco_utils"] __email__ =['<EMAIL>'] __maintainer__ =['<NAME>'] __...
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Layer, Dense, Embedding, TimeDistributed, Dropout # from tensorflow_core.python.keras.layers import Layer, Dense, Embedding, TimeDistributed, Dropout from tensorflow.python.keras.layers.dense_attention import BaseDenseAttention def ...
import torch import torch.nn as nn from torchvision.models import mobilenet import torch.utils.model_zoo as model_zoo from .rutils import register class SepConvBNReLU(nn.Sequential): def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, expand_ratio=1): padding = (kernel_size - 1) // 2 ...
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, reduce, repeat from typing import Sequence, Tuple, Callable from torch.nn import Module, ModuleList, Linear, LayerNorm, GroupNorm, Conv2d class ConditionalNHWC(Module): """ Conditional NHWC layer. """ de...
from . import ( compare_values, get_dict_value, ParserLiterals, CollectionFunctions, ) class VariableProcessor(object): """ The VariableProcessor is responsible for evaluating the declared variables in a Rule. It parses the **variables** key of the rule and evaluates each variable. It ...
import time import cv2 import numpy as np from simple_playgrounds.engine import Engine from spg_overlay.fps_display import FpsDisplay from spg_overlay.misc_data import MiscData from spg_overlay.score_manager import ScoreManager from spg_overlay.save_data import SaveData from spg_overlay.sensor_disablers import Enviro...
""" Convert ARM32 instruction into human readable form suitable to be processed by an assembler. """ import struct from typing import List, Tuple, Set from CpuA32 import opcode_tab as a32 from Elf import enum_tab def _EmitReloc(ins: a32.Ins, pos: int) -> str: if ins.reloc_kind == enum_tab.RELOC_TYPE_ARM.JUMP24: ...
""" Author: <NAME> Date: 30th August 2020 License: MIT License =================================================================== Implementation of function mysql_2_csv() in Python: it exports csv file from mysql pydb param host: host name param user: user name param password: password param file_path: file path to s...
# -*- coding: utf-8 -*- # # ----------------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this softw...
import io from json import load import boto3 import requests import pandas as pd from kauffman import constants as c from zipfile import ZipFile import kauffman.constants as c def file_to_s3(file, s3_bucket, s3_file): """ Upload a local file to S3. file: str location of the local file s3_buck...
import torch import torch.nn as nn import torch.optim as optim import os import numpy as np from tqdm import tqdm import re class MLP(nn.Module): def __init__(self, vae_file_name, hidden_1, hidden_2): super(MLP, self).__init__() # vae_file_name form: VAE_??.pkl latent_num = in...
import colconfig width_selectors = dict() file = open("columns.css", "w") minify = colconfig.minify def block_start(prelude, indent = ""): if minify: prelude = prelude.replace(" > ", ">").replace(" + ", "+").replace(": ", ":").replace(", ", ",") elif indent != "": file.write(indent) file.w...
# Xception model -> 300 classes from keras import layers from keras import models from keras import backend as K from keras.optimizers import Adam from keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint, CSVLogger from sklearn.model_selection import train_test_split from keras.preprocessing.image ...
import os import tqdm import argparse from typing import List from .utils import random_filename from tokenizers import Tokenizer, models, decoders from tokenizers.trainers import WordPieceTrainer from tokenizers.normalizers import BertNormalizer from tokenizers.pre_tokenizers import BertPreTokenizer def _split_subse...
from .auxiliary_window import AuxiliaryWindow from ..managers.config_manager import (NonUniquePriority, NonValidPriority, MissingPriority) from tkinter import messagebox import logging import tkinter as tk logdict = {"DEBUG": logging.DEBUG, "INFO": logging.INFO, ...
# -*- coding: utf-8 -*- import os, json from utils import ajax_required from django.http import HttpResponseRedirect, HttpResponse from django.conf import settings from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator from django.core.files.storage import FileSystemStorage ...
from ipywidgets import Widget, widget_serialization from traitlets import Bool, Enum, Instance, Int, Unicode from ._frontend import module_name, module_version class ToneWidgetBase(Widget): _model_module = Unicode(module_name).tag(sync=True) _model_module_version = Unicode(module_version).tag(sync=True) cl...
# Copyright 2022 The jax3d 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 applicable law or agreed to in wr...
from __future__ import absolute_import import math from torch import nn from .DCNv2.dcn_v2 import DCN BN_MOMENTUM = 0.1 def get_simple_net(num_layers, heads, head_conv=256): model = DCN_Detector(heads) # model.init_weights(num_layers) return model def fill_up_weights(layer): """Custom function fo...
from __future__ import print_function import argparse import git import logging import logging.config import os import shutil import sys import tarfile import six from past.builtins import basestring from six.moves.urllib.parse import urlparse, urlencode from six.moves.urllib.request import urlopen from six.moves.url...
# This is a simple inventory program for a small car dealership. print('Automotive Inventory') class Automobile: def __init__(self): self._make = '' self._model = '' self._year = 0 self._color = '...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import ( compat_str, compat_HTTPError, ) from ..utils import ( ExtractorError, find_xpath_attr, ) class NBCIE(InfoExtractor): _VALID_URL = r'http://www\.nbc\.com/(?:[^/]+/)+(?P<id>n?\d+)' _TEST...
#!/usr/bin/env python3 # type: ignore import sys from PySide2.QtGui import QPainter, QIntValidator, QDoubleValidator from PySide2.QtWidgets import ( QApplication, QMainWindow, QWidget, QAction, QHBoxLayout, QVBoxLayout, QGridLayout, QSizePolicy, QLabel, QLineEdit, ) from PySide2...
import os from argparse import Namespace from tqdm import tqdm import time import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader import sys sys.path.append(".") sys.path.append("..") from configs import data_configs from datasets.inference_dataset import InferenceDataset from e...
''' Utility functions for parsing expressions and statements. ''' import re from collections import Counter import sympy from sympy.printing.precedence import precedence from sympy.printing.str import StrPrinter from brian2.core.functions import (DEFAULT_FUNCTIONS, DEFAULT_CONSTANTS, ...
import uuid from logging import getLogger from decimal import Decimal import stripe from enumfields import EnumField from rehive import Rehive, APIException from django.db.models import Q from django.db import models, transaction from django_rehive_extras.models import DateModel from django_rehive_extras.fields import...
""" Please note that this app does *not* demonstrate Flask best practice! It is much better to place views, controllers, configuration files, and the like in their own directories. """ import json import os import sqlite3 from flask import Flask, render_template, request, send_from_directory from flask_api import Fl...
# Python modules import os import sys import subprocess # 3rd party modules try: import packaging.requirements as packaging_requirements except ImportError: print("Please install 'packaging'. You can use this command:") print("pip install packaging") sys.exit() # Note that this code can't assume too...
""" Parses the animethemes api, getting data by title. - load data from cache - animethemes,unavalible = load_cache() - animethemes: list[AnimeThemeAnime] - unavalible: dict[site_name:set[site_id]] - animelist = get_old() - sorted by _fetched_at - organize animethemes into dict by id - start fetching d...
#!/usr/bin/env python3 """ Copyright (c) 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable la...
""" highlight ========= **Module** : ``footer.menus.highlightmenu.py`` Contains menus related to highlighting, like menus for style and lexer. """ from kivy.uix.bubble import Bubble from kivy.properties import ObjectProperty from kivy.uix.button import Button from kivy.extras.highlight import KivyLexer from kivy.uix....
''' BSD Licence Copyright (c) 2017, Science & Technology Facilities Council (STFC) 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 no...
""" Loss.py """ import logging import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from config import cfg def get_loss(args): """ Get the criterion based on the loss function args: commandline arguments return: criterion, criterion_val """ if args.img_wt_los...
# "Colorful Life" from <NAME> # https://github.com/adam-zheleznyak/colorful-life # # Modified by fire-eggs to remove the uses of numpy and matplotlib, # as these are the "display" functions superceded by using the RGB # matrix. # import math from random import random from random import uniform class Hue: """This is a...
import unittest import numpy as np import torch from Utility.Torch import Glimpses class testView(unittest.TestCase): def testBasic(self): """ Tests whether view works """ test_tensor = torch.randn([20, 30, 10]) Glimpses.reshape(test_tensor, 10, [5, 2]) Glimpses.reshape(test_tenso...
# standard scalar transform of continuous variable from collections import namedtuple import numpy as np import pandas as pd from snsynth.preprocessors.data_transformer import BaseTransformer SpanInfo = namedtuple("SpanInfo", ["dim", "activation_fn"]) ColumnTransformInfo = namedtuple( "ColumnTransformInfo", ...
""" Helper functions for probability distributions. """ import os from .cupy_utils import betaln, erf, xp def beta_dist(xx, alpha, beta, scale=1): r""" Beta distribution probability .. math:: p(x) = \frac{x^{\alpha - 1} (x_\max - x)^{\beta - 1}}{B(\alpha, \beta) x_\max^{\alpha + \beta + 1}} ...
''' * * Copyright (C) 2020 Universitat Politècnica de Catalunya. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless requi...
import collections as col from sndict.nesteddict import NestedDict from sndict.utils import list_equal dict_a = col.OrderedDict([ ("key1", "val1"), ("key2", col.OrderedDict([ ("key2_1", "val2_1"), ("key2_2", "val2_2"), ])), ("key3", col.OrderedDict([ ("key3_1", col.OrderedDict...
#!/usr/bin/env python3 import argparse import asyncio from datetime import datetime, timedelta from tempfile import gettempdir from typing import AsyncIterable from datetime import datetime import os from datetime import datetime from utils import evalAgent, getFederatedModel # import yapapi modules from ...
import os import pytz import time from datetime import datetime from distutils.version import LooseVersion import github3.exceptions from cumulusci.core.exceptions import GithubApiError from cumulusci.core.exceptions import GithubApiNotFoundError class BaseChangeNotesProvider(object): def __init__(self, release...
import argparse import numpy as np import cv2 as cv def str2bool(v): if v.lower() in ['on', 'yes', 'true', 'y', 't']: return True elif v.lower() in ['off', 'no', 'false', 'n', 'f']: return False else: raise NotImplementedError parser = argparse.ArgumentParser() parser.add_argument...