content
stringlengths
5
1.05M
import numpy as np import pandas as pd from ..abstract_base_classes.solver_abc import SolverABC from scipy.optimize import Bounds, LinearConstraint, basinhopping, minimize from ....models.strategy_optimal import StrategyOptimal __all__ = ['StrategyOptimalSolver'] #DIVIDER = 10**6 DIVIDER = { 'SBER': 10**6, ...
import pandas as pd import numpy as np import pickle import os import sys sys.path.append(os.path.abspath(os.path.join('.'))) from graph_creation_helpers import sqlite_to_table import warnings warnings.filterwarnings('ignore') def calc_max_reviews_in_day(df: pd.DataFrame) ->pd.DataFrame: reviews_df = df[['Upda...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ------------------------------------------------- File Name:class Description : lightGBM 分类实例 with early-stopping sklearn API 1. https://lightgbm.readthedocs.io/en/latest/Python-API.html#scikit-learn-api Email : autuanliu@163.com Date:2018/3/20 """ from...
# Generated by Django 3.0.10 on 2021-01-19 08:47 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0042_auto_20210119_0818'), ] operations = [ migrations.CreateModel( name='Position', ...
# Copyright (c) 2021 Matthew Scroggs # FEniCS Project # SPDX-License-Identifier: MIT import basix import pytest import numpy import sympy one = sympy.Integer(1) x = sympy.Symbol("x") y = sympy.Symbol("y") z = sympy.Symbol("z") @pytest.mark.parametrize("degree", range(6)) @pytest.mark.parametrize("cell_type", [ ...
class backend: # API Definitions def list_components(): ''' Returns a list of all component names available to the backend ''' pass def def_component(name: str, version=None: str): ''' Returns a definition of the component for the given name. Can retu...
#!/usr/bin/env python from getpass import getpass from sys import exit password = getpass() cisco3 = dict( host= 'cisco3.lasthop.io', username= 'pyclass', password= password, device_type= 'cisco_ios', ) arista1 = dict( host= 'arista1.lasthop.io', username= 'pyclass', password= password, ...
#!/usr/bin/env python import argparse import struct import sys import copy import ipdb import rospy from std_msgs.msg import ( Empty, Header ) import copy from baxter_core_msgs.msg import EndpointState from sensor_msgs.msg import JointState from geometry_msgs.msg import WrenchStamped from birl_baxter_tasks.m...
from ClauseAnalysis.FilePreprocess import * from ClauseAnalysis.SentenceExtractor import * import re critical_words = [] def sentence_filter(sentences): good_sentences = [] bad_sentences = [] for sentence in sentences: if contains_critical_word(sentence): good_sentences.append(senten...
# -*- coding: utf-8 -*- """ Created on Tue Nov 9 10:15 2018 @author: Kashyap Thimmaraju @email: kashyap.thimmaraju@sect.tu-berlin.de """ ''' Functions to configure the servers for the desired traffic scenario/topology, vswitch mode and resource allocation. The specific configuration for each permutation is specified...
import logging from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from config import Config class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: ...
import math a, b, c = input().split() #Recebe valores inteiros# a = int(a) b = int(b) c = int(c) d = int(d) maior1 = (a + b + abs(a - b)) / 2 maior2 = (maior1 + c + abs(maior1 - c)) / 2 print("{} eh o maior".format(int(maior2)))
from UnstructuredCAEDA.settings.base_CAE import CAEConfig class Baseline1(CAEConfig): """This model is the baseline CAE in my report and is *similar* to the model described in: LOSSY IMAGE COMPRESSION WITH COMPRESSIVE AUTOENCODERS (2017), Theis et al. http://arxiv.org/abs/1703.00395 Note: this c...
import time from typing import * # use type hints to make signatures clear import wrappers # the function that will be executed on a thread def f() -> List[int]: print("f() will sleep for 500 ms") time.sleep(0.5) return [i for i in range(200)] # return a large list # spawn a thread t = wrappers.Threa...
import wx import os import time import threading from RomUtils import RomUtils class RomFrame(wx.Frame): def __init__(self): self.endcallback = None self.ser = None self.amiga = None self.execlib = None self.doslib = None self.snip = None self.abort = threadin...
from collections import defaultdict,OrderedDict from setup_logger import logger import time import numpy as np import talib import math import statistics as s class InstrumentObject(): def getName(self): return self.name def getValue(self): return self.value def getPrice(self): ...
import os import numpy as np import random import argparse import utils import defenses import math import torch import torchvision.datasets as datasets import torchvision.models as models import torchvision.transforms as trans from boundary_attack_simple import boundary_attack parser = argparse.ArgumentParser(descrip...
""" Main file We will run the whole program from here """ import torch import hydra from train import train from dataset import MyDataset, CocoImages from models.base_model import MyModel from torch.utils.data import DataLoader from utils import main_utils, train_utils, data_loader from utils.train_logger import Trai...
from datetime import date, datetime, timedelta from typing import List, Union def daterange( start: datetime, stop: datetime, step: timedelta = timedelta(days=1), inclusive: bool = False ): # source: https://stackoverflow.com/a/1060376/1940450 if step.days > 0: while start < stop: yiel...
# Copyright (c) 2005 Gavin E. Crooks <gec@threeplusone.com> # # This software is distributed under the MIT Open Source License. # <http://www.opensource.org/licenses/mit-license.html> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation f...
async def banUser(plugin, ctx, user, reason, log_type, ban_type, days=0): try: await ctx.guild.ban(user, reason=reason, delete_message_days=days) except Exception as ex: return await ctx.send(plugin.t(ctx.guild, "ban_failed", _emote="WARN", error=ex)) else: plugin.bot.ignore_for_e...
from neo4jclient.AbsClient import AbstractClient class VulnerabilityCompClient(AbstractClient): def __init__(self, password, **kwargs): super().__init__(password=password, **kwargs) def create_shadowserver_part(self, path): """ Create nodes and relationships for vulnerability_compone...
from tkinter import * class Janela(Tk): def __init__(self): super().__init__() def nome(self, nome:str='Janela principal'): super().title(nome) def dimensoes_com_espaco(self, largura=200, altura=200, espaco_a_direita=200, espaco_acima=200): super().geometry(f'{largura}x{altura}+{...
from .template import ConfigTemplate from .utilities import Files, State class NetDefine: def __init__(self, root, environment='local'): self.environment = environment self.files = Files(root=root, environment=self.environment) self.templates = self.files.templates self.features = ...
# %% import pandas as pd import requests import json import os from dotenv import load_dotenv load_dotenv() from pathlib import Path headers = { "Content-Type": "application/json", "pinata_api_key": os.getenv("PINATA_API_KEY"), "pinata_secret_api_key": os.getenv("PINATA_SECRET_API_KEY"), } def convert_df_...
# -*- coding: UTF-8 -*- import torch.nn as nn from models.BaseModel import GeneralModel class Tensor(GeneralModel): @staticmethod def parse_model_args(parser): parser.add_argument('--emb_size', type=int, default=64, help='Size of embedding vectors.') parser.add_ar...
# -*- coding: utf-8 -*- """ml-m6-rfr.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1ZLKuu-cbBqHBqw30dg4Fe0b90p2yicbr """ #importing libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #dataset dataset = pd.read_csv...
from rest_framework import serializers from .models import University, Department, Course class UniversitySerializer(serializers.ModelSerializer): class Meta: model = University fields = '__all__' class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department...
from setuptools import setup setup(name='dappled-core', version='0.1.0', packages=['dappled_core'], include_package_data=True, # use MANIFEST.in # package_data={ # 'dappled_core' : [ # 'static/*', # 'templates/*', # 'nbserver_extension/*' # ...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import re import reprlib RE_WORD = re.compile('\w+') class Sentence: def __init__(self, text): self.text = text self.words = RE_WORD.findall(text) def __repr__(self): return 'Sentence(%s)' % reprlib.repr(self.text) def __iter__(s...
# Generated by Django 2.2.4 on 2019-08-27 12:53 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import movie.utilities class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('m...
# To import required modules: import numpy as np import time import os import sys import matplotlib import matplotlib.cm as cm #for color maps import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec #for specifying plot attributes from matplotlib import ticker #for setting contour plots to log scale im...
# Copyright 2013 VMware, 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...
#!/usr/bin/env python2.7 from configparser import SafeConfigParser import sys import boto.sqs import boto.s3.connection import boto.ec2 import boto.sqs from time import sleep import subprocess config = SafeConfigParser() config.read('config.ini') def fill_config(): print('Prompting to set unset options in config...
#!/usr/bin/env python3 ############################################################################## # # # Program purpose: Reverse the digits of a given number and add it to # # the original, if the sum is not a...
# -*- coding:utf-8 -*- ''' @file get_ozone_data.py @brief get ozone concentration, A concentration of one part per billion (PPB). @n step: we must first determine the iic device address, will dial the code switch A0, A1 (ADDRESS_0 for [0 0]), (ADDRESS_1 for [1 0]), (ADDRESS_2 for [0 1]), (ADDRESS_3 for [1 1]). ...
# (c) 2014 jano <janoh@ksp.sk> # Various types of messages with colors import sys from enum import Enum class Status(Enum): ok = 0 wa = 1 tle = 2 exc = 3 ce = 4 # not used yet err = 5 valid = 6 def __str__(self): return self.name.upper() def colored(self, end=None): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 4 17:10:34 2021 @author: yanni """ import os, glob, h5py, torch import numpy as np import sigpy as sp from tqdm import tqdm from bart import bart from torch.utils.data import Dataset # Plain, single-shot load def get_motion_data(anatomy, contras...
# Generated by Django 2.1.5 on 2019-03-24 01:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0006_auto_20190324_0040'), ] operations = [ migrations.AddField( model_name='serveruser', name='host', ...
import discord from discord.ui import Button, View from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) GUILD_ID = 123 TEAM_ROLE = 123 TICKET_CHANNEL = 123 CATEGORY_ID = 123 @bot.event async def on_ready(): print("Online!") @bot.command() async def ticketmsg(ct...
import os from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db.models.loading import get_model HEADER = """\ ####################################################################### # # Note: This file is a generated file--do not edit it directly! # Instead...
import datetime from urllib.parse import urlencode import scrapy from gazette.items import Gazette from gazette.spiders.base import BaseGazetteSpider class PiTeresina(BaseGazetteSpider): TERRITORY_ID = "2211001" name = "pi_teresina" allowed_domains = ["dom.pmt.pi.gov.br"] start_date = datetime.date(...
""" Escreva um programa que leia a velocidade de um carro se ele ultrapassa 80 km/h mostre uma msg dizendo que ele foi multado a multa vai custar 7.00 por km a cima do limite.""" velocidade = int(input('Velocidade do carro: ')) calculo_da_multa = (velocidade - 80) * 7 if velocidade > 80: print(f'Infelizmente você...
""" Info Endpoint. Querying the info endpoint reveals information about this beacon and its existing datasets and their associated metadata. * ``/`` Beacon-v1 * ``/info`` Beacon-v1 * ``/info?model=GA4GH-ServiceInfo-v0.1`` GA4GH * ``/service-info`` GA4GH .. note:: See ``beacon_api`` root folder ``__init__.py`` and ...
from .compute_metric import compute_metrics
from config.db import Db class ControllerUser(object): def setNome(self, nome): self.nome = nome def setEmail(self, email): self.email = email def setCidade(self,cidade): self.cidade = cidade def setUf(self, uf): self.uf = uf def AddUser(self): datab...
from django.contrib import admin from .models import UserModel admin.site.register(UserModel)
#!/usr/bin/python # -*- coding: UTF-8 -*- import RPi.GPIO as GPIO import time class RGBLedSetter: def __init__(self): self.R_LED = 11 # GPIO17 self.G_LED = 12 # GPIO18 self.B_LED = 13 # GPIO27 GPIO.setwarnings(False) # Disable warnings GPIO.setmode(G...
"""Take list of JIRA issues and write them into a directory as text files """ from __future__ import absolute_import from __future__ import print_function import logging import os from progressbar import ProgressBar def textlines(issue): """Yield a bunch of results Now I'm just showing off because I think ...
import os import re import sublime from unittesting import DeferrableTestCase from GitSavvy.tests.mockito import when, unstub from GitSavvy.tests.parameterized import parameterized as p import GitSavvy.core.commands.diff as module from GitSavvy.core.commands.diff import GsDiffCommand, GsDiffRefreshCommand THIS_DIR...
"""Pipeline for the FIC dataset (didn't end up using for the paper)""" import math import os import tensorflow as tf from tensorflow.python.platform import gfile from absl import logging AUTOTUNE = tf.data.experimental.AUTOTUNE NUM_CHANNELS = 3 EVENT_NAMES_MAP = {"label_1": ["Idle", "Intake"]} NUM_TRAINING_FILES = 20...
import shutil import sys import os import pickle from sklearn.utils import shuffle from nnexpy import DataDescriptor, DataPoint, DataInstance import numpy as np import subprocess import json randomSeed = 468643654 dataDescriptorList = [ DataDescriptor(dimension=3, nHoles=3, holeDimension=[2, 2, 3 ...
import time import threading import logging import departure.board.data_updater as data_updater from departure.commons.log import log_function_stdout_to_debug from . import national_rail, view_model, ui logger = logging.getLogger(__name__) class DataUpdaterNationalRail(data_updater.DataUpdater): def __init__( ...
import json, requests, datetime, random, os from bs4 import BeautifulSoup __USER_AGENT_URL__ = 'http://www.useragentstring.com/pages/useragentstring.php?name={}' class UserAgent(object): """The UserAgent class generates random UserAgent strings """ __DATA_PATH = os.path.abspath( os.path.join(o...
# ASSIGNMENT 3 # State abbreviation -> Full Name and visa versa. FL -> Florida, etc. # (Handle Washington DC and territories like Puerto Rico etc.) from pandas import DataFrame class DataProcessor(): def __init__(self, state_df): ''' Parameters: my_df (pandas.DataFrame) has a column ca...
import sys import mcpi.block import mcpi.minecraft from mcthings.scene import Scene from mcthings.server import Server from mcthings.world import World from minecraftstuff import MinecraftDrawing BUILDER_NAME = "ElasticExplorer" MC_SEVER_HOST = "localhost" MC_SEVER_PORT = 4711 def main(): try: World.c...
""" Bluetooth client for android phones """ from jnius import autoclass from Queue import Queue import threading class BlueberryClient(object): def __init__(self): self.BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter') self.BluetoothDevice = autoclass('android.bluetooth.Bluetoo...
"""Unit test package for Tilapya."""
class Solution: def getRow(self, rowIndex: int) -> list[int]: if rowIndex == 0: return [1] row = [1, 1] for _ in range(1, rowIndex): new_row = [1] for i in range(len(row)-1): new_row.append(row[i] + row[i+1]) new_row.append(1)...
# -*- coding: utf-8 -*- # prueba de inferencia con el entrenamiento del dataset IA418 import os os.environ['CUDA_VISIBLE_DEVICES'] = '-1' device_count={'GPU': 0} import tensorflow as tf import argparse argparser = argparse.ArgumentParser( description='inferencia con el entrenamiento de IA418') argp...
#!/usr/bin/env python3 import sys import csv fields = ['govuk', 'government-organisation'] sep = '\t' print(sep.join(fields)) # read register data government_organisation = {} for row in csv.DictReader(open(sys.argv[1]), delimiter=sep): government_organisation[row['government-organisation']] = row for row in c...
class UnionFind: def __init__(self, n): # 初始化 self.fa = [i for i in range(n)] # 每个元素的集合编号初始化为数组 fa 的下标索引 self.rank = [1 for i in range(n)] # 每个元素的深度初始化为 1 def find(self, x): # 查找元素根节点的集合编号内部实现方法 while self.f...
# -*- coding: utf-8 -*- import logging logger = logging.getLogger('django_rest_client') class BaseException(Exception): """ A base class for exceptions in this module... """ def __init__(self, cause=None, *args, **kwargs): # # Call the base constructor. # super(Exce...
# -*- coding:utf-8 -*- # /usr/bin/env python """ Author: Albert King date: 2019/12/29 0:11 contact: jindaxiang@163.com desc: """ import json import requests def get_option_dates(symbol='50ETF', exchange='null'): url = f"http://stock.finance.sina.com.cn/futures/api/openapi.php/StockOptionService.getStockName?" \...
from logzero import logger
import csv import logging import pickle from typing import List, NamedTuple import click from company_graph.cg import CompanyGraph logger = logging.getLogger(__name__) class NameEdge(NamedTuple): source: str target: int n: int def read_rows(fp, cg: CompanyGraph) -> List[NameEdge]: rows = [] w...
import collections import random import os def get_random_team(): this_dir, this_file = os.path.split(__file__) DATA_PATH = os.path.join(this_dir, "data/teams/teams.txt") teams = [] with open(DATA_PATH, 'r') as f: for line in f: tokens = line.rstrip('\n').split(',') tea...
# Written by: Nick Gerend, @dataoutsider # Viz: "Big Screen", enjoy! from math import sqrt, sin, cos, pi class point: def __init__(self, index, row, column, item, x, y, path = -1, value = -1): self.index = index self.row = row self.column = column self.item = item self.x =...
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import pytest from flask import session from indico.modules.categories.models.categories import EventCrea...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Mar 23 13:20:15 2019 @author: chin-weihuang """ from __future__ import print_function import numpy as np import torch import matplotlib.pyplot as plt # plot p0 and p1 plt.figure() # empirical xx = torch.randn(10000) f = lambda x: torch.tanh(x*2+1) ...
# 给定一个有序整数型和一个整数,在其中找两个元素,使其和为target。返回两个数的索引 # 说明: # 返回的下标值(index1 和 index2)不是从零开始的。 # 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 from typing import List # 使用对撞指针 class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: left = 0 right = len(numbers) - 1 # 由于不能使用相同的数字,所以左右指针...
from abc import ABC, abstractmethod class IUser(ABC): firstname: str lastname: str @abstractmethod def get_addresses(self): pass @abstractmethod def get_all_user_data(self): pass class RealUser(IUser): def __init__(self, firstname, lastname): self.firstname = fi...
import numpy as np import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import snn.network as snn dt = 0.1 size = 1000 external_input = 5 parameters = {'a': 0.02, 'b': 0.2, 'c': -65, 'd': 8} W = np.random.normal(0, 1, size=(size, size)) graph = tf.Graph() with graph.as_default(): N = snn.Izhi_Nucleus(size, ...
# Generated by Django 2.0.3 on 2018-08-13 09:02 import apps.contracts_uis.validators import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contracts_uis', '0002_auto_20180805_1407'), ] operations = [ migrat...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals, annotations) import time # Everyone in queue, and their desired order def get_customers(): return [('Bob', 'Ham Sandwich'), ('Paul', 'Grilled Cheese'), ...
""" Definition of the RailEnv environment and related level-generation functions. Generator functions are functions that take width, height and num_resets as arguments and return a GridTransitionMap object. """ import numpy as np from flatland.core.grid.grid4 import Grid4TransitionsEnum from flatland.core....
""" 函数相互调用 """ # -------------函数--------------- def attack(): print("直拳") return "ok" def repeated_attack(count): list_result = [] for i in range(count): result = attack() list_result.append(result) return list_result # -------------入口--------------- res = repeated_attack(1) p...
""" Utilities for managing chunked file uploads. See https://jupyter-notebook.readthedocs.io/en/stable/extending/contents.html#chunked-saving """ import base64 import contextvars import time # Used as a "registry" for uploads. content_chunks = contextvars.ContextVar("jupyterlab_content_chunks", default={}) def sto...
from typing import Generic, TypeVar from .command_query_base import CommandQueryBase C = TypeVar('C', covariant=True) class ICommand(Generic[C], CommandQueryBase[C]): def __init__(self) -> C: pass
from requests.exceptions import HTTPError from .exceptions import MissingToken, InvalidToken, LockNotAcquired def require_session(func): """Decorator applied to functions that require a valid Session. The session ID is verified in the instance for the attribute `_session_id`. Raises: Missing...
import numpy as np from openrec.legacy.utils.evaluators import Evaluator class Recall(Evaluator): def __init__(self, recall_at, name="Recall"): self._recall_at = np.array(recall_at) super(Recall, self).__init__(etype="rank", name=name) def compute(self, rank_above, negative_num): d...
__author__ = 'nickyuan' # 1. print(2**38) # print(pow(2, 38)) # 2. try to solve the offset problem s = 'g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyrq ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.' # s1 = ...
# -*- coding: utf-8 -*- import sys from ev3dev import * # Motor speed for linear motion, in percents SPEED_LINEAR = 75 # ... for circular motion SPEED_CIRCULAR = 50 # Motor maximal speed (will be detected) max_speed = 0 MOTOR_LEFT = OUTC MOTOR_RIGHT = OUTB MOTOR_BOTH = MOTOR_LEFT | MOTOR_RIGHT IR_CHANNEL = 0 ...
# Copyright (c) Open-MMLab. All rights reserved. from vedacore.misc import registry from .base_hook import BaseHook @registry.register_module('hook') class DistSamplerSeedHook(BaseHook): """Data-loading sampler for distributed training. When distributed training, it is only useful in conjunction with :obj...
# basic imports import numpy as np import pandas as pd from argparse import ArgumentParser from tqdm import tqdm # sklearn from sklearn.model_selection import train_test_split # tensorflow import tensorflow as tf from tensorflow.data import TFRecordDataset # custom imports import config from dataset import get_data...
def forward(w,s,b,y): Yhat= w * s + b output = (Yhat-y)**2 return output, Yhat def derivative_W(x, output, Yhat, y): return ((2 * output) * (Yhat - y)) * x # w def derivative_B(b, output, Yhat, y): return ((2 * output) * (Yhat - y)) * b #bias def main(): w = 1.0 #weight x = 2.0 #samp...
from .pyarrow_test import * from .pyarrow_test_partitioned_dataset import *
from dateutil.parser import parse import datetime DEFAULT_DATE = datetime.datetime(1901, 1, 1) def parse_no_default(datestring): date = parse(datestring, default=DEFAULT_DATE) if date == DEFAULT_DATE: return None else: return date
from __future__ import absolute_import import json import re import multiprocessing import traceback from portfolio.extract import is_currency, get_quote from portfolio.holding import Holding from portfolio.interface import str_color, num_color #====================================== # Exceptions #===================...
## ____ _ ____ ## / ___|__ _ ___| |_ _ _ ___ / ___|__ _ _ __ _ _ ___ _ __ ## | | / _` |/ __| __| | | / __| | | / _` | '_ \| | | |/ _ \| '_ \ ## | |__| (_| | (__| |_| |_| \__ \ | |__| (_| | | | | |_| | (_) | | | | ## \____\__,_|\___|\__|\__,_|___/ \____\__,_|_| |_|\__, |\___/|...
from .rich import RichPrint from .magic import __dirname__, __line__, __fun__, __assert__ from .download import download_one_file, unpack_one_file __VERSION = '0.0.10'
OID_CDP_GLOBAL_DEVICE_ID = '1.3.6.1.4.1.9.9.23.1.3.4.0' OID_CDP_CACHE_DEVICE_ID = '1.3.6.1.4.1.9.9.23.1.2.1.1.6' OID_CDP_CACHE_CAPABILITIES = '1.3.6.1.4.1.9.9.23.1.2.1.1.9' OID_CDP_CACHE_ADDRESS = '1.3.6.1.4.1.9.9.23.1.2.1.1.4' OID_CDP_CACHE_DEVICE_PORT = '1.3.6.1.4.1.9.9.23.1.2.1.1.7' OID_LLDP_LOC_CHASSIS_ID = '1.0....
""" Non-skeletal Parallel Functions """ __all__ = ['procs', 'wtime', 'barrier', 'at_root'] from typing import Callable import random from mpi4py import MPI from pyske.core.support import parallel def randpid() -> int: """ If called by different processors, the result may be different on each calling proces...
import numpt as np X = np.array([1,2]) W = np.array([[1,3,5],[2,4,6]]) np.dot(X,W)
from decimal import Decimal from typing import List import pytest from exapi.models.hitbtc import (HitbtcCandleModel, HitbtcCurrencyModel, HitbtcOrderBookModel, HitbtcOrderBookOrderModel, HitbtcOrderModel, HitbtcRawCandl...
"""Code for loading trajectory data and rotating, interpolating and translating it""" import pathlib import glob from typing import List, Dict import numpy as np from scipy.spatial.transform import Rotation as Rot from scipy import interpolate rot = Rot.from_euler("x", -23.5, degrees=True) class SplRep: def __i...
#!/usr/bin/python3 import requests import json import time import sys import datetime import logging from logging.handlers import RotatingFileHandler import paho.mqtt.client as mqtt from requests.api import request import os from datetime import datetime, timezone logfile = "easeelog.log" logging.basicConfig(handlers...
# 该文件无需自定义 import requests from socket import gethostname import subprocess import sys import time import uuid import random import zmail import threading import pyautogui # pip install pyautogui==0.9.50 import DDOS url = sys.argv[1] # 全局变量初始化 for i in range(1, 10): url = sys.argv[i] if url[:4] == "http": ...
import unittest from mock import MagicMock, Mock, patch, PropertyMock, call @patch('hmac.new') class XHubSignatureMiddlewareTestSuite(unittest.TestCase): def setUp(self): with patch('django.http.HttpResponse'): with patch ('django.conf.settings'): import middleware ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Created on May 29, 2020 Desc: Media file downloader Author: Mashiro URL: https://2heng.xin License: MIT """ import urllib.request import ffmpy from .get_config import GetConfig config = GetConfig() def MediaDownloader(data): """ :param object: Data return from Tweet...