content
stringlengths
5
1.05M
import os from . import Engine, AnimationManager COLORKEY = (128, 160, 128) def getImages(home='./'): # General Sprites def general_sprites(root, files): for name in files: if name.endswith('.png'): full_name = os.path.join(root, name) IMAGESDIC...
""" This Plugin adds the capability of running distributed pytorch training to Flyte using backend plugins, natively on Kubernetes. It leverages `Pytorch Job <https://github.com/kubeflow/pytorch-operator>`_ Plugin from kubeflow. """ from dataclasses import dataclass from typing import Any, Callable, Dict from google.p...
import cv2 as cv import numpy as np # https://docs.opencv.org/4.2.0/d7/dfc/group__highgui.html def white_balance(img): result = cv.cvtColor(img, cv.COLOR_BGR2LAB) avg_a = np.average(result[:, :, 1]) avg_b = np.average(result[:, :, 2]) result[:, :, 1] = result[:, :, 1] - ((avg_a - 128) * (result[:, :, ...
def escorre_para_lado(geradores, matriz): novos_geradores = [] for coord in geradores: ref = coord[1] cont = 0 while matriz[coord[0] + 1][ref] == "#": cont += 1 ref += 1 for i in range(1, cont+1): matriz[coord[0]][coord[1]+i] = "o" mat...
from multiprocessing.managers import BaseManager from distributedSpider.HtmlDownloader import HtmlDownloader from distributedSpider.HtmlParser import HtmlParser class SpiderWork(object): def __init__(self): # 初始化分布式进程中的工作节点的连接工作 # 实现第一步:使用BaseManager注册获取Queue的方法名称 BaseManager.register('get_...
# 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 # "License"); you may not u...
class Node: def __init__(self, val): self.val = val self.next = None def reverse_linked_list(head): last = head nxt = last.next last.next = None while nxt: temp = nxt.next nxt.next = last last = nxt nxt = temp return last if __na...
from django.views.generic.detail import SingleObjectMixin from irekua_database.models import Annotation from irekua_database.models import Item from irekua_filters.annotations import annotations from selia.views.list_views.base import SeliaListView class ListAnnotationView(SeliaListView, SingleObjectMixin): pag...
""" NPS middleware used to set request attrs and cookies. When determining whether to display the NPS survey to user, we cache the output (True|False) so that we don't have to do a database lookup on each request. This value is added to the user session (so a max of one lookup per session. """ from __future__ import ...
# Bep Marketplace ELE # Copyright (c) 2016-2021 Kolibri Solutions # License: See LICENSE file or https://github.com/KolibriSolutions/BepMarketplace/blob/master/LICENSE # from django.urls import path, re_path from . import consumers websocket_urlpatterns = [ path('tracking/viewnumber/<int:pk>/', consumers.Curren...
# MIT License # # Copyright (c) 2020 Gcom # # 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, publish...
# license: Creative Commons License # Title: Big data strategies seminar. Challenge 1. www.iaac.net # Created by: Diego Pajarito # # is licensed under a license Creative Commons Attribution 4.0 International License. # http://creativecommons.org/licenses/by/4.0/ # This script uses pandas for data management for more i...
"""Advent of Code 2015 - Day 9.""" import itertools import re from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() class CityMap: """Map of cities and their mutual dista...
# -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab """ config ~~~~~~ Provides app configuration settings """ from __future__ import ( absolute_import, division, print_function, with_statement, unicode_literals) from os import path as p BASEDIR = p.dirname(__file__) PARENTDIR = p.dirname(BASEDIR) DB_NAME = ...
ESPER_COUNT = 27 RAMUH, IFRIT, SHIVA, SIREN, TERRATO, SHOAT, MADUIN, BISMARK, STRAY, PALIDOR, TRITOCH, ODIN, RAIDEN,\ BAHAMUT, ALEXANDR, CRUSADER, RAGNAROK, KIRIN, ZONESEEK, CARBUNKL, PHANTOM, SRAPHIM, GOLEM, UNICORN,\ FENRIR, STARLET, PHOENIX = range(ESPER_COUNT) id_esper = { 0 : "Ramuh", 1 : "Ifrit", ...
import asyncio, discord, time, parsedatetime from discord.ext import commands from datetime import datetime from Cogs import Utils, DisplayName, ReadableTime def setup(bot): # Add the bot and deps settings = bot.get_cog("Settings") bot.add_cog(Mute(bot, settings)) class Mute(commands.Cog): ...
import matplotlib matplotlib.use('tkagg') from matplotlib import pyplot as plt plt.rc('figure', figsize=[10, 6]) import time from data_models import * from prediction_models import * from control_models import * USE_RAY = False if USE_RAY: import ray def get_real_data(max_assets): sampler = RealData() ...
from project.appliances.fridge import Fridge from project.appliances.laptop import Laptop from project.appliances.tv import TV from project.rooms.room import Room from project.people.child import Child class YoungCouple(Room): def __init__(self, family_name: str, salary_one: float, salary_two: float): su...
from collections import Iterable import sympy as SYM import numpy as NP from scipy.integrate import quad from scipy.optimize import minimize_scalar from ..util.chapman import chapman_sym from ..gpstk import PyPosition class SlantIntegrator(object): def __init__(self, fun, stn_pos, height1=50, height2=2000): ...
# from time import sleep #print('Contagem regressiva!') # sleep(1) # c = 0 # f = 11 # while f != 0: # f -= 1 # print(f) # sleep(1) # print('Fim') #print('Somente os números pares entre 1 e 50... ') #c = 52 #while c != 2: # c -= 2 # print(c) #soma = conta = 0 #c = 1 #wh...
import numpy as np import torch import logging from torch.autograd import Variable from naslib.search_spaces.core.primitives import MixedOp from naslib.optimizers.core.metaclasses import MetaOptimizer from naslib.utils.utils import count_parameters_in_MB from naslib.search_spaces.core.query_metrics import Metric impo...
from kappagate import (overhangs_list_to_slots, predict_assembly_accuracy, plot_colony_picking_graph, success_rate_facts) overhangs = ['TAGG', 'GACT', 'GGAC', 'CAGC', 'GGTC', 'GCGT', 'TGCT', 'GGTA', 'CGTC', 'CTAC', 'GCAA', 'CCCT'] slots = overhangs_list_to_slots(overhan...
import argparse import numpy as np from PIL import Image def pad_image(image: Image, desired_size: tuple, pad_value: str='#fff') -> Image: """ pad image to make image in center. Args: image: PIL.Image: desired_size: tuple(int): (desired width, desired height) pad_value...
#!/usr/bin/env python3 """ Parses google maps timeline JSON, counts days spent at work """ import os import json import argparse import datetime def parse(file, place): """ parses the given file for visits to the specified place """ data = json.load(file) days = set() for obj in data["timelineObject...
import cv2 import numpy as np cap = cv2.VideoCapture(0,cv2.CAP_DSHOW) cap.open(0) while cap.isOpened(): flag, frame = cap.read() if not flag: break key_pressed = cv2.waitKey(60) # frame = cv2.resize(frame, (100,100)) frame = cv2.Canny(frame, 100, 200) frame = np.dstack((frame, frame,...
"""Example of a plug-in that will crash because of an import error""" # Third party imports import non_existent_package # noqa # PyPlugs imports import pyplugs @pyplugs.register def a_plugin(): """A plug-in that will not work, due to an import error""" return "I wish"
import os import pathlib import re import requests from urllib.parse import urlparse, unquote from girder.utility.model_importer import ModelImporter from girder.models.folder import Folder from .import_providers import ImportProvider from .resolvers import DOIResolver from .entity import Entity from .data_map import...
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm mnist = input_data.read_data_sets("/tmp/tensorflow/mnist/", one_hot=True) latent_size = 2 batch_size = 128 epochs = 25 initializer = tf.contrib....
#!/usr/bin/env python import os import sys import time from cmd import Cmd from optparse import OptionParser from pprint import pprint from tsdb import * VERSION="0.37" class TSDBCLI(Cmd): """Implements a simple CLI for inspecting TSDBs""" def __init__(self, db_path): Cmd.__init__(self) se...
from glob import glob import os import pandas as pd from torch import tensor from torchvision.ops import box_convert from annotation_utils.utils import extract_width_and_height, list_images, read_annotation_lines """ Creates CSV file with the following structure: image_name,layout,x,y,width,height ... ... ...
from functools import partial import colossalai import pytest import torch.multiprocessing as mp from colossalai.amp import AMP_TYPE from colossalai.core import global_context as gpc from colossalai.utils import free_port from tests.components_to_test.registry import non_distributed_component_funcs from colossalai.tes...
import random TRN_STATUSES = ['FAILED', 'INPROGRESS', 'INVALID','SUCCESSFUL'] def get_trasfer_status(trn_id): return TRN_STATUSES[random.randint(0, len(TRN_STATUSES)-1)]
from typing import Any, Callable, List import torch from torch import Tensor, nn from torch.linalg import norm reductions = {"mean": torch.mean, "sum": torch.sum} class Regularizer(nn.Module): """Wrapper class, just for naming. """ class MultiModalScaling(Regularizer): def __init__(self, reduction: s...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
from .image import ImageViewSet from .user import users_logout_view, users_me_view __all__ = ['ImageViewSet', 'users_logout_view', 'users_me_view']
""" Project OCELoT: Open, Competitive Evaluation Leaderboard of Translations """ from pathlib import Path from tempfile import NamedTemporaryFile from zipfile import ZIP_DEFLATED from zipfile import ZipFile from django.contrib import admin from django.http import FileResponse from leaderboard.models import Competitio...
import typing from ..repo import description from . import Command class Fetch(Command): """ Fetch all remotes for all repositories """ LOCAL = True FILTER = True def run(self, repo: description.RepositoryDescription) -> bool: if not repo.local.exists(): return False re...
############################################### # RabbitMQ in Action # Chapter 10 - Queue count (HTTP API) check. ############################################### # # # Author: Jason J. W. Williams # (C)2011 ############################################### import sys, json, httplib, urllib, base64, socket #(aqcc.0) N...
# Copyright (c) 2020 PaddlePaddle 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 app...
import json import cv2 path = "/home/mingxuzhu/Program_Design/CenterNet/data/rear_headlight/annotations/train.json" res = json.load(open(path)) img_dir = "/home/mingxuzhu/Program_Design/CenterNet/data/rear_headlight/images/train/" new_anno = {} categories = [{'supercategory': 'vehicle(v)', 'id': 1, 'name': 'vehicle...
# # Copyright 2018-2019 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...
""" wrap ssd-1 ready for correlating output from heatmap and ssd modules """ ############################################################################# # Imports ############################################################################# from keras import backend as K import keras.preprocessing.image as kg fr...
from .yolox_s import Exp as YoloxSCfg
from twisted.application.service import ServiceMaker octopus_editor = ServiceMaker( name='octopus-editor', module='blocktopus.server.tap', description='Run the octopus editor service.', tapname='octopus-editor' )
#!/usr/bin/env python # coding: utf-8 # BEGIN --- required only for testing, remove in real world code --- BEGIN import os import sys THISDIR = os.path.dirname(os.path.abspath(__file__)) APPDIR = os.path.abspath(os.path.join(THISDIR, os.path.pardir, os.path.pardir)) sys.path.insert(0, APPDIR) # END --- required only f...
from typing import Any, Optional, Type from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.dispatcher.storage import FSMContextProxy GLOBAL_CONTEXT = "__AIOGD_G_CONTEXT" DIALOG_CONTEXT = "__AIOGD_D_CONTEXT" DIALOG_INTERNAL_CONTEXT = "__AIOGD_ID_CONTEXT" LAST_MESSAGE_ID = "LAST_MESSAGE_ID" F...
""" NOT DONE YET Class for receding horizon player AI. Use to aquire the next desired paddle state based on curret paddle state and puck state. """ ################################################# DEPENDENCIES from __future__ import division import numpy as np import numpy.linalg as npl ##########################...
from dataclasses import dataclass from typing import Callable, Iterator from sqlalchemy.orm import Session from app.adapters.spi.circuit_repository import CircuitRepository from app.adapters.spi.session import SessionLocal from app.ports.api import GetCircuitUseCase from app.services.circuit_service import CircuitSer...
import torch import argparse import wandb import os.path from os import path def parse_args(): parser = argparse.ArgumentParser( description='This script extracts backbone weights from a checkpoint') parser.add_argument('output', default=None, type=str, help='destination file name') parser.add_arg...
import time #from Display import display #from Updater import updater #import Feature import os import threading import socket ''' Monitor water level every 10 seconds If greater than xxx turn on pump for yyy if not switched less than zzz turn off pump in xxx Also monitor switch. If switch changed to 0 set switched t...
import sys import typing import numba as nb import numpy as np @nb.njit((nb.i8[:, :], ), cache=True) def solve(ab: np.ndarray) -> typing.NoReturn: n = len(ab) a, b = ab[:, 0], ab[:, 1] a.sort() b.sort() if n & 1: s = b[n >> 1] - a[n >> 1] + 1 else: s = b[n >> 1] + b[(n >> 1) - 1] ...
import unittest import dwmon class CronTests(unittest.TestCase): def test_parse_requirements(self): cron_string = "CHECKHOURS0-9 CHECKMINUTES0-10 " \ "WEEKDAYS MINNUM5 MAXNUM20 LOOKBACKSECONDS3600" result = dwmon.parse_requirements(cron_string) self.assertTrue(result["check_ho...
import matplotlib.pyplot as plt import matplotlib_scalebar.scalebar as scale from adjustText import adjust_text import numpy as np import pandas as pd # スポット分析の描画 def plot_point(ax, x, y, points, crystals): ax.plot(x, y, "o", mec="w", c="r") # adjust_text()に渡すためにリストに格納する texts = [ plt.te...
# -*- coding: utf-8 -*- """ Copyright (c) 2018-2019 Masahiko Hashimoto <hashimom@geeko.jp> 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...
from schemas import PodResourcesConfig def get_affinity(affinity, default_affinity): return affinity or default_affinity def get_tolerations(tolerations, default_tolerations): return tolerations or default_tolerations def get_node_selector(node_selector, default_node_selector): return node_selector or...
from .apis import DataDragonAPI, ChampionAPI, ChampionMasteryAPI, LeagueAPI, MatchAPI, SpectatorAPI, SummonerAPI class RiotAPY: """ Initiate a RiotAPY class, from which all API calls will be made. :param str api_key: API key .. note:: Your API key can be found over `here <https://developer.riotgames...
import json import os from config.cst import CONFIG_DATA_COLLECTOR_PATH, PriceIndexes class DataCollectorParser: @staticmethod def parse(file): if os.path.isfile(CONFIG_DATA_COLLECTOR_PATH + file): with open(CONFIG_DATA_COLLECTOR_PATH + file) as file_to_parse: file_content...
#!/usr/bin/python # Copyright (c) 2016, Globo.com <https://github.com/globocom> # This file is part of globocom/zabbix-scripts # (see https://github.com/globocom/zabbix-scripts). # License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause import re import commands import string from os import path from sy...
from django.core.urlresolvers import reverse_lazy from django.views.generic import ListView from django.views.generic.base import RedirectView from django.views.generic.detail import DetailView from meta.views import MetadataMixin from ..blog.helpers import Meta from ..utils.views import BaseViewMixin, RelatedListMix...
from setuptools import setup setup( name='fastly_debug', version='0.1.0', scripts=['fastly_debug'] )
""" Extract mel-spectrogram features and mu-law encoded waveforms from wav files """ import os from argparse import ArgumentParser from pathlib import Path import jax import librosa import numpy as np from tqdm.cli import tqdm from dsp import MelFilter from utils import load_config def extract_mel_mu( mel_filt...
import random import time from hashlib import md5 def _create_row(fields, values): row = Row(*values) row.__fields__ = fields return row class Row(tuple): """ A row in L{DataFrame}. The fields in it can be accessed like attributes. Row can be used to create a row object by using named argu...
from django.forms.models import modelform_factory class GenericViewWidgetMixin: """ Enables widgets property in django generic view classes. usage: class CreateView(GenericViewWidgetMixin, generic.edit.CreateView): model = MyModel fields = ['field1', 'field2'] ...
from .view import ModelView
import http import fastapi import fastapi.concurrency import mlrun.api.crud import mlrun.api.initial_data import mlrun.api.schemas import mlrun.api.utils.background_tasks from mlrun.utils import logger router = fastapi.APIRouter() current_migration_background_task_name = None @router.post( "/operations/migra...
import re from django.core.urlresolvers import reverse, reverse_lazy from django.db.models import Sum from django.http import HttpResponseNotAllowed from django.shortcuts import redirect, render from django.utils.translation import ugettext_lazy from django.views import generic from utils import pdf from athletes.mod...
import ply.lex as lex from prettytable import PrettyTable keywords = ('this', 'class', 'void', 'super', 'extends', 'implements', 'enum', 'interface', 'byte', 'short', 'int', 'long', 'char', 'float', 'double', 'boolean', 'null', 'true', 'false', 'final', 'public', 'protected', 'private', 'abstract', 'static'...
# Question: https://projecteuler.net/problem=700 # coin n # 1 1504170715041707 1 # 2 8912517754604 3 # 3 2044785486369 506 # 4 1311409677241 2527 # 5 578033868113 4548 # 6 422691927098 11117 # 7 267349986083 ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __a...
#JARVIS mark 10. python 3.5.1 version #JUST.A.RATHER.VERY.INTELEGENT.SYSTEM. import speech_recognition import datetime import os import random import datetime import webbrowser import time import calendar from difflib import SequenceMatcher import nltk from nltk.tokenize import sent_tokenize, word_tokenize ...
# encoding=utf8 """Monkey king evolution algorithm test case module.""" from unittest import TestCase import numpy as np from numpy import random as rnd from WeOptPy.task.interfaces import Task from WeOptPy.algorithms import ( MonkeyKingEvolutionV1, MonkeyKingEvolutionV2, MonkeyKingEvolutionV3 ) from WeOptPy.alg...
class GPGException(Exception): """ Base app exception. """ class DecryptionError(GPGException): """ Raised when an error occurs while trying to decrypt and encrypted file. """ class KeyFetchingError(GPGException): """ Unable to receive key or key not found. """ class KeyDoesNot...
from pycordia import models import pycordia import dotenv import os dotenv.load_dotenv() client = pycordia.Client(intents=pycordia.Intents.all()) @client.event async def on_message_create(message: models.Message): if message.author.bot or not message.content: return if message.content.startswith(".p...
# Generated by Django 2.2.1 on 2020-03-09 21:30 from django.conf import settings import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('address'...
#!/usr/bin/env python """ # Author: Xiong Lei # Created Time : Thu 31 May 2018 08:45:33 PM CST # File Name: __init__.py # Description: """ __author__ = "Lei Xiong" __email__ = "jsxlei@gmail.com" from .layer import * from .model import * from .loss import *
import torch import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader, Dataset import torch.nn as nn from torch.optim import lr_scheduler from torchvision import datasets, models, transforms import torch.nn.functional as F import sys...
from django.contrib import admin from .models import Topic from .models import Topic, Entry # Register your models here. admin.site.register(Topic) admin.site.register(Entry)
# coding: utf-8 """ FastScore API (proxy) No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 1.7 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys impo...
from rpython.jit.codewriter.effectinfo import EffectInfo from rpython.jit.metainterp.history import (Const, ConstInt, ConstPtr, get_const_ptr_for_string, get_const_ptr_for_unicode, REF, INT, DONT_CHANGE, CONST_NULL) from rpython.jit.metainterp.optimizeopt.optimizer import ( CONST_0, CONST_1, REMOVED, Optimi...
from sphero.request.spherorequest import SpheroRequest class SetBackLed(SpheroRequest): CID = 0x21 FMT = '!B'
import atexit from collections import defaultdict import fnmatch import hashlib import os import stat import re import shutil import threading import time import traceback from decorator import decorator import pkg_resources from .simpleuri import UriParse, uri_from_parts from .exceptions import (NoSchemeError, ...
import os import sys import unittest import mock from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.unittest import skipIf from classsettings import Settings, Config, from_env, utils from classsettings.urls import Context, Scope, url IS_ABOVE_26 = sys.version_...
import tkinter as TK from tkinter.filedialog import askopenfilename from astropy.io import fits import numpy as np import pandas as pd import time from KinMS import KinMS #from IPython import get_ipython #ipython = get_ipython() #ipython.magic("gui tk") #Import GUI functions import GUIFunctions as GU...
import unittest from pieces.queen import Queen from board import Board class TestSum(unittest.TestCase): def test_no_movement(self): board = Board() queen1 = Queen("W", 7, 0, board) queen2 = Queen("W", 6, 1, board) queen3 = Queen("W", 6, 0, board) queen4 = Queen("W", 7, 1,...
from sentence_transformers.evaluation import SentenceEvaluator, SimilarityFunction import torch from torch.utils.data import DataLoader import logging from tqdm import tqdm from sentence_transformers.util import batch_to_device import os import csv from sklearn.metrics.pairwise import cosine_distances import numpy as n...
# sublimelint.py # SublimeLint is a code checking framework for Sublime Text # # Project: https://github.com/lunixbochs/sublimelint # License: MIT import sublime import sublime_plugin import os from threading import Thread import time import json from .lint.edit import apply_sublimelint_edit from .lint.edit import E...
"""The back-end API application for interacting with plant data. API [wip] /plants {GET} /plants/<id> {GET} """ from flask import Flask app = Flask(__name__) if __name__ == '__main__': app.run(debug=True)
from AmazonSQSMessage import AmazonSQSMessage class WatermarkJobMessage (AmazonSQSMessage): """ Interface for a WatermarkJob message. """ def __init__ (self, name = None, username = None, contentWidth = None, contentHeight = None, contentType = None, bucket = None, destinationBucket = None, filePath =...
import asyncio import os from loguru import logger from tortoise import Tortoise from rearq import ReArq, Task from rearq.server import models rearq = ReArq(delay_queue_num=2, keep_job_days=7) @rearq.on_shutdown async def on_shutdown(): logger.debug("rearq is shutdown") await Tortoise.close_connections() ...
# Copyright 2014 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...
# -*- coding: utf8 -*- import datetime from bs4 import BeautifulSoup import urllib.request from datetime import date import calendar my_date = date.today() day = str(calendar.day_name[my_date.weekday()]) date = str(datetime.date.today()) link = "http://www.defimedia.info" content = str(urllib.request.ur...
''' This performs some statistical manipulations on distributions given in series It has no state ''' from scipy import stats def compareDistributionsMannWhitney(distA, distB, sig_level, htmlise=False): distA.sort() distB.sort() u_statistic, p_value = stats.mannwhitneyu(distA,distB) diver = "\n" ...
from nacl.encoding import HexEncoder from nacl.secret import SecretBox from nacl.signing import SigningKey import nacl.utils from nacl.public import PrivateKey, Box def symmetric_encrypt(message: str) -> dict: key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE) box = SecretBox(key) result = box.encryp...
from flask import redirect from flask import jsonify from flask import request from flask import session from app.model.tables.users import User from .utils import nonLogin class Login(object): @classmethod @nonLogin def loginPost(cls, *args, **kwargs): data = request.form.to_dict() or ...
# stdlib import logging from datetime import datetime from typing import Dict # lib from cloudcix.api import Membership from cloudcix.auth import get_admin_token from dateutils import relativedelta from django.conf import settings from rest_framework.test import APITestCase __all__ = [ 'TestBase', ] class TestB...
project = 'Basic docs-versions-menu test' import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] extensions = [ 'docs_versions_menu', ] docs_versions_menu_conf = dict( menu_title="Docs", )
# Copyright 2020 The T5 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 writi...
'''demo3_harness_telemetry_job.py Please read the README file. ''' # # optional author information # __author__ = 'Cisco Systems Inc.' __copyright__ = 'Copyright (c) 2018, Cisco Systems Inc.' __contact__ = ['pyats-support-ext@cisco.com'] __date__= 'April 2018' # # import block # import os from genie.harness.main im...
from unittest import TestCase class TestBatteryStatsService(TestCase): def test_stop(self): self.assertTrue(True)
''' Author: jianzhnie Date: 2021-12-20 15:43:53 LastEditTime: 2021-12-22 09:33:07 LastEditors: jianzhnie Description: ''' import torch import torch.nn as nn def sequence_mask(X, valid_len, value=0): """Mask irrelevant entries in sequences.""" maxlen = X.size(1) mask = torch.arange((maxlen), dtype=torch....