text
stringlengths
2
999k
# Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
"""Constants and configs.""" import os import pathlib import dotenv import hikari dotenv.load_dotenv() # The reason we need this, is that dns lookup fails with default settings, # so we need to set the dns severs manually, # so to stop one dns from ruining our day lets use more than one. # SOLUTION FROM: # https://...
"""Init module.""" from vizier._src.jax import xla_pareto from vizier._src.jax.xla_pareto import JaxParetoOptimalAlgorithm
# -*- coding: utf-8 -*- """ github3.api =========== :copyright: (c) 2012-2014 by Ian Cordasco :license: Modified BSD, see LICENSE for more details """ import warnings from functools import wraps from .github import GitHub, GitHubEnterprise gh = GitHub() def deprecated(func): """Decorator to mark a function as...
""" SoftLayer.tests.CLI.modules.subnet_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ import json from unittest import mock as mock import SoftLayer from SoftLayer.fixtures import SoftLayer_Product_Order from SoftLayer.fixtures import SoftLayer_Product_Pack...
"""Data loaders for summarization datasets.""" from lit_nlp.api import dataset as lit_dataset from lit_nlp.api import types as lit_types import tensorflow_datasets as tfds class GigawordData(lit_dataset.Dataset): """English Gigaword summarization dataset.""" def __init__(self, split="validation", max_examples=-...
# data from EMSL: https://bse.pnl.gov/bse/portal # 4-31G EMSL Basis Set Exchange Library 11/9/12 10:13 AM # Elements References # -------- ---------- # H, C - F: R. Ditchfield, W.J. Hehre and J.A. Pople, J. Chem. Phys. 54, 724 # (1971). # He, Ne: ...
import os import sys import urllib import zipfile class DatasetExplorer: """ Yeri geldiğinde bir adet nesne oluşturulmalıdır. Lütfen bu sınıftan oluşturulacak nesneye dışarıdan müdahalede bulunmayın. """ def __init__(self, demanded_datasets, path_dict): self.to_be_used_datasets = demanded...
from torchvision import models from torch import nn import torch import torch.nn.functional as F class FCN_ResNet18(nn.Module): def __init__(self, n_class): super().__init__() base_model = models.resnet18(pretrained=False) self.layers = list(base_model.children()) la...
import torch from . import common_functions as c_f class ModuleWithRecords(torch.nn.Module): def __init__(self, collect_stats=True): super().__init__() self.collect_stats = collect_stats def add_to_recordable_attributes( self, name=None, list_of_names=None, is_stat=False ): ...
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------------...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/02a_data_anime_heads.ipynb (unless otherwise specified). __all__ = ['Tokenizer', 'Datasets', 'DataLoaders'] # Cell import pandas as pd import numpy as np from PIL import Image from sklearn.model_selection import train_test_split import torch from torch.utils.data import...
from collections import OrderedDict from .common import EWSAccountService, create_shape_element from ..util import create_element, set_xml_value, TNS, MNS from ..version import EXCHANGE_2010 class FindFolder(EWSAccountService): """MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-refer...
from deuce.drivers.blockstoragedriver import BlockStorageDriver from deuce.drivers.metadatadriver \ import MetadataStorageDriver, GapError, OverlapError # noqa
from __future__ import division from __future__ import print_function from __future__ import absolute_import import tensorflow as tf import numpy as np import os import time import math from model import Model_S2VT from data_generator import Data_Generator from inference_util import Inference import configuration im...
from typing import Dict, Sequence, List import pyexlatex as pl from datacode.models.variables import Variable def model_eqs(structural_dict: Dict[Variable, Sequence[Variable]], measurement_dict: Dict[Variable, Sequence[Variable]], var_corr_groups: Sequence[Sequence[Variable]], ...
from abc import ABC, abstractmethod import geopandas as gpd import graph_tool import graph_tool.draw import graph_tool.topology import numpy as np from aves.features.geo import positions_to_array from .base import Network class LayoutStrategy(ABC): def __init__(self, network: Network, name: str): self....
# -*- coding: utf-8 -*- from argh.decorators import arg import lain_sdk.mydocker as docker from lain_cli.auth import SSOAccess from lain_cli.utils import check_phase, get_domain from lain_sdk.util import info, warn @arg('phase', help="lain cluster phase id, can be added by lain config save") def logout(phase): "...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: pyatv/mrp/protobuf/RegisterHIDDeviceResultMessage.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import me...
#!/usr/bin/env python """insertionsort.py: Program to implement insertion sort""" __author__ = 'Rohit Sinha' def insertion_sort(alist): for selected in range(1, len(alist)): selected_value = alist[selected] pos = selected while pos > 0 and alist[pos - 1] > selected_value: ali...
#!/usr/bin/env python3 # # Script to test LUPFactors_simple, LUPFactors and LUPPFactors on a variety # of ill-conditioned matrices. # # Daniel R. Reynolds # SMU Mathematics # Math 4315 # imports import numpy import time from LUPFactors_simple import LUPFactors_simple from LUPFactors import LUPFactors from LUPPFactors ...
#!/usr/bin/env python3 #https://codeforces.com/problemset/problem/1140/D #所有都带1? #\Sum n**2 的公式 => https://zhuanlan.zhihu.com/p/26351880 i = int(input()) print((i-1)*i*(i+1)//3-2)
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
############################################################################### # WaterTAP Copyright (c) 2021, The Regents of the University of California, # through Lawrence Berkeley National Laboratory, Oak Ridge National # Laboratory, National Renewable Energy Laboratory, and National Energy # Technology Laboratory ...
from os import path, remove, mkdir, getcwd import sys from shutil import copytree, rmtree, copy as shcopy import PyInstaller.__main__ from py7zr import SevenZipFile from main.code.engine.constants import cprint, clear_terminal, colorize import re # Build instructions def get_version() -> str: """Get version in fo...
import FWCore.ParameterSet.Config as cms process = cms.Process("TestDQMFileSaver1") process.load("DQMServices.Components.test.MessageLogger_cfi") process.load("DQMServices.Components.EDMtoMEConverter_cff") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) process.source = cms.Source("Pool...
from librosa.core import load from librosa.feature import mfcc import numpy as np def normalize_gain(samples: np.ndarray) -> np.ndarray: min_ = samples.min() max_ = samples.max() return (samples - min_) / (max_ - min_) def mfccs(filepath: str, frame_ms: int, sliding_ms: int, n_mfccs: int) -> np.ndarray: ''' G...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # -------------------------------------------------------- # BEIT: BERT Pre-Training of Image Transformers (https://arxiv....
""" This module defines classes for describing properties of a model. """ import collections import collections.abc from copy import deepcopy from datetime import date, datetime from typing import ( Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union, Any, Callable, ) fr...
import FWCore.ParameterSet.Config as cms from L1Trigger.L1TMuonEndCap.fakeEmtfParams_cff import * L1TMuonEndCapForestOnlineProd = cms.ESProducer("L1TMuonEndCapForestOnlineProd", onlineAuthentication = cms.string('.'), forceGeneration = cms.bool(False), onlineDB = cms.string('oracle://CMS_...
#!/usr/bin/env python # # This script generates a BPF program with structure inspired by trace.py. The # generated program operates on PID-indexed stacks. Generally speaking, # bookkeeping is done at every intermediate function kprobe/kretprobe to enforce # the goal of "fail iff this call chain and these predicates". #...
""" API operations on User objects. """ import copy import json import logging import re from collections import OrderedDict from markupsafe import escape from sqlalchemy import ( false, or_, true ) from galaxy import ( exceptions, util, web ) from galaxy.exceptions import ObjectInvalid from g...
import os import time from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from django.utils import timezone from member.models import UserNotification from nadine import email class Command(BaseCommand): help = "Send User Notification Emails." def h...
# # Copyright (c) 2021 the Hugging Face team. # # 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 agree...
# CommentPolicy.py - Pre Checkin Trigger import os, sys, re, tkMessageBox def checkComment(comment): comment = comment.lower() caseIds = re.findall(r'bug\d+|feat\d+',comment) return caseIds def main(): comment = os.environ.get('CLEARCASE_COMMENT','') version = os.environ['CLEARCASE_XPN']...
"""Utilities for assertion debugging.""" import collections.abc import os import pprint from typing import AbstractSet from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import Mapping from typing import Optional from typing import Sequence import _pytest...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: building_zone_names.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflecti...
from gui import GUI program = GUI() program.run()
import numpy as np def WithinMP(x,rho,Rss=1.42,Alpha=0.5): ''' Determines if a set of x and rho (sqrt(y**2 + z**2)) coordinates are within the magnetopause boundary or not. Inputs: x: Position(s) in x MSM direction. rho: Position(s) in rho MSM direction. Rss: Distance of the subsolar point on the magnetopa...
# -*- coding: utf-8 -*- from futu import * quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111) print(quote_ctx.get_trading_days(Market.HK, start='2018-02-01', end='2018-02-05')) from futu.quote.quote_get_warrant import Request req = Request() req.sort_field = SortField.CODE req.ascend = True req.type_list =...
from unittest import TestCase from chatterbot.adapters.storage import JsonFileStorageAdapter from chatterbot.conversation import Statement, Response class JsonAdapterTestCase(TestCase): def setUp(self): """ Instantiate the adapter. """ from random import randint # Generat...
import torch from model_save import * import torchvision from torch import nn # 方式1-》保存方式1,加载模型 model = torch.load("vgg16_method1.pth") # print(model) # 方式2,加载模型 vgg16 = torchvision.models.vgg16(pretrained=False) vgg16.load_state_dict(torch.load("vgg16_method2.pth")) # model = torch.load("vgg16_method2.pth") # prin...
import warnings warnings.warn( "\n\n" "In a future version of Scanpy, `scanpy.api` will be removed.\n" "Simply use `import scanpy as sc` and `import scanpy.external as sce` instead.\n", FutureWarning ) from anndata import AnnData from ..neighbors import Neighbors from anndata import read as read_h5ad ...
import model import theano_funcs import utils from iter_funcs import get_batch_idx # credit to @fulhack: https://twitter.com/fulhack/status/721842480140967936 import seaborn # NOQA - never used, but improves matplotlib's style import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.axes_grid1 import Im...
import tensorflow as tf from tensorflow.python.framework import ops import sys, os base_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(base_dir) nnquery_module = tf.load_op_library(os.path.join(base_dir, 'tf_nnquery_so.so')) def build_sphere_neighbor(database, query, ...
from typing import List, Tuple import numpy as np import seaborn as sns import pandas as pd sns.set_style("darkgrid") def space_sep_upper(column_name: str) -> str: """ Separates strings at underscores into headings. Used to generate labels from logging names. Parameters ---------- column_na...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import argparse import glob import multiprocessing as mp import os import time import cv2 import tqdm from detectron2.config import get_cfg from detectron2.data.detection_utils import read_image from detectron2.utils.logger import setup_logger fro...
import datetime from ..controllers.logger import Logger from ..core.fake_ssl_thread import FakeSslThreadABC from ..utils.functions import bypass_error, fake_certificate_exists from ..utils.socket import close_socket_pass_exc, get_bind_socket from traceback import format_exc from threading import Thread from ssl import...
import unittest import os from monty.collections import frozendict, Namespace, AttrDict, \ FrozenAttrDict, tree test_dir = os.path.join(os.path.dirname(__file__), 'test_files') class FrozenDictTest(unittest.TestCase): def test_frozen_dict(self): d = frozendict({"hello": "world"}) self.asser...
"""test sparse matrix construction functions""" import numpy as np from numpy import array from numpy.testing import (assert_equal, assert_, assert_array_equal, assert_array_almost_equal_nulp) import pytest from pytest import raises as assert_raises from scipy._lib._testutils import check_free_memory from scip...
""" `schemas.errors` module defines pydantic models for different error responses. """ from pydantic import BaseModel class NotFoundTask(BaseModel): error: str = "Task not found by ID" class NotFoundTopic(BaseModel): error: str = "Topic not found by ID" class RateLimitExceeded(BaseModel): error: str =...
""" Path utilities for benchbuild. """ import os import sys def list_to_path(pathlist): """Convert a list of path elements to a path string.""" return os.path.pathsep.join(pathlist) def path_to_list(pathstr): """Conver a path string to a list of path elements.""" return [elem for elem in pathstr.spl...
from flask import render_template,request,redirect,url_for,abort,flash from . import main from ..models import User, Blog, Comment from flask_login import login_required,current_user from datetime import datetime, timezone from .. import db from .forms import BlogForm,CommentForm # Views index @main.route('/') def in...
# -*- coding: utf-8 -*- # # Copyright 2019 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...
""" Module for managing a sensor via KNX. It provides functionality for * reading the current state from KNX bus. * watching for state updates from KNX bus. """ from __future__ import annotations from typing import TYPE_CHECKING, Any, Iterator from xknx.remote_value import ( GroupAddressesType, RemoteValue,...
#!/usr/bin/python """Linear topology with one computer, one router and one client""" import time import experiment import topo class LinearQuic(experiment.Experiment): """One edge controller in the leftmost host followed by an edge computer, an edge router and an edge client in the rightmost one""" def __i...
from rest_framework import serializers from api.src.MH.MHModel import MH class MHSerializer(serializers.ModelSerializer): class Meta: model = MH fields = '__all__'
from __future__ import absolute_import, unicode_literals import collections import contextlib import logging import operator from mopidy import compat, exceptions, models from mopidy.compat import urllib from mopidy.internal import validation logger = logging.getLogger(__name__) @contextlib.contextmanager def _ba...
# Copyright 2001 by Katharine Lindner. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Martel based parser to read NBRF formatted files. This is a huge regular regular expre...
# -*- coding: utf-8 -*- """ Local settings - Run in Debug mode - Use console backend for emails - Add Django Debug Toolbar - Add django-extensions as app """ import socket import os from .common import * # noqa # DEBUG # ------------------------------------------------------------------------------ DEBUG = env.bo...
from __future__ import print_function import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.Config import ModifierChain,Modifier class Eras (object): """ Dummy container for all the cms.Modifier instances that config fragments can use to selectively configure depending on what scenario is acti...
""" Description: A technique for detecting anomalies in seasonal univariate time series where the input is a series of <timestamp, count> pairs. Usage: anomaly_detect_ts(x, max_anoms=0.1, direction="pos", alpha=0.05, only_last=None, threshold="None", e_value=False, longterm=Fals...
from django.contrib import admin from .models import Comments admin.site.register(Comments)
import asyncio from ph4_walkingpad import pad from ph4_walkingpad.pad import WalkingPad, Controller from ph4_walkingpad.utils import setup_logging import yaml import psycopg2 from datetime import date def on_new_status(sender, record): distance_in_km = record.dist / 100 print("Received Record:") print('Dis...
""" Created: March 1, 2020 Updated: September 14, 2020 Author: Suleyman Barthe-Sukhera Description: RSA private and public key classes """ from binascii import hexlify, unhexlify from os import getcwd from Crypto.Cipher import PKCS1_OAEP from Crypto.Hash.SHA3_256 import SHA3_256_Hash from Crypto.PublicKey.RSA import ...
from pylab import figure, show, setp #from matplotlib.numerix import sin, cos, exp, pi, arange import numpy as np t = np.arange(0.0, 2.0, 0.01) s1 = np.sin(2*np.pi*t) s2 = np.exp(-t) s3 = np.sin(2*np.pi*t)*np.exp(-t) s4 = np.sin(2*np.pi*t)*np.cos(4*np.pi*t) fig = figure() t = np.arange(0.0, 2.0, 0.01) yprops = dict(...
# Generated by Django 3.2.5 on 2021-08-01 18:53 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', ...
from __future__ import absolute_import, division, print_function import logging import sys from mesos.interface import Executor from .messages import decode, encode class ExecutorProxy(Executor): """Base class for Mesos executors. Users' executors should extend this class to get default implementations of...
from Jumpscale import j from bottle import Bottle, request, response app = Bottle() client = j.clients.oauth_proxy.get("main") oauth_app = j.tools.oauth_proxy.get(app, client) @app.route("/oauth/authorize") def authorize(): return oauth_app.authorize() @app.route("/oauth/callback") def callback(): return ...
from flask import Flask from flask_bootstrap import Bootstrap from config import config_options from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_uploads import UploadSet,configure_uploads,IMAGES from flask_mail import Mail from flask_simplemde import SimpleMDE login_manager = Log...
from __future__ import absolute_import import falcon from tracker.utils import create_cart_id, json_dumps from tracker.hooks import validate_request from tracker.tasks import db_save class CartItem(object): @falcon.before(validate_request) def on_post(self, req, resp, **params): params['cart_id'] =...
# Copyright (c) 2021 Horizon Robotics and ALF Contributors. 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...
"""The application/controller class for ABQ Data Entry""" import tkinter as tk from tkinter import ttk from tkinter import messagebox from tkinter import filedialog from . import views as v from . import models as m from .mainmenu import MainMenu class Application(tk.Tk): """Application root window""" def __in...
#!/usr/bin/env python import os import sys from pathlib import Path if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some...
# -*- coding: utf-8 -*- # # Jinja2 documentation build configuration file, created by # sphinx-quickstart on Sun Apr 27 21:42:41 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleab...
import keras.backend as K from keras.layers.convolutional import Conv3D from keras.layers.core import Activation, Dense, Dropout from keras.layers.merge import concatenate from keras.layers.normalization import BatchNormalization from keras.layers.pooling import (AveragePooling3D, GlobalAveragePooling3D, AveragePooling...
#=============================================================================== # Imports #=============================================================================== import os import re import sys import stat import base64 import inspect import subprocess from abc import ( abstractproperty, ) from os.path i...
# -*- coding: utf-8 -*- # 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...
# -*- coding: utf-8 -*- """ pagarmeapisdk This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). """ from pagarmeapisdk.models.update_price_bracket_request import UpdatePriceBracketRequest class UpdatePricingSchemeRequest(object): """Implementation of the 'UpdatePrici...
from cnas.evaluation.core.config import args from cnas.evaluation.eval import eval_entry if __name__ == "__main__": eval_entry(args)
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-10-08 07:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('music', '0001_initial'), ] operations = [ migrations.AddField( ...
import cmiles import fragmenter import json mol_id = cmiles.get_molecule_ids('OCCO', strict=False) mapped_smiles = (mol_id['canonical_isomeric_explicit_hydrogen_mapped_smiles']) mol = cmiles.utils.load_molecule(mapped_smiles) torsions = fragmenter.torsions.find_torsions(mol) dihedrals_list = [torsions['internal']['t...
import os import logging import urllib.request import requests import re import io import us import zipfile import json from datetime import datetime from functools import lru_cache from enum import Enum import pandas as pd import numpy as np from covidactnow.datapublic.common_fields import CommonFields from libs.dat...
# Copyright (C) 2016 Kevin Ross # # 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 3 of the License, or # (at your option) any later version. # # This program is distributed in the...
"""Unit test package for disambigufile."""
""" Tests to visually inspect the results of the library's functionality. Run checks via python check_visually.py """ from __future__ import print_function, division import imgaug as ia from imgaug import augmenters as iaa from imgaug import parameters as iap import numpy as np from scipy import ndimage, misc from...
import torch import torch.nn as nn class PGD: def __init__(self, eps=60 / 255., step_size=20 / 255., max_iter=10, random_init=True, targeted=False, loss_fn=nn.CrossEntropyLoss(), batch_size=64): self.eps = eps self.step_size = step_size self.max_iter = max_iter sel...
from support import * import numpy as np import shap np.random.seed(1) def combined(feature_perturbation, twin=False): n = 2000 shap_test_size = 2000 X, y, df, eqn = toy_weight_data(n) X = df.drop('weight', axis=1) y = df['weight'] rf = RandomForestRegressor(n_estimators=40, oob_score=True, n...
import torch import torch.nn as nn import torch.nn.functional as F class QNetwork(nn.Module): def __init__(self, state_size, action_size, seed, hidden_layers): """ state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random ...
import time from collections import deque from copy import deepcopy import numpy as np import torch from gym import make from torch import nn from torch.distributions import Normal from torch.optim import Adam from HW03.agent import transform_state, Agent N_STEP = 1 GAMMA = 0.9 DEVICE = torch.device("cuda" if torch....
from datetime import datetime from uuid import uuid4 from django.contrib.auth import authenticate from rest_framework.exceptions import NotFound from api.exceptions import WithdrawalUser, AlreadyLogout from apps.users.models import User, UserSession class UserService(object): def check_username(self, username:...
import numpy as np def Mahalanobis_distance(x, mu, M): """ Calculating the Mahalanobis distance between x and mu, MD(x,mu), in a space with metric M. ------------PARAMETERS------------ @param simul : Number of simulations @param x : First vector @param mu : Second vector, usually containing t...
import random ''' def get_trade(r_sold, q_sold, i_buying, agent_id): return { 'r_sold': r_sold, 'q_sold': q_sold, 'i_buying': i_buying, 'agent_id': agent_id, 'action_id': 'Trade' } def get_arb_market(settle_asset, agent_id): return { 'settle_asset': settle_a...
# Copyright 2020-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 agre...
import os import json import logging from ..core.logger import setup_logger from ..benchmarks.utils import run_benchmarks from ..core.utils import load_class LOGGER = logging.getLogger() def run_evaluation(config): logger_path = os.path.join(config['benchmark_tmp_root'], 'logger') os.makedirs(config['benchm...
""" Parse spotify URLs """ from __future__ import unicode_literals, print_function, division import re import logging log = logging.getLogger('spotify') def handle_privmsg(bot, user, channel, args): """Grab Spotify URLs from the messages and handle them""" m = re.match(".*(https?:\/\/open.spotify.com\/|spo...
from io import BytesIO from zipfile import ZipFile import requests import os from utilities.get_or_create_temporary_directory import get_temporary_directory as get_temp def get_file_from_server(url, return_directory, **kwargs): """ This accepts a a URL and (ii) retrieves a zipped shapefile from the URL. ...
# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy.orm import declarative_base import sqlalchemy_mate as sam Base = declarative_base() class User(Base, sam.ExtendedBase): __tablename__ = "users" id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String, nullable=True) t_use...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) Megvii, Inc. and its affiliates. # VOC_CLASSES = ( '__background__', # always index 0 VOC_CLASSES = ( "bus", "car", "motorcycle", "truck" )