text
stringlengths
3.07k
12.6k
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2020 LG Electronics Inc. # SPDX-License-Identifier: Apache-2.0 import logging import re from bs4 import BeautifulSoup from urllib.request import urlopen import fosslight_util.constant as constant logger = logging.getLogger(constant.LOGGER_NAME) def get_do...
""" <Program Name> common_args.py <Author> <NAME> <<EMAIL>> <Started> Mar 09, 2018 <Copyright> See LICENSE for licensing information. <Purpose> Provides a collection of constants that can be used as `*args` or `**kwargs` to argparse.ArgumentParser.add_argument() for cli tools with common command line ...
from klotan.criteria import ( args_to_string, expected, is_type, equals, regex, accept, reject, ) from klotan.exceptions import ValidationError from typing import Pattern import re # TODO: Handle criteria exception class CriteriaResult: def __init__(self, criteria, *kargs, **kwargs): ...
"""Contains entities for scheduling-app.""" import calendar from dataclasses import dataclass, field import datetime from random import randint from typing import Any, Dict, List, Tuple import numpy as np @dataclass(eq=True) class Employee: """Class for an employee. Attributes: - name(string) : Name of...
from random import uniform class Personagem: def __init__( self, nome, vida, p_ataque, p_defesa ): # definir características dos personagens self.nome = nome self.vida = vida self.p_ataque = p_ataque self.p_defesa = p_defesa self.vivo = True def carac(self...
#!/usr/bin/env python from log import * from bs4 import BeautifulSoup as bs MAX_COLS = 32 """ Collect all relevant tables that contain data of interest, and ignore all tables that may not have anything important for data collection. Optionally, allow to specify the extact table by an index value that may be on a ...
# -*- coding: utf-8 -*- """ Created on Mon Jul 8 03:53:27 2019 @author: srishti """ import chatterbot from chatterbot import ChatBot import re from chatterbot.comparisons import levenshtein_distance from chatterbot.comparisons import SynsetDistance import requests import uuid import json import flask import os from w...
from tqdm import tqdm import fire import os import copy import time import numpy as np import scipy as sp import scipy.io import multiprocessing import torch import torch.nn as nn import torch.nn.functional as F from torchvision.datasets import MNIST from model import GAT_MNIST import util to_cuda = util.to_cuda ...
#!/usr/bin/env python3 # coding: utf-8 # Example 29 IoTボタンや温度センサでチャイム音・玄関呼び鈴システム # IoTボタンやIoT温度センサが送信するUDPを受信し、IoTチャイムへ鳴音指示を送信する # 接続図 # [IoTボタン] --+---> [本機] ------> [IoTチャイム] # ボタン操作 | チャイム音 # | # [IoT温度センサ] --+ # 温度値 # 機器構成 # 本機...
#!/usr/bin/env python3 """Unit test for encrypted post which includes the suite of the key exchange (receive public key and email address of agent via POST, send API email address, public key and nonce encrypted by agent public key via GET), the validation (receive symmetrically encrypted nonce, and the symmetric key e...
# -*- coding: utf-8 -*- # Inspired by: # https://docs.djangoproject.com/en/1.9/ref/migration-operations/#runpython # http://clld.org/2015/11/13/glottocode-to-isocode.html from __future__ import unicode_literals from django.db import migrations # A map from iso codes to glottocodes: isoToGlottoMap = { "aae": "arbe1...
import time from datetime import date from Queue import Empty import pytz from dateutil import relativedelta, parser from datetime import datetime class Bug(object): def __init__(self, dictionary): for key, value in dictionary.iteritems(): if 'date' in key and value: dt = datet...
# The example function below keeps track of the opponent's history and plays whatever the opponent played two plays ago. It is not a very good player so you will need to change the code to pass the challenge. def Predict_Player(play_history, num): import pandas as pd import tensorflow as tf import os ...
import tensorflow as tf from keras.utils.layer_utils import count_params import numpy as np from scipy.stats import poisson def evaluate(test_targets, test_preds): res_H, res_A = test_preds p1 = np.mean(np.log(poisson.pmf(test_targets[:, 0], res_H))) p2 = np.mean(np.log(poisson.pmf(test_targets[:, 1], re...
from __future__ import annotations from datetime import datetime from typing import Any, Dict, List, Optional, Union import pydantic import python_on_whales.components.service from python_on_whales.client_config import ( ClientConfig, DockerCLICaller, ReloadableObjectFromJson, ) from python_...
from nltk.corpus import stopwords import string from config import word_values, search_categories from db_utils.db_methods import get_jobs_table punc = [p for p in list(string.punctuation)] stop = stopwords.words('english') + punc + list(word_values.keys()) def categorize_jobs(): categorizer = Categorizer() ...
from django.db import models from django.forms import ValidationError, RadioSelect from django.contrib import admin from cms.extensions import PageExtensionAdmin from djangocms_theme.widgets import TextWidget from djangocms_theme.forms import (ThemeForm, PageThemeForm, GridModelChoi...
# -*- coding: utf-8 -*- try: from lxml import etree print("running with lxml.etree") except ImportError: try: # Python 2.5 import xml.etree.cElementTree as etree print("running with cElementTree on Python 2.5+") except ImportError: try: # Python 2.5 ...
import json import os from PIL import Image import argparse import time import numpy as np import sys import csv layer = None def _prof_summary(report): sums=dict() counts=dict() summary=[] for line in [v for v in report.split('\n') if v]: row = [v for v in line.split(' ') if v] name=row...
import time import random import re import urllib.request, urllib.error, urllib.parse import socket from cwbot.modules.BaseChatModule import BaseChatModule from cwbot.common.kmailContainer import Kmail _url = "http://sourceforge.net/projects/cwbot/" _ranks = {'major': 1, 'minor': 2, 'bugfix': 3} def _ver...
"""MobileNetV2""" import torch.nn as nn from model.layers.basic import _ConvBNReLU, InvertedResidual from torch.quantization import QuantStub, DeQuantStub __all__ = ['MobileNetV2', 'get_mobilenet_v2', 'mobilenet_v2_1_0', 'mobilenet_v2_0_75', 'mobilenet_v2_0_5', 'mobilenet_v2_0_35'] class MobileNetV2(nn.Mo...
import json import torch import random import numpy as np from opts import * from model.Model import Model from pycocoevalcap.bleu.bleu import Bleu from pycocoevalcap.rouge.rouge import Rouge from pycocoevalcap.cider.cider import Cider from pycocoevalcap.meteor.meteor import Meteor from torch.utils.data import DataLoad...
#!/usr/bin/env python # -*- coding: utf-8 -*- # test_ray.py # Copyright (c) 2017-2019, <NAME> # # This file is part of the cameratransform package. # # cameratransform is free software: you can redistribute it and/or modify # it under the terms of the MIT licence. # # cameratransform is distributed in the h...
import operator import pytest from ...primitives import Int, Str, Any from ...containers import List from ...geospatial import ImageCollection from ...identifier import parameter from .. import MaskedArray, Array, DType, Scalar import numpy as np from ...core import ProxyTypeError arr_fixture = [[1, 2], [3, 4]] m...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User class ApplicationForm(models.Model): name = models.CharField(max_length=50, verbose_name=u"名稱") scan_file = models.FileField(null=True, blank=True, verbose_name=u"申請表檔案", upload_to="appform_fi...
#!/usr/bin/env python3 ''' A basic script that is used to fetch and update defined repositories(YAML format) into an OpenGrok source location. The main feature is (compared to running it in crontab) is that it provides an easy-to-read and easy-to-use YAML configuration file that even non-operation people or other ser...
import pandas as pd import numpy as np import pandas_datareader as pdr import datetime as dt # Recebe-se uma série de retornos e uma lista de pesos """ # ! Base de testes YEAR = 10 DAYS = 365 * YEAR stocks = ['EEM', 'SPY', 'XLB', 'XLK','XLY'] spy = ['SPY'] endDate = dt.datetime.now() startDate = endDate - dt.timedelta...
#!/usr/bin/env python # -*- coding: utf-8 -*- """First approximation of a simulation models to be used in the framework Simulation Models ----------------- There are a bunch of very simple simulation models to demonstrate different functionality. `ExampleWaterSupplySimulation`: simulation only, no assets `ExampleWa...
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import dash_table import statistics import plotly.graph_objects as go import plotly.express as px import statistics def getNumberOfCategories(): return len(df['category'].value_counts()) def getAvgRating(): ...
__doc__ = """ Test scripts for rotation kernels in Elastica Numpy implementaiton """ # System imports import numpy as np import pytest from numpy.testing import assert_allclose import sys from elastica._rotations import ( _generate_skew_map, # noqa _get_diag_map, # noqa _get_inv_skew_map, # noqa _ge...
#!/usr/bin/env python3 ## ## Copyright(c) 2019-2021 Qualcomm Innovation Center, Inc. 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; either version 2 of the Licen...
import numpy as np import matplotlib import matplotlib.pyplot as plt class BenchmarkSoftsortBackwardsResultsParser: r''' Parses an individual results (i.e. log) file and stores the results. ''' def __init__(self): self.epochs = None self.loss = None self.spearmanr = None ...
"""Apply rules to process datalines.""" import os import io import shutil from pathlib import Path from .constants import ( BACKUPS_DIR_NAME, CONFIGFILE_CONTENT, CONFIGFILE_NAME, DATADIR_NAME, DATADIR_RULEFILE_CONTENTS, DATADIR_RULEFILE_NAME, ROOTDIR_RULEFILE_CONTENTS, ROOTDIR_RULEFILE_...
""" some common funcs for the tests """ import os import re import sys import tempfile import time import json from argparse import Namespace from distutils.spawn import find_executable from typing import Any from typing import Dict from typing import List from typing import Tuple from typing import Optional import l...
""" Full assembly of the parts to form the complete network """ import torch import torch.nn as nn import torch.nn.functional as F from models.conv2d_mtl import Conv2dMtl, ConvTranspose2dMtl class DoubleConv(nn.Module): """(convolution => [BN] => ReLU) * 2""" def __init__(self, in_channels, out_channels, mi...
from PIL import Image, ImageDraw, ImageColor, ImageFont import matplotlib.pyplot as plt import numpy as np import string import random import json import generate_codecharts as gc import os # FIXED parameters text_color = ImageColor.getrgb("white") font_type = "Arial.ttf" px_pt_ratio = 20/29 # according to our image ...
import os import numpy as np # keras from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import load_model # cho, jung, jong & total chosung = list("ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ") # 19개 jungsung = list("ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ") # 21개 jongsung = list("_ㄱㄲㄳㄴㄵㄶㄷ...
"""Utility methods for gruut""" import base64 import itertools import logging import os import re import typing from enum import Enum from pathlib import Path import gruut_ipa from .const import REGEX_MATCH, REGEX_PATTERN _DIR = Path(__file__).parent _LOGGER = logging.getLogger("gruut.utils") # --------------------...
import torch import torch.nn as nn import torchvision from python_developer_tools.cv.bases.channels.channels import ChannelShuffle def Conv3x3BNReLU(in_channels,out_channels,stride,groups): return nn.Sequential( nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=strid...
# Copyright (c) 2021 Baidu.com, Inc. 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 l...
import os import sys import tempfile from pathlib import Path from shutil import rmtree import pytest try: from h5pyd._apps.hstouch import main as hstouch from hsds.hsds_app import HsdsApp with_reqd_pkgs = True except ImportError: with_reqd_pkgs = False def set_hsds_root(): """Make required HSD...
''' Descripttion: version: Author: Shicript Date: 2021-06-17 09:58:56 LastEditors: Shicript LastEditTime: 2021-06-17 11:57:57 ''' import json import torch import transformers import numpy as np from transformers import BertModel, BertTokenizer from tokenizers import BertWordPieceTokenizer from .utils import * mode...
# Copyright (c) 2017-2019 Cloudify Platform 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 # # Unless required ...
import os import sys import argparse import torch from torch.utils.data import DataLoader from tqdm import tqdm import numpy as np sys.path.append(os.path.join(os.path.dirname(__file__), "../../src/")) # add the path to the DiffusionNet src import diffusion_net from human_segmentation_original_dataset import HumanSeg...
import os import matplotlib as mpl import torch import torchvision from data_management import Permute, load_ct_data from networks import RadonNet # ----- load configuration ----- import config # isort:skip # ----- global configuration ----- mpl.use("agg") device = torch.device("cuda:0") torch.cuda.set_device(0) ...
import re import os import time import subprocess import collections import colorama colorama.init() class GitRepoStatus( list ): _rex_log_commit_oneline = re.compile("^[a-z0-9]{7}\s.*$") _rex_status_oneline = re.compile("^[a-zA-Z0-9\s]{2}\s.*$") def __init__( self, path, git_executa...
# -*- coding: utf-8 -*- from scrapy import Request from scrapy.spiders import Spider from one.items import OneQuoteItem from one.items import OneArticleItem from one.items import OneQuestionItem import re class QuoteSpider(Spider): """ 「ONE · 一个」 每日一句、每日一图爬虫 每日一句: 爬取的内容有期号、句子、发布日期 每日一图: ...
import pandas as pd import csv import glob import os from pathlib import Path import xlrd from money import Money def get_path(): return str(Path().absolute()) + "/" def convert_to_csv(output_file_name,my_file, my_sheet_name="Sheet1",my_index=False): wb = xlrd.open_workbook(str(my_file), logfile=open(os.dev...
#!/usr/bin/env python3 # # Copyright 2014 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """JSONRPC-related utilities.""" import socket import socketserver import threading import time import unittest import jsonrpcl...
from src.core import Player from src.utils import transform_frame, discount_rewards import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical PLAYER_COLOR = (31, 120, 10) # dark green class Agent(Player): # TODO: add n_size to initializ...
# GPS P code construction # # Copyright 2014 <NAME> import numpy as np chip_rate = 10230000 code_length = chip_rate*86400*7 def x1a_shift(x): return [x[11]^x[10]^x[7]^x[5]] + x[0:11] def x1b_shift(x): return [x[11]^x[10]^x[9]^x[8]^x[7]^x[4]^x[1]^x[0]] + x[0:11] def x2a_shift(x): return [x[11]^x[10]^x[9]^x[8]...
import csv import random class BTreeNode: """ 二叉树结点 """ def __init__(self, left, right, index, key, leftindex, rightindex): """ 二叉树结点 Args === `left` : BTreeNode : 左儿子结点 `right` : BTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- __author__ = 'andyguo' import collections from dayu_path.plugin import DayuPathPlugin, DayuPath def get_configs(self, disk_type='publish'): ''' 内部的解析分析方法。 返回初步分析的大致结果: * db_config_orm = 对应的数据库结构orm * storage_orm = 对应的STORAGE orm * project_orm...
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for sdk_update.py.""" import exceptions import mox import os import subprocess import sys import tempfile import uni...
import csv import numpy as np import matplotlib import matplotlib.pyplot as plt from scipy.interpolate import interp1d import datetime as dt from typing import List import argparse #---------------------------------Functions-----------------------------------# def toCurrents(charges: List): for i in range(len(cha...
# Codes borrowed and modified from Stanford CS224W colabs import torch import torch_scatter import torch.nn as nn import torch.nn.functional as F from torch_geometric import nn as pyg_nn import torch_geometric.utils as pyg_utils from torch import Tensor from typing import Union, Tuple, Optional from torch_geometric....
""" Patched version of tools from SymPy which handle matrices correctly. """ from __future__ import print_function, division from sympy.core import Basic, Mul, Add, Symbol from sympy.core.containers import Tuple from sympy.core.compatibility import iterable from sympy.utilities.iterables import numbered_symbols, order...
from argparse import ArgumentParser import numpy as np import tensorflow as tf from ..mechanics.pong import Pong, random_sign, S from ..mechanics import constants as c from ..utils.tf_machinery import NeuralNetwork from ..utils import common class ImitationLearner: """Learn by imitating an expert.""" def ...
from datetime import datetime, timedelta import subprocess import logging import os from math import log10, floor from flask import Flask, current_app from flask.ext.sqlalchemy import SQLAlchemy from jinja2 import FileSystemLoader from werkzeug.local import LocalProxy import yaml from flask.ext.cache import Cache fr...
from flask import Flask from flask import render_template from flask import request from flask import make_response from flask import session app = Flask(__name__) app.secret_key = '<KEY>' @app.route('/') def index(): return render_template('index.html') @app.route('/iniciarTest', methods=['POST']...
import math from functools import reduce import numpy as np import torch from torch.nn.modules.module import _addindent class Stats(object): def __init__(self, group, items): self._stats = [] self._group = group self._items = items def add(self, tup): if len(tup) != len(self....
import ast from typing import cast from typing import Iterable from typing import List from typing import Tuple from typing import Type from typing import Union from tokenize_rt import Offset from tokenize_rt import Token from pyupgrade._ast_helpers import ast_to_offset from pyupgrade._ast_helpers import is_name_attr...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import getopt import os import magic from tabulate import tabulate __version__ = '0.0.3' class Ext: def __init__(self, *args, **kwargs): self.table = kwargs.get('table', False) self.mime_type = kwargs.get('mime_type', False) self.mi...
import itertools from Bio import SeqIO from Bio import pairwise2 import Bio.PDB.PDBParser from util import open_file from util import message ONECODE = {'ALA':'A', 'CYS':'C', 'ASX':'B', 'GLU':'E', 'ASP':'D', 'GLY':'G', 'PHE':'F', 'ILE':'I', 'HIS':'H', 'LYS':'K', 'XLE':'J', 'MET':'M', 'LEU':'L'...
#!/bin/env python3 ########## imports ########## import sys import pathlib # enable modules from the .build folder to be imported directory = pathlib.Path() sys.path.append ( str(directory) + "/.build" ) from base_classes import * from config import * ########## classes ########## def get_dependencies (component_...
# -*- coding: utf-8 -*- """ Created on Fri Mar 18 14:44:30 2022 @author: jstra """ import numpy as np class Vector: def __init__(self, components, units=None): self.components = np.array(components) self.units = units def __str__(self): if self.units is None: retur...
import numpy as np from collections import OrderedDict import os import glob import cv2 import torch import torch.utils.data as data import torchvision.transforms as transforms from PIL import Image rng = np.random.RandomState(2020) class DataLoader(data.Dataset): def __init__(self, video_folder, transform, time_...
""" Script to make plots for the loss weight quality experiments of the "Simplifying Loss Weighting" paper. """ import os import argparse import json import glob from typing import Dict, Any import matplotlib.pyplot as plt DATASETS = [f"MTRegression{n}" for n in [2, 10, 20, 30, 40, 50]] NUM_TASKS = { "MTRegress...
import pygame import sys import random import math import os os.environ['SDL_VIDEO_WINDOW_POS'] = "20,20" SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) class Util(): def intersects(self, a, b, c, min, max): disc = b ** 2 - 4 * a * c if disc...
""" LSLGA.groups ============ Code to do construct various group catalogs. """ from __future__ import absolute_import, division, print_function import os import time import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set(style='ticks', font_scale=1.4, palette='Set2') PIXSCALE = 0.262 def...
### # Discriminative Voxel-Based ConvNet Training Function # <NAME>, 2016 import argparse import imp import time import logging import math import os import numpy as np from path import Path import theano import theano.tensor as T import theano.sandbox.cuda.basic_ops as sbcuda import lasagne # import sys # sys.pa...
""" # GitHub examples repository path: RadioTestSets/Python/RsInstrument Created 2022/04 Author: Jahns_P Version Number: 2 Date of last change: 2022/04/11 Requires: R&S CMA180, FW 1.7.20 or newer and adequate options Installed VISA e...
#! /usr/bin/python2 # -*- coding: utf-8 -*- from __future__ import print_function import os import logging import argparse from iterative_deepening import IterativeDeepening, ERR_MESSAGE, State, Searchable class Domino(object): def __init__(self, index, content): self.index = index self.content = content ...
#!/usr/bin/python3 import argparse import itertools import os import pprint import sys import yaml from PIL import Image, ImageDraw import bs4 THUMB_MARGIN = 10 def get_polys(html): with open(html) as f: soup = bs4.BeautifulSoup(f.read(), features="html5lib") out = {} for a in soup.find_all("area"): ...
import lshlink as lsh import numpy as np import matplotlib.pyplot as plt from collections import defaultdict from sklearn import datasets from scipy.cluster.hierarchy import dendrogram, linkage, cophenet from scipy.spatial.distance import pdist from functools import reduce, lru_cache import datetime import pickle impor...
# -*- coding: utf-8 -*- """ =============================================================================== Class representation of atom bonds (:mod:`sknano.core.atoms._bonds`) =============================================================================== .. currentmodule:: sknano.core.atoms._bonds """ from __future...
import sys import os import os.path import shutil import glob import re from datetime import date from http.server import HTTPServer, SimpleHTTPRequestHandler from jinja2 import Environment, FileSystemLoader BASE=os.path.expanduser('~/soapbox') PAGES_DIR='pages' POSTS_DIR='posts' TEMPLATES_DIR='templates' STATIC_DIR...
import base64 import os import re import time import requests from selenium import webdriver from selenium.webdriver import DesiredCapabilities from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By # 下载图片 def request_do...
import io, os, sys import argparse import jinja2 import jinja2.loaders from . import __version__ import imp, inspect from .context import read_context_data, FORMATS from .extras import filters class FilePathLoader(jinja2.BaseLoader): """ Custom Jinja2 template loader which just loads a single template file """...
# -*- coding: utf-8 -*- # Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FIWARE project. # # 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: # # htt...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib import ticker from matplotlib.legend_handler import HandlerTuple from matplotlib.transforms import Bbox from matplotlib.textpath import TextPath from pandas_ods_reader import read_ods def plt_clean_legend(): original = plt.gc...
""" Copyright 2019 Samsung SDS 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 ...
import json import pickle import re import threading import time from os import environ import pytest from httpbin import app as httpbin from PIL.PngImagePlugin import PngImageFile from requests import exceptions from requests.auth import HTTPBasicAuth from remix import sessions from remix.clients import HttpBin from...
import math import os import warnings from glob import glob from PIL import Image, ImageOps, ImageFile, ImageFilter from numpy.random import randint from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.preprocessing.image import load_img from nima.config import INPUT_SHAPE, AVA_DATASET_...
""" common estimator (metric) utils to rank different networks (architecture subsets of a super network) """ import torch from uninas.methods.abstract import AbstractMethod from uninas.models.networks.uninas.search import SearchUninasNetwork from uninas.training.trainer.simple import SimpleTrainer from uninas.optimiza...
""" I solved this one manually first. Since this is an assembly-like language, many of the operations 'merge' down into simpler operations/if statements. `mul x 0` `add x z` Is just setting x = z, for example. The trick is figuring out that there are two kinds of computational blocks. The input is a number, ...
# coding=utf-8 # Copyright 2022 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...
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (c) 2019 HERE Europe B.V. # # SPDX-License-Identifier: MIT # License-Filename: LICENSE # ############################################################################### # UTILS import gzip import jso...
import inspect import json import os from typing import Optional import pytest from jury import Jury, load_metric from tests.jury import EXPECTED_OUTPUTS _TEST_METRICS = [ load_metric("accuracy"), load_metric("bertscore", compute_kwargs={"model_type": "albert-base-v1", "device": "cpu"}), load_metric("ble...
# # Copyright (c) 2019-2020, NVIDIA CORPORATION. # Copyright (c) 2019-2020, BlazingSQL, 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...
import math import random import mathutils from src.main.Provider import Provider from src.utility.BlenderUtility import get_bounds class UpperRegionSampler(Provider): """ Uniformly samples 3-dimensional value over the bounding box of the specified objects (can be just a plane) in the defined upper dire...
from acltracker import acl_db from acltracker import device_session from acltracker import acl import datetime import logging import re import time #testing def inventory_devices(): if test: device_list = [{'host_name': 'BIG-Site/admin', 'ip': '10.20.0.1', 'model': None, 'fk_conn_status': 1, 'iddevice': 121, 'ch...
import jax import jax.numpy as jnp from typing import List from abc import ABCMeta, abstractmethod __all__ = [ "Transform", "TransformChain", "ToTensorTransform", "RandomUniformDequantizeTransform", "RandomHFlipTransform", "RandomCropTransform", "RandomResizedCropTransform", ] class Tran...
import numpy as np import pandas as pd import pdb from copy import deepcopy as COPY def reduce_recomb_rate_info(rcmb_rate_info, bim_SNP_positions): rcmb_rate_intervals = rcmb_rate_info["Position(bp)"].to_numpy() # INDEXING NOTE: Not subtracting one from "SNP_pos_rcmb_interval_map" returns the closest ind...
import json import re import time from typing import Dict import falcon import sqlite3 from constants import ERROR_MSG_AUTHORIZATION_FAIL, ERROR_MSG_DATA_VALIDATION_FAIL valid_locs = set(range(14)) # Obviously this can be made to specifically grab members worlds valid_worlds = {n for n in range(301, 581)} def hook...
#------------------------------------------------------------------------------- # Micro Server - HTTP request and response types # # Copyright (c) 2022 <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 o...
import sys def create_hsv_filter(h, s, v): return "TargetFilter filter = new HSVFilter(new Range({}, {}), new Range({}, {}), new Range({}, {}));".format(h[0], h[1], s[0], s[1], v[0], v[1]) def create_fov(h_degrees, v_degrees): return "FOV fov = new FOV({}, {});".format(h_degrees, v_degrees) def create_resolu...
#!/usr/bin/env python3 """ gftools lang-support Adds language support metadata to METADATA.pb files. Usage: # Standard usage. Does not overwrite existing data. gftools lang-support -l ./lang/ ./ofl/noto*/METADATA.pb # Generate a report with insights about data and potential metadata holes. gftools lang-support -l ....
""" What idr needs: cameras.npz scale_mat_{i} world_mat_{i} image mask """ import argparse import os import open3d as o3d import sys from tqdm import tqdm import trimesh from scipy.spatial.transform import Rotation import cv2 import numpy as np # from src.datasets.scenenet import SceneNet f...
import discord import secrets from random import randint from aiosmtplib.errors import SMTPException from email_sender import send_email from registration_mail_template import REGISTRATION_MAIL_TEMPLATE from welcome_msg_template import WELCOME_MSG_TEMPLATE from course_specification_template import COURSE_SPECIFICATION_...