text
stringlengths
3.07k
12.6k
# Copyright 2018 - Nokia Corporation # Copyright 2014 OpenStack Foundation # # 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 require...
# Copyright 2020 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 pybreaker import os import json import logging from urllib3.util.url import get_host from .exceptions import ApiCircuitBreakerError, CustomHttpCircuitBreakerError import newrelic.agent import socket class MonitorListener(pybreaker.CircuitBreakerListener): def __init__(self): self.event_name = "cir...
import os from cStringIO import StringIO import tarfile import numpy as np from . import get_data_home from tools import download_with_progress_bar TARGETLIST_URL = ("http://www.astro.washington.edu/users/ivezic/" "linear/allDataFinal/allLINEARfinal_targets.dat") DATA_URL = ("http://www.astro.washi...
# -*- coding: utf-8 -*- import logging import warnings from quixote.errors import TraversalError from vilya.models.project import CodeDoubanProject from vilya.models.pull import PullRequest, merge_pull, close_pull from vilya.models.ticket import Ticket, TicketComment, TicketCommits from vilya.libs.api_errors import ...
import os,csv,re,jieba, math import jieba.posseg as pseg from os import walk def sentlist(in_fname): f = open(in_fname, mode='r', encoding = 'utf-8-sig', errors='ignore') # each sentance s = [] # total sentances sentls = [] for sents in f.read().split(' '): # replace \ufeff sents = sents.repl...
from __future__ import print_function import maya.cmds as cmds import maya.mel as mel from functools import partial import csv import os import pprint iconPath = os.path.join(os.path.dirname(__file__),'icon') manualPath = os.path.join(os.path.dirname(__file__),'manual') def refreshNS(*args): nsLst = [i fo...
# -*- coding=utf-8 -*- #!/usr/bin/python3 import sys import os, argparse import json import xml.etree.ElementTree as ET # 检测框的ID起始值 START_BOUNDING_BOX_ID = 1 # 类别列表无必要预先创建,程序中会根据所有图像中包含的ID来创建并更新 #PRE_DEFINE_CATEGORIES = {} # If necessary, pre-define category and its id #PRE_DEFINE_CATEGORIES = {"aeroplane": 1, "bicyc...
import random import pytest from notcallback.async_ import Promise from notcallback.exceptions import PromiseRejection from notcallback.promise import FULFILLED, PENDING, REJECTED from .suppliers import simple_resolve pytestmark = pytest.mark.filterwarnings('ignore::notcallback.exceptions.UnhandledPromiseRejectionW...
import base64 from collections import OrderedDict from itertools import islice import json import os import random import re import attr import jinja2 from .io import TensorflowDatasetExporter, TensorflowDatasetImporter dir_path = os.path.dirname(os.path.realpath(__file__)) TEMPLATE_FILE = 'via-2.0.6.html' ANNOTATI...
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.contenttypes.fields import GenericRelation from django.db import models from django.urls import reverse from django.utils.functional import cached_property from django.utils.timezone import now from autoimagefield.fields import AutoImageField...
""" Provides enhanced email messaging such as mutlipart html/text emails. """ import re from django.conf import settings from django.core import mail as django_mail from django.core.mail.message import EmailMultiAlternatives from django.utils.html import strip_tags INVISIBLE_HTML_TAGS = ('head', 'style', 'script', 'o...
# Copyright 2019 The TensorFlow 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 applica...
from collections import namedtuple from string import Template import cupy, torch import cupy as cp import torch from torch import nn from torch.autograd import Function from utils.roi_cupy import kernel_backward, kernel_forward import warnings warnings.filterwarnings("ignore") class VGG16RoIHead(nn.Modul...
#!/usr/bin/env python # -*- coding: utf-8 -*- from typing import List import torch import torch.nn.functional as F from torch import Tensor @torch.jit.script def _get_edge_kernel() -> Tensor: d_kernel = torch.tensor( [ [1, 0], [0, -1], ], dtype=torch.float, )....
import os import typing as t import logging import secrets import threading import contextlib from typing import TYPE_CHECKING from datetime import datetime from datetime import timezone from functools import wraps from functools import lru_cache import attr import requests from simple_di import inject from simple_di ...
""" Linked layer structure. """ from __future__ import absolute_import, unicode_literals import attr import io import logging from psd_tools.constants import LinkedLayerType from psd_tools.psd.base import BaseElement, ListElement from psd_tools.psd.descriptor import DescriptorBlock from psd_tools.validators import in_...
from datetime import date, datetime from yamale import validators as val def test_validator_defaults(): """ Unit test the dictionary of default validators. """ assert val.DefaultValidators[val.String.tag] is val.String assert val.DefaultValidators[val.Any.__name__] is val.Any def test_equality()...
""" FastEstimator Apphub parser """ import glob import inspect import json import os import pydoc import re import subprocess import sys import tempfile re_sidebar_title = '[^A-Za-z0-9:!,$%.() ]+' re_route_title = '[^A-Za-z0-9 ]+' re_url = '\[notebook\]\((.*)\)' apphub_md_dir = 'apphub_md' tmp_markdown = os.path.join...
import asyncio import numpy as np from bokeh.plotting import Figure from entropylab.graph_experiment import ( Graph, PyNode, pynode, GraphExecutionType, SubGraphNode, ) async def a(): rest = 0.001 print(f"Node a resting for {rest}") await asyncio.sleep(rest) print(f"Node a finish...
""" symbol_cache --------- symbol cache management """ import pandas as pd import numpy as np import pandas_datareader.data as pdr from pandas_datareader._utils import RemoteDataError from yahooquery import Ticker from pathlib import Path import datetime import sys import os import brownbear as bb ###################...
#!/usr/bin/env python #python imports from falconpy.hosts import Hosts from falconpy.oauth2 import OAuth2 from falconpy.api_complete import APIHarness import json import logging import sys #local imports from Send2HumioHEC import Send_to_HEC as humio import CrowdStrikeDevices2HumioConfig as config def main(): c...
# Copyright 2020 The Flax 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...
# -*- coding: utf-8 -*- """ Utilities that assist in dictionary manipulation Created on Thu Jul 7 21:14:25 2020 @author: <NAME> """ from __future__ import division, print_function, unicode_literals, absolute_import import sys from warnings import warn import math if sys.version_info.major == 3: unicode = str ...
'''Train CIFAR10 with PyTorch.''' import torch.optim as optim import torch.cuda import torch.backends.cudnn as cudnn import torch.utils.data from datasets.dataloader import get_data import os from utils.argument import get_args from utils.metric import MultiLabelAcc, AverageMetric from utils.loss import CostLoss from ...
# Python interface to CEA (Chemical Equilibrium with Applications) # Authors: <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # Original interface code written by <NAME> # Project Caelus, 04 February 2021 import os import shutil import sys import csv import math import numpy as np import time import subprocess import threadin...
import os import sys from PIL import Image import numpy as np import matplotlib.image as img import matplotlib.pyplot as plt import cv2 import tqdm def get_labels_from_json(dir_labels, dir_annotated, format="tif", no_label=False): if not os.path.exists(dir_labels): print("New Label Directory:", dir_labels...
# coding=utf-8 import argparse """ import tensorflow as tf import tensorflow_hub as hub class TextEmbedder: embedder = None def __init__(self): embedder = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/2") def embed(texts): similarity_input_placeholder = tf.placeholder(t...
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with t...
import numpy as np import matplotlib.pyplot as plt import h5py import torch import os from klampt.model.trajectory import Trajectory from klampt.io.loader import save from pdb import set_trace def plot_pushing_error(bg, max_horiz=100): test_data = bg.T.MTEST test_ans = bg.MTestAnswers test_structures = bg....
import torch import torch.utils.data as torch_data import os class dataset(torch_data.Dataset): def __init__(self, src1, src2,src3, tgt, tgtv,tgtpv):#raw_src1, raw_src2, raw_src3, raw_tgt): self.src1 = src1 self.src2 = src2 self.src3 = src3 self.tgt = tgt self.tgtv = tgtv ...
#!/usr/bin/env python # Copyright 2012 Google 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 o...
import argparse from collections import defaultdict from nltk import word_tokenize import os import pandas as pd import torch from transformers import ( MarianTokenizer, MarianMTModel, ) def load_data(args): """ Load data from tsv into pd.DataFrame """ df = pd.read_csv(args.input_file, delimiter="\t")...
import torch import torch.nn as nn import torchvision.models import torch.nn.functional as F from sklearn.cluster import KMeans from sklearn.metrics.pairwise import cosine_similarity from models.backbones import * from models.senet import * from models.activation import * from models.layers import * ''' Modified bac...
from optimizers import Adam from utils import * from shared_noise import * from experiments import get_experiment import ray import gym import parser import argparse import numpy as np import pandas as pd import os import socket @ray.remote class Worker(object): def __init__(self, env_seed, env_na...
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.base import ContextMixin, View from django.views.generic import CreateView, UpdateView, DeleteView from history.models import ParamHistory, Param from children.models import Child from history.forms import HistoryForm from django.forms ...
import pandas as pd import pytest from toolz import merge from ..testing_utils import make_ecommerce_entityset from featuretools.entityset import Timedelta from featuretools.exceptions import NotEnoughData from featuretools.primitives import Count # , SlidingMean from featuretools.utils.wrangle import _check_timedel...
# -*- coding: utf-8 -*- """ Created on Sat Aug 10 09:24:24 2019 @author: Dror """ import numpy as np from gensound.utils import isnumber midA = 440 octave = 2 semitone = np.power(octave, 1/12) cent = np.power(semitone, 1/100) logSemitone = lambda k: np.log(k)/np.log(semitone) midC = lambda s: midA*semitone**(-9+s...
from __future__ import division from __future__ import print_function from __future__ import absolute_import from builtins import zip from past.utils import old_div from .asift import affine_detect, init_feature, filter_matches, explore_match from .common import Timer from tests.tesisfunctions import Plotim,overlay i...
from datetime import datetime from django.core.exceptions import ( ImproperlyConfigured, SuspiciousFileOperation, ) from django.core.files.base import ContentFile, File from django.test import TestCase from django.utils.six import BytesIO from storages.backends import dropbox try: from unittest import mock e...
from django import forms from django.conf import settings from directory_validators.common import not_contains_url_or_email from directory_validators.company import no_html from .generics.forms import DITHelpForm, DITHelpModelForm from .meta import choices, label, help_text, placeholder, validation from .models import...
""" Client for tdm-pilot.org. This project is in a pilot stage and functionality may change. """ import logging import glob import gzip import json import os import sys import zipfile from pathlib import Path import time from urllib.request import urlretrieve import progressbar import requests from IPython.core.dis...
import socket import asyncio import struct import cv2 import pickle import numpy as np from datetime import datetime import threading import io try: from picamera.array import PiRGBArray from picamera import PiCamera except: pass buffer_size = 4096 class AsyncServer: def __init__(self, host: str, po...
import torch import torch.nn as nn import numpy as np from model import CAEP from utils import Kodak,GeneralDS,compute_bpp from torchvision.utils import make_grid, save_image from torch.utils.data import DataLoader import pytorch_msssim import time from torch.utils.data.sampler import SequentialSampler SSIM = pytorch_...
# -*- coding: utf-8 -*- """ Fill data into an auxiliary patent database """ from __future__ import print_function import sys from optparse import OptionParser import psycopg2 from cnsipo.shared import get_logger from cnsipo.patent_parser import PatentParser logger = get_logger() APP_NO = 'app_no' APP_YEAR = 'app...
#coding:utf-8 import tensorflow as tf from tensorflow.python.platform.flags import FLAGS from SSD_Net import * from build_loss import * import common_flags import variables_collection from read_data import data_reader import numpy as np import sys from utils import * import cv2 def box_scale(k): s_min = 0.1 s_...
import argparse import ctypes import io import logging import os import platform import subprocess import sys from traceback import format_exc from botocore.exceptions import ClientError from paramiko.rsakey import RSAKey from .aws import AwsClient from .config import Config from .error import VpnSwapperException fro...
from timm.models.layers import drop_path from ofa.imagenet_codebase.modules.layers import * from ofa.layers import set_layer_from_config, MBInvertedConvLayer, ConvLayer, IdentityLayer, LinearLayer from ofa.imagenet_codebase.utils import MyNetwork, make_divisible from ofa.imagenet_codebase.networks.proxyless_nets import...
import logging import time from pathlib import Path import os import torch from utils.miou import compute_mean_ioU_file import numpy as np from PIL import Image import numpy as np import torchvision def create_logger(cfg,phase = 'train'): log_dir = Path(cfg.DIR.LOG) out_dir = Path(cfg.DIR.OUTPUT) vis_di...
import asyncio import json import logging from typing import Optional, List import aiohttp import elasticsearch from aiohttp import RequestInfo, BaseConnector from aiohttp.client_proto import ResponseHandler from aiohttp.helpers import BaseTimerContext from multidict import CIMultiDictProxy, CIMultiDict from yarl impo...
import sys import requests import pandas as pd from datetime import datetime extraction_date = datetime.today().strftime("%Y%m%d_%H%M%S") HEADERS = { "accept": "application/json; charset=utf-8", "accept-encoding": "gzip, deflate, br", "accept-language": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7", "conte...
# -*- coding: utf-8 -*- import logging logger = logging.getLogger("sdata") import os import uuid from sdata import Data import pandas as pd class VaultIndex(): """Index of a Vault """ INDEXDATAFRAME = "indexdataframe" def __init__(self): """Vault Index """ self._df = pd.Dat...
""" BigQuery helper functions Ported from 2018 Beacons study Jupyter Notebook """ import time import collections import pandas as pd from google.cloud import bigquery global project, dataset project='mlab-sandbox' dataset='mattmathis' DefaultArguments = { 'verbose_errors':True, 'maxdepth':4, 'project':pr...
# Copyright European Organization for Nuclear Research (CERN) # # 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 # # Authors: # - <NAME>, <<EMAIL>>, ...
""" GTSAM Copyright 2010-2019, Georgia Tech Research Corporation, Atlanta, Georgia 30332-0415 All Rights Reserved See LICENSE for the license information CustomFactor demo that simulates a 1-D sensor fusion task. Author: <NAME>, <NAME> """ from functools import partial from typing import List, Optional import gtsam...
# -*- coding: utf-8 -*- # (c) 2021, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) import os import re import sys from distutils.version import LooseVersion from functools import reduce from andeboxlib.actions.base import AndeboxAction class IgnoreFileE...
# Copyright (c) 2018, Palo Alto Networks # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS...
# -*- coding: utf-8 -*- # $Id$ # Functionality for managing, as well as loading and saving a dataset from __future__ import absolute_import import logging import xml.sax as sax class XMLException(Exception): """The base class for all XML parser exceptions. These are caught by some content handlers and augmen...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """A Plugin to tagall in the chat for @UniBorg and cmd is `.all`""" import asyncio import random import re from userbot...
#!/usr/bin/env python import argparse import os import pickle import ray.rllib.agents.ppo as ppo from ray.rllib.models import ModelCatalog from ray.tune.registry import register_env from scenario import FactoredModel from scenario import PathPlanningModel # from ray.rllib.utils.space_utils import flatten_to_single_...
#!/usr/bin/env python import logging import numpy as np import theano from argparse import ArgumentParser from theano import tensor from skimage.transform import rotate from blocks.bricks import MLP, Identity, Tanh, Logistic, Rectifier from blocks.bricks.recurrent import SimpleRecurrent from blocks.algorithms import...
import atexit import hashlib import hmac import re import os import sys import time import typing as t from datetime import datetime, timedelta import click import requests from loguru import logger from pytz import utc from urllib.parse import urlencode, urljoin from . import notifiers from .util import read_config,...
#!/usr/bin/python import sys, getopt, os, json import datetime, time def print_help_and_exit(exit_code,exit_msg=''): if exit_msg == '': print('test.py -i <inputfile> -o <outputfile>') else: print(exit_msg) sys.exit(exit_code) def process_results(directory, failed_list, broken_list, skippe...
from astropy.coordinates import SkyCoord from astropy import units as u def sex2deg(ra, dec): """ Convert sexagesimal coordinates to degrees. sex2deg( ra, dec) Args: ra: the right ascension in HH:MM:SS dec: the declination in DD:MM:SS """ c = SkyCoord( ra, dec, frame='icrs', un...
import detectron2 from detectron2.utils.logger import setup_logger setup_logger() # import some common libraries import numpy as np import cv2 import random # import some common detectron2 utilities from detectron2 import model_zoo from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg f...
from copy import copy from typing import Union, List from .layers import Layer, ConstantLayer, AmbientLayer, Substrate class MultilayerStructure: """Defines the structure of a multilayer sample through one or multiple :class:`Layer` objects and an ambient SLD. Initializes with a default ambient and substrat...
import asyncio import os import subprocess import tempfile from pathlib import Path from .version import VERSION __all__ = [ 'AsyncPydf', 'generate_pdf', 'get_version', 'get_help', 'get_extended_help', ] THIS_DIR = Path(__file__).parent.resolve() WK_PATH = os.getenv('WKHTMLTOPDF_PATH', str(THIS_D...
import os import sys from pathlib import Path import click from typing import Dict, List builtin_cmd_folder = Path(__file__).parents[0].joinpath('cmd').absolute() builtin_migration_folder = Path(__file__).parents[0].joinpath('migration').absolute() def find_dotbldr_dir(here: Path = None) -> Path: return find_par...
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ##...
#usr/bin/env python #-*- coding:utf-8- -*- import pygame import random from constants import * pygame.init() # pygame初始化,必须有,且必须在开头 font = pygame.font.Font("./font/simkai.ttf", 20) bigfont = pygame.font.Font("./font/simkai.ttf", 30) class DigitalBubble: speed = 2 # 速度 color = COLORS["bubble"] def __i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re, subprocess, os, sys, argparse def parse_atoms(arr): pattern_atom = re.compile(r"([0-9]{1,})\s{1,}([a-zA-Z]{1,})\s{1,}([0-9\.+-]{1,})\s{1,}([0-9\.+-]{1,})\s{1,}([0-9\.+-]{1,})") res = [] for line in arr: pm = pattern_atom.match(line)...
#!/usr/bin/env python3 # Copyright (2021-) <NAME> <<EMAIL>> # # 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...
# Copyright 2004-2008 <NAME>. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import os import types from pyplusplus import decl_wrappers from pyplusplus import code_repository class code_creator_t(object): ""...
# coding: utf-8 """封装常用的设计模式以及对内置函数和方法进行约定性的简化 """ import types import inspect from functools import wraps from girlfriend.exception import GirlFriendSysException _singletons = {} def singleton(clazz): """单例修饰器,被修饰的类在系统中都是单例的 非线程安全,请勿用在多线程环境当中 """ @wraps(clazz) def constructor(*args, **kws)...
#!/usr/bin/env python3 """ This program plays a game of Rock Paper Scissors Spock Lizard between two players, and reports both player's scores each round. It allows the user to select one of 5 different player types for each competitor. """ import random import time moves = ["scissors", "paper", "rock", "lizard", "S...
from bitcoin import bip32, script from binascii import unhexlify, hexlify from errors import BaseError class ScriptError(BaseError): NAME = "Script error" class DescriptorScript: def script(self, derivation): raise WalletError("Not implemented") def get_keys(self): raise WalletError("No...
# Copyright 2015-2021 SWIM.AI inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
import os import datetime import numpy as np import tensorflow as tf from sacred import Experiment from sacred.observers import FileStorageObserver, RunObserver from deep_rlsp.model import LatentSpaceModel, InverseDynamicsMDN from deep_rlsp.run import get_problem_parameters # changes the run _id and thereby the pat...
# -*- coding: utf-8 -*- #~ from __future__ import (unicode_literals, print_function, division, absolute_import) import numpy as np import matplotlib.cm import matplotlib.colors from .myqt import QT import pyqtgraph as pg from .base import BaseMultiChannelViewer, Base_MultiChannel_ParamController from .datasource i...
#!/usr/bin/env python3 # ## @file # edk_manifest_validation.py # # Copyright (c) 2018- 2019, Intel Corporation. All rights reserved.<BR> # SPDX-License-Identifier: BSD-2-Clause-Patent # import os import argparse import unicodedata import sys import traceback from edkrepo_manifest_parser.edk_manifest im...
import pandas as pd import numpy as np from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.optimizers import Adam import tensorflow as tf from keras import backend as K # turnLeft: 1000 # turnRight: 1000 import matplotlib.p...
from collections import defaultdict from urllib.parse import urlparse from datetime import datetime, timedelta import pymysql import html2text import subprocess import yaml h = html2text.HTML2Text() full_html_str = '' num_for_each_category = 10 with open('config.yml', 'r') as config_file: config = yaml.load(conf...
import numpy as np import scipy as sp import pandas as pd import h5py #from pyminc.volumes.factory import * import os from re import sub from sys import argv, exit from os.path import basename, exists, splitext from os import makedirs from set_images import * from utils import * def adjust_batch_size(n1, n2, batch_siz...
import datetime from ietf.utils import unaccent from ietf.person.models import Person, Email, Alias from ietf.doc.models import NewRevisionDocEvent from ietf.idtracker.models import EmailAddress def clean_email_address(addr): addr = addr.replace("!", "@").replace("(at)", "@") # some obvious @ replacements # w...
# # Imports # from forms import * from models import * from flask_table import Table, Col, LinkCol from flask import render_template, request, redirect, url_for, jsonify, flash # # Edit Research table class # class WriteActuatorTable (Table): classes = ['table'] id = Col('Id', show = False) identificac...
""" This file implements unit tests for several of the ConsumptionSaving models in HARK. These tests compare the output of different models in specific cases in which those models should yield the same output. The code will pass these tests if and only if the output is close "enough". """ from __future__ import print...
from collections import OrderedDict import torch from torch import nn, nn as nn from torch.nn import functional as F def default_norm_layer(planes, groups=16): groups_ = min(groups, planes) if planes % groups_ > 0: divisor = 16 while planes % divisor > 0: divisor /= 2 ...
import json import flask import os import yum.account as acc import yum.CONSTANTS as CONST from yum import Parser, food, state from yum.Guest import Guest from .cli import cli from click._unicodefun import click from flask import request class YumWeb(flask.Flask): """ Represents web part of the application - ...
import pytest from airbyte_dto_factory import * from airbyte_config_model import * @pytest.fixture def dummy_source_dto(): """ Creates a dummy SourceDto """ source = SourceDto() source.source_definition_id = 'ef69ef6e-aa7f-4af1-a01d-ef775033524e' source.source_id = '7d95ec85-47c6-42d4-a7a2-8e5c...
import re import json import types valid_names = re.compile(r'^[a-zA-Z0-9]+$') def encode_to_dict(obj): if hasattr(obj, 'to_dict'): # Calling encode_to_dict to ensure object is # normalised to a base dictionary all the way down. return encode_to_dict(obj.to_dict()) elif isinstance(obj...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 12 00:17:13 2021 @author: alankar """ import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from scipy.integrate import solve_ivp import h5py import sys from scipy import interpolate import sys from decimal impor...
""" MAFIA: A Maximal Frequent Itemset Algorithm (Without any optimization) Reference: MAFIA: A Maximal Frequent Itemset Algorithm for Transactional Databases - <NAME>, <NAME>, <NAME> (Department of CS, Cornell University) """ import numpy as np from functools import lru_cache class TransVerticalBitmaps: """ Sto...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2013 Contributor # # 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 #...
""" Code in this file deals with the data from the Milky Way Project First Data Release """ import os import cPickle as pickle import numpy as np import h5py from cloud import bucket, running_on_cloud from .util import overlap from .field import get_field def _has_field(lon): """Return True if image data exists...
from rekall import Interval, IntervalSet, IntervalSetMapping, Bounds3D from rekall.predicates import * from vgrid import VGridSpec, VideoMetadata, VideoBlockFormat, FlatFormat, SpatialType_Bbox, SpatialType_Keypoints, Metadata_Keypoints from vgrid_jupyter import VGridWidget import os, json import pandas as pd from cons...
""" Pytorch implementation of the supervised part of: "Vector-based navigation using grid-like representations in artificial agents" (Banino et al., 2018) <NAME>, 2019 """ import torch from torch import nn import numpy as np def truncated_normal_(tensor, mean=0, std=1): # https://discuss.pytorch.org/...
from oslo_db import exception as db_exc from oslo_db.sqlalchemy import session as db_session from oslo_db.sqlalchemy import utils as db_utils from oslo_log import log from oslo_utils import importutils from oslo_utils import strutils from oslo_utils import timeutils from oslo_utils import uuidutils from sqlalchemy.orm....
import os import time import multiprocessing import numpy as np from PIL import Image import tvm from tvm.contrib.graph_executor import GraphModule def preprocess(img_data): mean_vec = np.array([0.485, 0.456, 0.406]) stddev_vec = np.array([0.229, 0.224, 0.225]) norm_img_data = np.zeros(img_data.shape).as...
# Copyright 2015. 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 la...
from __future__ import print_function import sys, gzip, json, uuid from rdkit import Chem from sanifix import fix_mol ''' Log output to STDERR ''' def log(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def add_default_io_args(parser): parser.add_argument('-i', '--input', help="Input SD file, if n...