content
stringlengths
5
1.05M
import re from copy import deepcopy from pyspark.sql.dataframe import DataFrame from pyspark.sql.session import SparkSession from functools import reduce altair_installed = True try: import altair as alt from altair import Chart except ImportError: altair_installed = False _outer_chart_spec_freq = { ...
from .user import UserRessonanteManager from .city_manager import CityManager
#!/usr/bin/env python """Command line interface to split a given workflow into several chunks. Usage: distribute_jobs.py -i input.yml THE USER MUST CHANGES THESE VARIABLES ACCORDING TO HER/HIS NEEDS: * project_name * path to the basis and Cp2k Potential * CP2K: - Range of Molecular ori...
import re import warnings import numpy as np import pandas as pd import expan.core.binning as binmodule import expan.core.early_stopping as es import expan.core.statistics as statx from expan.core.experimentdata import ExperimentData from expan.core.results import Results, delta_to_dataframe_all_variants, feature_che...
__all__ = ["save_model", "load_model"] import os from .models import Lm, Lm2, Lmer from .utils import _df_meta_to_arr from rpy2.robjects.packages import importr import deepdish as dd import pandas as pd import warnings from tables import NaturalNameWarning base = importr("base") def save_model(model, filepath, comp...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") import yfinance as yf yf.pdr_override() import datetime as dt # input symbol = 'AAPL' start = dt.date.today() - dt.timedelta(days = 365*2) end = dt.date.today() # Read data df = yf.download(symbol...
class Processor(object): ''' Processor is a engine of pyno, there functions defines and outputs calculates ''' def init_processor(self): self.proc_result = None self.func = None self.gen_output = {} self.need_update = True self.problem = False sel...
from aiohttp_example.services import services async def get_visited_count(name: str) -> int: visited_count_raw = await services.redis.hget('user_visited_count', name) return int(visited_count_raw) if visited_count_raw else 0 async def incr_visited_count(name: str) -> None: await services.redis.hincrby('...
import pandas as pd from mlxtend.frequent_patterns import association_rules from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori, fpmax, fpgrowth from adasher.data_utils.__util import DF, Period from adasher.templates import * from adasher.templates.__util import Template...
import torch import torch.nn as nn import numpy as np def weights_init(m): if isinstance(m, nn.Linear): torch.nn.init.xavier_uniform_(m.weight.data) torch.nn.init.uniform_(m.bias.data) def fanin_init(m): if isinstance(m, nn.Linear): fanin = m.weight.data.size(0) v = 1. / np.sqrt(fanin) m.weight.data.unifo...
import random n_total = 130 n_test = 15 n_dev = 15 test_dev_set = set() while len(test_dev_set) < n_test+n_dev: test_dev_set.add(random.randint(0, n_total)) i_test = 0 i_dev = 0 with open('title_key_story_10sents_fables.txt', 'r') as f, open('fairy_tale_title_key_story_train_10sents_fables.txt', 'w') as f_train, op...
from django.core.management.base import BaseCommand, CommandError from openbadge.analysis import send_weekly_email from openbadge.models import StudyGroup class Command(BaseCommand): help = 'Send the weekly email to all members of a group, or all groups if no key is provided' def add_arguments(self, parser): ...
from .arcface_trainer import * from .centerloss_trainer import * from .vggface2_trainer import *
import socket import subprocess def ricevi_comandi(conn): while True: richiesta = conn.recv(4096) risposta = subprocess.run(richiesta.decode(), shell=True, stdout=subprocess.PIPE, stderr=subproc...
import logging from .base import * # noqa from .base import env # GENERAL # ------------------------------------------------------------------------------ DEBUG = env.bool("DEBUG", default=True) # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env("SECRET_KEY", default="fOqtAorZrVqWYbuM...
import io import json from copy import deepcopy import GetAwayUsers import demistomock as demisto def util_load_json(path): with io.open(path, mode='r', encoding='utf-8') as f: return json.loads(f.read()) away_user_data = util_load_json('test_data/away_user.json') def test_script_valid(mocker): ...
from flask import Flask, request, jsonify, render_template_string import redis import requests import re import json import sys app = Flask(__name__) @app.route('/getid/<username>') def getid(username): red = redis.Redis(host="redis_users") return red.get(username).decode() @app.route('/useraction', methods...
from pisht30.pisht30 import *
from __future__ import annotations from typing import Dict from typing import List from typing import Optional import sqlalchemy as sa from sqlalchemy.engine.base import Engine from spinta.backends.components import Backend from spinta.components import EntryId from spinta.components import Namespace from spinta.dim...
import doctest import re import pytest import numpy as np from numpy.testing import assert_array_equal from datascience import * import pandas as pd ######### # Utils # ######### @pytest.fixture(scope='function') def table(): """Setup Scrabble table""" return Table().with_columns([ 'letter', ['a', '...
#!/usr/bin/python import shapely from shapely import speedups, wkb from shapely.geometry import LineString, Point from osgeo import ogr from optparse import OptionParser from math import atan2, degrees, sin, cos import math # Be fast if possible. if shapely.speedups.available: shapely.speedups.enable() parser = ...
""" Testing group-level finite difference. """ import unittest import numpy as np from openmdao.core import Group, Problem from openmdao.components import ParamComp, ExecComp from openmdao.test.simple_comps import SimpleComp, SimpleArrayComp from openmdao.test.util import assert_rel_error class TestIndices(unitte...
""" Testing out Librato's metrics platform. """ from ConfigParser import NoOptionError, NoSectionError import base64 import httplib import urllib from blueprint import cfg try: token = cfg.get('librato', 'token') username = cfg.get('librato', 'username') auth = 'Basic {0}'.format(base64.b64encode('{0}:{...
from .elastic import ElasticHook
from docutils import nodes import sphinx.domains.std # Borrowed from: http://stackoverflow.com/questions/13848328/sphinx-references-to-other-sections-containing-section-number-and-section-title class CustomStandardDomain(sphinx.domains.std.StandardDomain): def __init__(self, env): env.settings['footnote_references...
from magma import * from .LUT import * from .arith import DefineSub from .logic import Not __all__ = ['DefineEQ', 'EQ'] __all__ += ['DefineNE', 'NE'] __all__ += ['DefineUGE'] __all__ += ['DefineULE'] __all__ += ['DefineUGT'] __all__ += ['DefineULT'] __all__ += ['DefineSGE'] __all__ += ['DefineSLE'] __all__ += ['Defin...
# Copyright 2016-2017 IBM Corp. 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...
import pandas as pd base = pd.read_csv('./datasets/credit-risc.csv') forecasts = base.iloc[:, 0:4].values classes = base.iloc[:, 4].values from sklearn.preprocessing import LabelEncoder label_encoder = LabelEncoder() forecasts[:,0] = label_encoder.fit_transform(forecasts[:,0]) forecasts[:,1] = label_encoder.fit_tran...
class Caesar: def caesar(cleartext, key, alphabet, cipher): result = "" cleartext = cleartext.lower() if not cipher: key = len(alphabet) - key for x in cleartext: if x not in alphabet: result += x else: i = al...
""" Handle non-attack Actions """ from collections import namedtuple import dice from pycs.action import Action from pycs.constant import SpellType from pycs.util import check_args ############################################################################## ##########################################################...
import numpy as np import matplotlib.pyplot as plt import pywt #import pywt.data #import pandas as pd def func_round(number): if number >= 0: if number - int(number) >= 0.5: return int(number) + 1 else: return int(number) elif number < 0: if number - int(number)<=-0.5: return int(number) - 1 ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-LOG 蓝鲸日志平台 is licensed under the MIT License. License for BK-LOG 蓝鲸日志平台: ------------------------------------------------...
''' A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T". Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string. For example, "AACCGGTT" -> "AACCGGTA" is 1 mutat...
# Download and build the data if it does not exist. import os import csv import pickle import zipfile from pathlib import Path import parlai.core.build_data as build_data def create_probing_format(orig_dpath): # Load raw data train_path = orig_dpath.joinpath('train.tsv') dev_path = orig_dpath.joinpath('d...
from subprocess import Popen, PIPE def shell(cmd, shell=False): if shell: p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) else: cmd = cmd.split() p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, err = p.communicate() return output
from alfi.datasets import DataHolder from alfi.configuration import MCMCConfiguration import abc class MCMCLFM(): def __init__(self, data: DataHolder, options: MCMCConfiguration): self.options = options self.data = data self.preprocessing_variance = options.preprocessing_variance s...
# MIT License # # Copyright (c) 2022 TrigonDev # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, pu...
if __name__ == "__main__": assert currentProgram is None assert state.getProject() is not None print("programless_script executed successfully")
#!/usr/bin/env python3 from setuptools import setup, find_packages from commit_linter import __version__, __description__, __author__, __email__, __license__ with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name="commit-linter", version=__version__, license=__li...
try: pass for x in []: pass finally<caret> #blah
from __future__ import absolute_import import unittest from nose.plugins.attrib import attr from nose.tools import nottest from beaker.cache import Cache from .common import CommonMethodMixin class RedisTestOverrides(object): @nottest def test_fresh_createfunc(self): # createfunc depends on create_...
import sys sys.path.insert(0, 'lib') import numpy as np import tensorflow as tf from snippets import generate_anchors_pre from generate_anchors_tf import generate_anchors_pre_tf # This tests compares if `generate_anchors_pre_tf` is doing exactly the same # as the original numpy implementation `generate_anchors_pre`...
from functools import cached_property from pydantic import BaseModel import numpy as np from .polyline import Polyline from .position import Position __all__ = ['Polyline', 'Position', 'BBXCornersClass'] def rot_x(x, y, phi): return x * np.cos(phi) - y * np.sin(phi) def rot_y(x, y, phi): ...
# -*- coding: utf-8 -*- # # Copyright (C) 2018 CERN. # # invenio-app-ils is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Circulation minters.""" from ..records.api import Document, InternalLocation, Item, Location from .providers i...
from nose.plugins.deprecated import DeprecatedTest def test_func(): raise DeprecatedTest()
from PIL import Image, ImageDraw, ImageFont import urllib import urllib.request from io import BytesIO # down load image avatar avatar = 'https://avatars3.githubusercontent.com/u/1332618?v=3&s=460' rsp = urllib.request.urlopen(avatar) data = rsp.read() fp = BytesIO() fp.write(data) fp.seek(0, 0) image = Image.open(fp...
from re import compile def require(value, message): if not value: raise ValueError(message) return value def match_validator(value, regex, message): if value and not regex.match(value): raise ValueError(message) return value class Contact: email_regex = compile( r"[a-z0...
from math import gcd from typing import Dict, List import torch import torch.nn as nn from torch.nn import functional as F class GraphAttention(nn.Module): """ Graph attention module to pool features from source nodes to destination nodes. Given a destination node i, we aggregate the features from nearb...
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
import os import torch from torch import nn from torch.utils.data import DataLoader from torchvision import datasets, transforms class NeuralNetwork(nn.Module): def __init__(self): super(NeuralNetwork, self).__init__() self.flatten = nn.Flatten() self.linear_relu_stack = nn.Sequ...
import gc class old_style_class(): pass class new_style_class(object): pass a = old_style_class() del a gc.collect() b = new_style_class() del b gc.collect() a = old_style_class() del old_style_class gc.collect() b = new_style_class() del new_style_class gc.collect() del a gc.collect() ...
# Copyright 2017 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 applicab...
import discord from discord.ext import commands import asyncio import calendar import concurrent.futures import csv import datetime import inspect import io import json import multiprocessing import random import string from typing import Optional import xml.etree.ElementTree from bs4 import BeautifulSoup import dic...
from django.shortcuts import render from django.contrib.auth import views as auth_views from django.contrib import messages from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.views.generic.edit import FormView,CreateView from django.views.generic import View f...
import FWCore.ParameterSet.Config as cms nTupleGenMET = cms.EDProducer( "BristolNTuple_GenMET", InputTag = cms.InputTag( 'slimmedMETs' ), Prefix = cms.string( 'GenMET.' ), Suffix = cms.string( '' ) )
import abc import collections import sqlite3 class BaseStore(object, metaclass=abc.ABCMeta): def add_one(self, trigram): self.add_many((trigram,)) @abc.abstractmethod def add_many(self, trigrams): pass @abc.abstractmethod def get_trigram_values(self, word_1, word_2): pass...
#!/usr/bin/env python3 """ Tic Tac Toe for two players. • 2 players should be able to play the game (both sitting at the same computer) • The board should be printed out every time a player makes a move • You should be able to accept input of the player position and then place a symbol on the board. It has been sugges...
"""Update the index of backups. """ import logging from archive.index import ArchiveIndex log = logging.getLogger(__name__) def update_index(args, config): idx_file = config.backupdir / ".index.yaml" if idx_file.is_file(): log.debug("reading index file %s", str(idx_file)) with idx_file.open(...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """A module containing all the micro-benchmarks.""" from superbench.benchmarks.micro_benchmarks.micro_base import MicroBenchmark, MicroBenchmarkWithInvoke from superbench.benchmarks.micro_benchmarks.gemm_flops_performance_base import GemmFlopsBe...
from localtalk.views.default import default_blueprint def init_views(app): app.register_blueprint(default_blueprint, url_prefix='/')
#!/usr/bin/env python import pytest import sys # Script first argument as that is the name of the script (pytest-submit.py). pytest.main(sys.argv[0:])
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from PlacePulse import app # ONLY RUN THIS BEHIND A PROXY! # Proxy Fixer needed for apache proxy in production, see http://flask.pocoo.org/docs/deploying/others/#proxy-setups from werkzeug.contrib.fixers...
#!/usr/bin/env python # encoding: utf-8 """ peer.py Created by Thomas Mangin on 2013-02-20. Copyright (c) 2009-2015 Exa Networks. All rights reserved. """ import os import sys import pwd import socket import select import asyncore from struct import unpack from exabgp.version import version from exabgp.reactor.net...
# Generated by Django 2.2.3 on 2019-07-28 02:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0005_auto_20190726_1302'), ] operations = [ migrations.AlterModelOptions( name='favoritething', options={'ordering':...
import torch from torch import nn class SEBlock(nn.Module): """ Implementation of the Squeeze-and-Excitation (SE) block proposed in [1]. Parameters ---------- in_channels : int Number of channels in the input tensor. reduction : int, optional, default=16 Reduction ratio to con...
import datetime import sys import re sys.path.append('..') from configure.settings import DBSelector, config from common.BaseService import BaseService from parsel import Selector # 雪球私募数据获取 class PrivateFund(BaseService): def __init__(self): super(PrivateFund, self).__init__('../log/privatefund.log') ...
from PyQt4 import QtCore, QtGui from CoreData import RegistroReserva, saveD, loadD import data class EditLibrosWindow(QtGui.QWidget): """ Ventana para agregar reservas Not DONE """ def __init__(self, isbn): super(EditLibrosWindow, self).__init__() self.createForm() self....
from math import acos, atan, asin, sin, degrees, sqrt from pythagoras import cosineRule, angleA class Kinematics(object) : def __init__(self, m1x, m1y, m2x, m2y, l1, l2, r1, r2): self.m1x = float(m1x) self.m1y = float(m1y) self.m2x = float(m2x) self.m2y = float(m2y) self.l1...
# Copyright 2018 Google LLC. 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 a...
import pygame import random from pygame.locals import ( KEYDOWN, K_UP, K_DOWN, K_RIGHT, K_LEFT, QUIT, K_ESCAPE ) # CONSTANTS SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 class Player(pygame.sprite.Sprite): def __init__(self): super(Player, self).__init__() self.surf = pyg...
from pypmml import Model model = Model.load("D:\mysoft\jwolf-micro\jwolf-bigdata\model\KMeansModelPMML.pmml") predict1 = model.predict([1, 1, 1, 1, 5, 1, 1, 2, 2, 1]) predict2 = model.predict([2 ,5 ,5,5 ,5 ,5, 6, 6, 2, 1]) predict3 = model.predict([8 ,5 ,9,9 ,9 ,9, 9, 6, 8, 1]) print(predict1,predict2,predict3)
from .model import YOLOv5 from .datasets import * from .engine import train_one_epoch, evaluate from .distributed import init_distributed_mode, get_rank, get_world_size from .utils import * from .gpu import * try: from .visualize import show, plot except ImportError: pass DALI = False try: import nvidia.d...
#!/usr/bin/python # http://flask.pocoo.org/docs/0.10/patterns/sqlite3/ # http://ryrobes.com/python/running-python-scripts-as-a-windows-service/ # http://stackoverflow.com/questions/23550067/deploy-flask-app-as-windows-service # http://gouthamanbalaraman.com/blog/minimal-flask-login-example.html from flask import Flas...
# Copyright 2016 Isotoma Limited # # 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...
import requests from queue import Queue import sys,random,re import threading USERAGENT = [ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536...
"""Python re-implementation of "Multi-Cue Correlation Filters for Robust Visual Tracking" @inproceedings{wang2018multi, title={Multi-cue correlation filters for robust visual tracking}, author={Wang, Ning and Zhou, Wengang and Tian, Qi and Hong, Richang and Wang, Meng and Li, Houqiang}, booktitle={Proceedings...
import smtplib from email.mime.text import MIMEText import DonkeySimple.DS as ds import settings def send_email(send_to, subject, body): msg = MIMEText(body) msg['Subject'] = subject msg['From'] = settings.EMAIL_FROM msg['To'] = send_to try: if hasattr(settings, 'EMAIL_PO...
""" Cisco_IOS_XR_fretta_bcm_dpa_resources_oper This module contains a collection of YANG definitions for Cisco IOS\-XR fretta\-bcm\-dpa\-resources package operational data. This module contains definitions for the following management objects\: dpa\: Stats Data Copyright (c) 2013\-2017 by Cisco Systems, Inc. All ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-02-22 08:58 from __future__ import unicode_literals from django.db import migrations from bluebottle.utils.utils import update_group_permissions def add_group_permissions(apps, schema_editor): group_perms = { 'Authenticated': { 'pe...
class Table: def __init__(self): self.cells = [] def get_bbox(self): # (x1, y1), (x1, y2), (x2, y2), (x2, y1) # --> [x,y,width,height] # https://cocodataset.org/#format-data bounds = min(self.coords[0][0], self.coords[1][0]), \ min(self.coords...
from collections import OrderedDict import yaml from valohai_yaml.objs.config import Config # https://stackoverflow.com/questions/42518067/how-to-use-ordereddict-as-an-input-in-yaml-dump-or-yaml-safe-dump yaml.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( "tag:yaml.org,2...
#!/usr/bin/python import subprocess import os import time class wpa_supplicant: def __init__(self, iface): self.use_wrapper = False self.interface = iface def f2c(self, f): return int((f-2407)/5) def wpa_cli(self, cmd, *args): if self.use_wrapper: cli = './wpawrapper' else: cli = '/sbin/wpa_cli'...
"""class Node: def __init__(self, freq,data): self.freq= freq self.data=data self.left = None self.right = None """ # Enter your code here. Read input from STDIN. Print output to STDOUT def is_leaf(root): if root.right == None and root.left == None: return True ...
def isEven(bin1, bin2): if (int(list(bin1)[-1]) + int(list(bin2)[-1]))%2==0: return 'Yes' return 'No' if __name__ == "__main__": for tc in xrange(int(raw_input())): bins=raw_input().split() print isEven(bins[0],bins[1])
from flask import make_response from flask import Blueprint from flask import render_template from flask.ext.login import login_required from flask.ext.security.core import current_user from models import Session, OAuthTokens import tweepy import json import random settings_renderer = Blueprint('settings', __name__) ...
import LAT_formulas as form class LAT_getter: # input parameter is the process class from LAT_reader.py def __init__(self, p): # proton beam energies self.energy_a = p.init.energy_a self.energy_b = p.init.energy_b self.events = p.events # sqrt(s) = 13 GeV se...
import lightgbm as lgb import numpy as np from utils.other import calc_r2 class lgbm_regression(): def __init__(self,X_tr,Y_tr): self.X_tr = X_tr self.Y_tr = Y_tr self.train_data = lgb.Dataset(self.X_tr, label=self.Y_tr) def fit(self,params,val_data): X_val,Y_val = val_data ...
from torch.utils.data import IterableDataset, DataLoader from awsio.python.lib.io.s3.s3dataset import S3IterableDataset from PIL import Image import io from torchvision import transforms class ImageNetS3(IterableDataset): def __init__(self, url_list, shuffle_urls=False, transform=None): self.s3_iter_datas...
import glob import os import copy import numpy as np import torch import torch.nn as nn def init(module, weight_init, bias_init, gain=1): weight_init(module.weight.data, gain=gain) bias_init(module.bias.data) return module def get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i i...
from setuptools import setup # Requirements used for submodules plot = ['plotly>=4.0'] hyperopt = [ 'scipy', 'scikit-learn', 'scikit-optimize>=0.7.0', 'filelock', 'joblib', 'progressbar2', 'psutil', ] develop = [ 'coveralls', 'flake8', 'flake8-type-annotations', 'flake...
import numpy from matchms import Spectrum from matchms.similarity import ParentmassMatchParallel from matchms.similarity.ParentmassMatchParallel import \ calculate_parentmass_scores def test_parentmass_match(): "Test with default tolerance." spectrum_1 = Spectrum(mz=numpy.array([], dtype="float"), ...
from flask import Blueprint, jsonify, request from application import utils bp = Blueprint("api", __name__, url_prefix="/api") @bp.route("/draw", methods=["POST",]) def draw(): issued_numbers = utils.get_issued_numbers() number = utils.draw_number(issued_numbers) return jsonify(number=number) @bp.rou...
import logging from typing import Dict, List, Any import numpy as np import pandas as pd import torch from transfer_nlp.common.tokenizers import CustomTokenizer from transfer_nlp.embeddings.embeddings import Embedding from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.v...
from requests.auth import HTTPBasicAuth from py42.clients import Clients from py42.clients._archiveaccess.accessorfactory import ArchiveAccessorFactory from py42.clients.alertrules import AlertRulesClient from py42.clients.alerts import AlertsClient from py42.clients.archive import ArchiveClient from py42.clients.audi...
from test.test import run_test if __name__ == '__main__': run_test()
import morpheus_mcpi morpheus_mcpi.start()
import json from django.conf import settings def get_fixture_data(file_name): """ Converts json fixtures into python dict. Args: * `file_name` - `str` - the name of the file e.g. 'nation.json' """ with open(settings.BASE_DIR + '/core/fixtures/' + file_name, 'r') as f: data = f.re...
"""An example of streaming to allow a full implementation down the track""" import base64 import websocket import json STREAM_API = "wss://streaming.vn.teslamotors.com/connect" websocket.setdefaulttimeout(60) class Stream: def __init__(self, email, vehicle): # XXX Need to keep the login email address o...
# -*- coding:utf-8 -*- from __future__ import unicode_literals # import getemotion import json import itchat import requests # import platform import os import re import random import threading from beta import wav2text # 登录和初始化 # 设置已回复人员列表,限制刷消息的人 replied = {} userId = '' BASE_DIR = os.path.dirname(os.path.abspath(__...
from numpy import pi from SciDataTool.Functions.derivation_integration import integrate def comp_torque_MT(self): """Compute the rotor electromagnetic torque from Maxwell Stress Tensor. Parameters ---------- self : OutMag an OutMag object Returns ------- Tem_slice : ndarray ...