content
stringlengths
5
1.05M
from django.db import models # Create your models here. from django.db import models class League(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) def __str__(self): return self.name class Division(models.Model): league = models.Foreig...
from api.router import Router if __name__ == '__main__': rt = Router() rt.listen("127.0.0.1", port=6001, ws_port=6002) # rt.set_domain("example.com") # 如果在服务器上使用 # rt.enable_debug() # 启用 Flask 调试 rt.run()
from pydub import AudioSegment import numpy as np import matplotlib.pyplot as plt def open_audio(path): return AudioSegment.from_file(path) # Used to standardize volume of audio clip def match_target_amplitude(sound, target_dBFS): change_in_dBFS = target_dBFS - sound.dBFS return sound.apply_gain(change_...
from exam_02apr.project.card.card import Card class TrapCard(Card): def __init__(self, name): super().__init__(name, damage_points=120, health_points=5)
from time import sleep for cont in range(10,0,-1): print(cont) sleep(1) print('Acabou !!!!')
# Import the library to create websites from flask import Flask, render_template from bokeh.plotting import figure, show, output_file from bokeh.embed import components from bokeh.resources import CDN from pandas_datareader import data import datetime app = Flask(__name__) # Decorator Home Page @app.route('/') def h...
import errno class AppTestErrno: spaceconfig = dict(usemodules=['errno']) def setup_class(cls): cls.w_errno = cls.space.appexec([], "(): import errno ; return errno") cls.w_errorcode = cls.space.wrap(errno.errorcode) def test_posix(self): assert not hasattr(self.errno, '__file__')...
import os import time import shutil import requests from urllib.parse import urljoin from bs4 import BeautifulSoup from telegram_send import send from selenium import webdriver from selenium.webdriver.chrome.options import Options class BasicFuncs(object): """docstring for BasicFuncs.""" def __init__(self): ...
import numpy as np import pandas as pd class SymbolFromTransformLog(object): def __init__(self, symbol_list): self._symbol_list = symbol_list self._symbol_assignment_list = [] def log_symbols(self, rigid_transform_dict): sym_assign = np.array([sym(rigid_transform_dict) for sym in self...
import os import subprocess import numpy as np import scipy.misc try: from subprocess import DEVNULL # py3k except ImportError: DEVNULL = open(os.devnull, 'wb') def which(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(pro...
# Copyright 2012 OpenStack 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 b...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Leonardo La Rocca """ from smbus2 import SMBus class RV_3028(): # i2c address RV_3028_ADDRESS = 0b1010010 # control and status STATUS_REGISTER_ADDRESS = 0x0E CONTROL1_REGISTER_ADDRESS = 0x0F CONTROL2_REGISTER_ADDRESS = 0x10 # ...
from rest_framework.routers import DefaultRouter from .views import PostcardJobViewset, AddressViewset router = DefaultRouter() router.register(r'jobs', PostcardJobViewset, basename='jobs') router.register(r'address', AddressViewset, basename='addresses') urlpatterns = router.urls
import json def handler(event,context): print('Log event',event) return { 'statusCode': 200, 'body': json.dumps('Hello world API!') }
import abc import typing import git from fiepipelib.assetaspect.data.config import AssetAspectConfiguration from fiepipelib.assetaspect.routines.autoconf import AutoConfigurationResult from fiepipelib.enum import get_worse_enum from fiepipelib.git.routines.ignore import AddIgnore, CheckCreateIgnore from fiepipelib.gi...
""" Entry-point into the application. Run with, eg: gunicorn app.main:app -b 0.0.0.0:8000 --access-logfile - This loader pattern from: http://charlesleifer.com/blog/structuring-flask-apps-a-how-to-for-those-coming-from-django/ """ from app import app from views import *
from flask import Flask, render_template, request, redirect, flash from nl4dv import NL4DV import pandas as pd import numpy as np import json import os import imp_list.imputation as imputation import imp_list.statistics as statistics import imp_list.recommend as recommend import imp_list.tree as tree im...
from setuptools import setup setup( name='findiff', version='0.6.2', description='A Python package for finite difference derivatives in any number of dimensions.', long_description="""A Python package for finite difference derivatives in any number of dimensions. Features: * Differen...
"""Models for daily API.""" # pylint: disable=no-name-in-module from typing import List from pydantic import BaseModel, Field class DailyDataItem(BaseModel): """Data Schema.""" station: str = Field(..., title="Station Idenfifier") date: str = Field(..., title="Calendar Date") max_tmpf: float = Field...
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : url.py @Time : 2021/04/27 22:53:54 @Author : LisonLIN @Contact : linliangsuan@qq.com @Desc : 路由文件 ''' # here put the import lib from django.urls import path from api import views from api.utils.auth import Login from rest_framework.routers...
import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt fashion_mnist = keras.datasets.fashion_mnist (train_images,train_labels),(test_images,test_labels) = fashion_mnist.load_data() class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'S...
""" exotx init """ import logging from .classes import Args, LightCurve, Transit, Periodogram, Params, Fit from .functions import retrieve, detrend, normalize, combine, \ periodogram, find_pg_params, fold, fit_continuum, normalize_t from .plotting import plot_lc, plot_folds from .mode...
#coding:utf-8 schema = 'https://' decrypt_tags = ['svgmtsi','d','e'] woff_path = 'woff/woff.woff' woff_xml_path = 'xml/woff.xml' pattern_svgcss = r'//(s3plus.meituan.net.+?)"' pattern_woff = r',url\("//(.+?\.woff)"' pattern_address_woff = r'\.address.*url\("//(.+?\.woff)"' example_shop_url = 'https://www.dianping...
#!/usr/bin/python #-*-coding:utf-8-*- # 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...
# -*- coding: utf-8 -*- """ netease-dl.exceptions ~~~~~~~~~~~~~~~~~~~~~ This module contains the set of netease-dl's exceptions. """ from requests.exceptions import RequestException class SearchNotFound(RequestException): """Search api return None.""" class SongNotAvailable(RequestException): """Some song...
import os,time from threading import Thread def updater(m,plugin): print('Module %s started' % plugin) try: func = getattr(m,plugin)() except Exception as e: print(str(e),plugin) print('Module %s completed' % plugin ) def main(): threadsList = [] path = os.path.dirname(os.path....
#!/bin/python3 import math import os import random import re import sys # Complete the plusMinus function below. def plusMinus(arr): plus=0 minus=0 zero=0 for i in range(len(arr)): if arr[i]>0 : plus+=1 elif arr[i]<0 : minus+=1 else: zero+=1 ...
import cv2 import matplotlib.pyplot as plt def save_and_show(image, path): # Save image to path cv2.imwrite(path, image) # Show Encrypted image plt.figure() plt.imshow(image[:, :, ::-1]) plt.title("Image Encrypted with your data") plt.axis("off") plt.show() return
import information_theory.config as config import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec def plot_binnings(data): """ Replicates figure 2 from A Tutorial for Information Theory in Neuroscience. Args: data (np.array): Sampled data points. """ N ...
""" 10 Days of Statistics Day 0 Weighted Mean """ from __future__ import division n = raw_input() vector = map(int,raw_input().split()) weight = map(int,raw_input().split()) prod = lambda x: x[0] * x[1] def weighted_mean(vector,weight): vector_weight = zip(vector,weight) return round(sum(map(prod,vecto...
#!/usr/bin/env pvpython # -*- Python -*- (syntax highlighting) # ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University of Chicago # # This code was developed as part of the Computational Infr...
from src.api import Api from src.gui.appJar.appjar import gui class TestUI: def __init__(self, app): self.__app = app self.__isRecording = False self.__RECORD_BUTTON_NAME = "TEST_START_STOP_RECORD_BUTTON" self.__USE_ACTION_CHECKBOX_NAME = "TEST_USE_ACTION_CHECKBOX" def append_i...
import unittest from komadu_client.parsers.fobs_parser import parse_fobs_json from datetime import datetime class TestFobsParser(unittest.TestCase): def test_fobs_parser_gray_scott(self): file_name = "./resources/gray-scott/codar.cheetah.fob.json" parsed_result, _ = parse_fobs_json(file_name) ...
optional_bibtex_fields = [ 'addendum', 'options' ]
# Read all temp sensors and write their datas into the table. # Note: # Added a multi-threaded function, but the reading of the 1WD seems to # still just be taking ~900ms between samples and so you might hit a # 1 second delay. So it helps, but not much to use a thread. # import sqlite3 as sql import datetime, ti...
# # net_generator.py # # Generate a NN based on the individual spec from DEAP # # Written by Mark Strefford # (c) 2021 Delirium Digital Ltd # # TODO: Add ReLU, etc? # TODO: Is padding and concat better for max 2 layers? Assuming currently we're creating lots of large tensors??! import os import shutil import numpy as...
from django.db import models from django.conf import settings class PersonManager(models.Manager): def all_with_prefetch_movies(self): qs = self.get_queryset() return qs.prefetch_related( 'directed', 'writing_credits', 'role_set__movie' ) class MovieMa...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django_maps import settings import os class ProfilePhotoUploadForm(forms.Form): userId = forms.IntegerField() file = forms.FileField() class RegistrationForm(UserCreationForm): ...
# # PySNMP MIB module HPN-ICF-L2ISOLATE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-L2ISOLATE-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:39:31 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
import pytest import add_map_to_timelapse crds = [45, 20, 102872980] exif_data = { 1: u'N', 2: ((44, 1), (11, 1), (102872399, 10000000)), 3: u'W', 4: ((94, 1), (0, 1), (178621199, 10000000)), 5: '\x00', 6: (280381, 1000), 7: ((20, 1), (9, 1), (18, 1)), 29: u'2018:01:01' } x_size = 20 y...
from sqlalchemy import Column, Integer, String, UniqueConstraint from sqlalchemy.orm import relationship from rdr_service.model.base import Base from rdr_service.model.site_enums import ObsoleteStatus from rdr_service.model.utils import Enum, UTCDateTime from rdr_service.participant_enums import OrganizationType cla...
#!/usr/bin/env python3 import requests import sys, os, time import configparser from lxml import html from dateutil import parser import tweepy def fail(message): print("ERROR: {}".format(message), file=sys.stderr) sys.exit(1) # Read config file in mydir = os.path.dirname(os.path.realpath(__file__)) configname = ...
#!/usr/local/bin/python # based on code by henryk ploetz # https://hackaday.io/project/5301-reverse-engineering-a-low-cost-usb-co-monitor/log/17909-all-your-base-are-belong-to-us # and the wooga office weather project # https://blog.wooga.com/woogas-office-weather-wow-67e24a5338 import os, sys, fcntl, time, socket fr...
str_tex_proc = """ // <https://www.shadertoy.com/view/4dS3Wd> // By Morgan McGuire @morgan3d, http://graphicscodex.com float hash_f(const float n) { return fract(sin(n) * 1e4); } float hash_f(const vec2 p) { return fract(1e4 * sin(17.0 * p.x + p.y * 0.1) * (0.1 + abs(sin(p.y * 13.0 + p.x)))); } float hash_f(const vec3 ...
__author__ = 'viktor' import pandas as pd import numpy as np from SAMKNN import SAMKNN from sklearn.metrics import accuracy_score from ClassifierVisualizer import ClassifierVisualizer from ClassifierListener import DummyClassifierListener import logging import sys from data_loader import DataLoader from datetime import...
#!/usr/bin/env python """ Build a mask from a spectral template. """ from __future__ import division from __future__ import print_function import argparse import os import sys import textwrap # import time import ipdb import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd impo...
# -*- coding: utf-8 -*- # Usage: # python sort_csv.py ../data/people_box_office_top_50_movies_1995-2014_imdb.csv movie_id import csv import sys if len(sys.argv) < 2: print "Usage: %s <input file> <sort by>" % sys.argv[0] sys.exit(1) INPUT_FILE = sys.argv[1] SORT_BY = sys.argv[2] items = [] headers = [] ...
#!/usr/local/bin/python3 """ Copyright (c) 2019-2020 Ad Schellevis <ad@opnsense.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain th...
import twutilities as tw import text_analysis as ta import json import pandas as pd import re sname = raw_input("Right on! Whose tweets do you want to get? (no @ symbol) > ") timeline = tw.getTimeline(sname, 100) userdata = tw.getUserData(timeline) print("\nInfo about this user:") print(userdata) # Get the full tex...
from flask import Blueprint from flask_restful import Api from resources import MasterDataResource, BulkMasterDataResource, CacheBustResource # end-point for independent service MDMS_BLUEPRINT = Blueprint("master-data-mgmt", __name__) #fetch master data end-point Api(MDMS_BLUEPRINT).add_resource(MasterDataResource, "...
import os import sys import subprocess import typer # 运行环境检查 def check_env(): # 模块检查 typer.secho("[module]", fg=typer.colors.MAGENTA, bold=True) fp = open("./requirements.txt") modules = {} max_length = 0 for module in fp.readlines(): module = module.strip() if "==" not in modu...
#!/usr/bin/env python # coding: utf-8 shead_anchors = ((18,), (36,), (72,), (128,), (208,), (320,), (512,), (768,)) chuman_anchors = ((10,), (48,), (128,), (192,), (256,), (320,), (512,)) comb_anchors = ((12,), (32,), (64,), (112,), (196, ), (256,), (384,), (512,)) hh_anchors = ((12,), (18,), (24,), (32,), ...
print "Como estas"
import numpy as np CONFIG_SUPERNET = { 'gpu_settings' : { 'gpu_ids' : [0] }, 'lookup_table' : { 'create_from_scratch' : False, 'path_to_lookup_table' : './supernet_functions/lookup_table.txt', 'number_of_runs' : 50 # each operation run number_of_runs times and then we will t...
import uuid from typing import List, Dict import lark from recognition.rules import astree grammar_cache = {} def build_repeat(node): if node.repeat_low == 1 and node.repeat_high == 1: return '' low = node.repeat_low if low == 0 and node.repeat_high is None: return '*' if low == 1 and ...
from pydantic import BaseSettings, AnyUrl class Settings(BaseSettings): log_level: str = 'INFO' redact_online_url: AnyUrl = "https://api.brighter.ai/" redact_url_default: AnyUrl = "http://127.0.0.1:8787/"
import pytest import numpy as np import pandas as pd from ..utils import _check_random_state from ..utils import _check_min_supp from ..utils import _check_growth_rate from ..utils import filter_maximal from ..utils import filter_minimal from ..utils import intersect2d def test_check_random_state(): random_state ...
def setup(): size(500,500) smooth() background(50) strokeWeight(5) stroke(250) noLoop() cx, cy, cRadius = 250, 250, 200 def draw(): global cx, cy, cRadius i = 0 for j in range(0, 12): i = i + 2*PI/12 x1 = cos(i)*cRadius + cx y1 = sin(i)*cRadius...
# Generated by Django 3.0.4 on 2020-04-04 19:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0013_blog'), ] operations = [ migrations.RemoveField( model_name='blog', name='id', ), migr...
#!/usr/bin/python3 import time, sys class logger(): """ A base class for named objects where state changes can be logged, with easy control over what is and isn't logged log files are held as a universal list """ logfiles={} logheader='{M:02d}:{S:05.2f} {name:10s}: ' lifelogso = ('life', ...
""" intro_3_03_hello_world_1.py Example code from Section 3.3 of "Introduction to SFC Models Using Python." This example does not create a useful model, but it and following examples demonstrate how models are built up by examining the log file. Copyright 2017 Brian Romanchuk Licensed under the Apache License, Vers...
# Generated by Django 3.0.4 on 2020-03-11 16:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('project_first_app', '0001_initial'), ] operations = [ migrations.CreateModel( name='License', ...
# Author: Peter Cerno <petercerno@gmail.com> # Plot of: # (a) Raw height/weight data. # (b) Standardized. # (c) PCA whitened. # (d) ZCA whitened. # Based on: # https://github.com/probml/pmtk3/blob/master/demos/heightWeightWhiten.m # Some source code taken from: # https://github.com/probml/pyprobml/blob/mast...
import pytest from urouter.api import Route, Router from urouter.constants import Method as mt @pytest.mark.parametrize( "method, pattern, handler", [ (mt.CONNECT, "/connect", lambda x: mt.CONNECT), (mt.DELETE, "/delete", lambda x: mt.DELETE), (mt.GET, "/get", lambda x: mt.GET), ...
from mowl.walking.deepwalk.model import DeepWalk from mowl.walking.node2vec.model import Node2Vec from mowl.walking.walkRdfAndOwl.model import WalkRDFAndOWL def walking_factory(method_name, edges, num_walks, walk_length, outfile, workers = 1, alpha = 0, p = 1, q=1): methods = [ "deepwalk", "node2v...
import importlib import pathlib import logging from utils import HelperException def load_commands(): path = pathlib.Path(__file__).parent for file_path in path.glob("*"): if file_path.name == "__init__.py": continue mod_name = file_path.stem if not file_path.is_file() or...
# -------------------------------------------------------------------------- # Default Site Configuration File # -------------------------------------------------------------------------- # This file contains Ark's default site configuration settings. Settings # in this file will be overridden by settings in a site's ...
from unittest.mock import patch import pytest from mypykaizen import mypykaizen def test_sanitize_output_lines_happy_path(): output_lines = [ '/Users/foobar/baz.pyi:00: note: "this" of "that" defined here', "my_lib/deadbeef.py:42: error: Deadbeef wasn't actually dead all along", "I'm a t...
#!/usr/bin/env python import os import re from flask import Flask, jsonify, request, Response from faker import Factory from twilio.jwt.client import ClientCapabilityToken from twilio.twiml.voice_response import VoiceResponse, Dial from twilio.rest import Client from twilio.twiml.voice_response import Record, VoiceRes...
# # Copyright (c) 2017 Intel Corporation # # 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 t...
import requests import os from unittest import TestCase from django.conf import settings class CloudflareCacheTestCase(TestCase): """ Ensure that our local cache of Cloudflare IP addresses is up to date. """ message = """ Cloudflare has updated its list of IP addresses since we last grabbed a co...
# Copyright 2018 Google Inc. 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 tempfile import shapefile import bbd.gis as gis def test_utils(): path = tempfile.mktemp(suffix="") # no extension with shapefile.Writer(path) as w: w.shapeType = shapefile.POLYGON w.field("test_name", "C") # text field w.poly([[[0, 0], [0, 100], [100, 100], [100, 0]]]) ...
import time import cv2 import numpy as np import pandas as pd #from customer_simulation import Customer transition_matrix = pd.read_csv("./data/transition_matrix.csv") transition_matrix.set_index("location", inplace=True) TILE_SIZE = 32 OFS = 50 MARKET = """ ################## ##..............## ##..db..s#..x#..## #...
PIECES = { "K": "<:WK:773990181170053140> ", "Q": "<:WQ:773990181001887764> ", "B": "<:WB:773990181052743680> ", "R": "<:WR:773990180930715679> ", "N": "<:WN:773990181148819477> ", "P": "<:WP:773990180687708180> ", "WS": ":white_large_square: ", "BS": ":brown_square: ", "k": "<:BK:77...
# Создаём переменные variable1 = 'variable1' variable2 = 2 variable3 = True variable4 = 4.44 # Вывод переменных print(type(variable4), type(variable3), type(variable2), type(variable1)) print(variable4, variable3, variable2, variable1) # Ввод данных inputInt = int(input('Enter the number: ')) inputDecimal = float(...
""" Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note: You may assume the string contains only lowercase letters. Follow up: What if the inputs contain unicode cha...
"""Setup file for sqltools.""" from setuptools import find_packages, setup try: LONG_DESC = open("README.md").read() except FileNotFoundError: LONG_DESC = "" setup( name="sqltools", version="0.0.1", description="Python library for convenient SQL functionality", url="https://github.com/pscosta5...
import __nemesys__ import posix def check_counters(): code_buffer_size = __nemesys__.code_buffer_size() code_buffer_used_size = __nemesys__.code_buffer_used_size() print('''nemesys counters: code_buffer_size == 0x%X code_buffer_used_size == 0x%X''' % ( code_buffer_size, code_buffer_used_size)) ...
#!/usr/bin/env python """igcollect - Values from Log File This script can retrieve last line values by column number: python logfile_values.py --metric "metric1:1" "metric2:2" ... And aggregate data by time period with different functions: median, mean, sum, min, max, count, frequency, speed (??) count_100 - count...
import boto3 from localstack.services.motoserver import MotoServer, get_moto_server from localstack.utils.common import get_free_tcp_port def test_get_moto_server_returns_singleton(): assert get_moto_server() is get_moto_server() def test_moto_server(): # despite being a new instance, it actually shares st...
from setuptools import find_packages, setup with open("README.md", "r") as fh: long_description = fh.read() project_slug = "tealprint" module_name = project_slug.replace("-", "_") setup( name=project_slug, use_scm_version=True, url=f"https://github.com/Senth/{project_slug}", license="MIT", au...
# List to Dictionary Function for Fantasy Game Inventory # Imagine that a vanquished dragon’s loot is represented as a list of strings like this: # dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] # # Write a function named addToInventory(inventory, addedItems), where the # inventory parameter ...
from ics2000.commands.Command import Command class CommandBuilder: def __init__(self, mac) -> None: self.mac = mac def new_command(self, entity, function, value): cmd = Command() \ .setmac(self.mac) \ .settype(128) \ .setmagic() \ .setentityid(en...
""" Dynamic host file management. """ from __future__ import absolute_import, print_function from ..docker import Container, events from dnslib import RR, QTYPE, TXT, RCODE, A, AAAA from dnslib.server import DNSServer, BaseResolver, DNSLogger from urlparse import urlparse from ..config import config import threading ...
from . import base, attributes, transactions, entities, documents class Account(base.SchemaBase): """Account base type - accounts can be associated with entities""" links = [ transactions.AssociatedWith ] transactions.AssociatedWith.links.append(Account) class PhoneNumber(Account): """Raw p...
class DuplicateEntityException(Exception): def __init__(self, entity_type: str, entity_id: str): super().__init__(f"The {entity_type} {entity_id} is already persisted")
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' name: dorado默认口令漏洞 referer: unknown author: Lucifer description: dorado是一款web中间件,具有AJAX特征的web应用表现层的快速开发框架,存在默认口令dev/dorado,admin/dorado。 ''' import sys import json import requests class dorado_default_passwd_BaseVerify: def __init__(self, url): self.url = ...
# -*- coding: utf-8 -*- import betamax def get_betamax(session): return betamax.Betamax( session, cassette_library_dir='tests/cassettes')
import os import re import requests import requests_cache from person import Person from pmid import Pmid from util import safe_commit from app import db from util import normalize # expire_after is in seconds requests_cache.install_cache('my_requests_cache', expire_after=60*60*24*30, ignored_parameters=["ts"]) # ju...
import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms import os from PIL import Image import numpy as np from tqdm import tqdm class INaturalist(Dataset): num_classes = 8142 def __init__(self, root, txt, transform=None): self.img_path = [] self.target...
#! /usr/bin/env python #coding:utf-8 import sys import os import re import urllib2 import urllib import requests import cookielib import getpass import json from bs4 import BeautifulSoup import socket socket.setdefaulttimeout(100.0) ## 这段代码是用于解决中文报错的问题 reload(sys) sys.setdefaultencoding("utf8") ##########...
import types import functools import base64 import pickle import time import hashlib import json import httpx import cloudpickle import pysparkrpc PROXY_URL = 'http://localhost:8765' CACHING = True def _copy_func(f): g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, a...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' [Module Description] ''' # Standard Imports # External Imports # Internal Imports # Function Declarations
# code adapt from https://www.internalfb.com/intern/diffusion/FBS/browse/master/fbcode/mobile-vision/experimental/deit/models.py # Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import json import math from functools import partial import torch import torch.nn as nn import torch.nn.functional as F f...
# Copyright 2020 The Oppia 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 applicable ...
""" The weight allocation module. """ import pandas as pd import numpy as np import math from scipy.optimize import minimize, Bounds from abc import ABC, abstractmethod class WeightAllocation(ABC): """ An abstract class for allocating securities within a portfolio. """ @abstractmethod def get...
from kinemathic.animation import animate import statsmodels.api as sm data = sm.datasets.co2.load_pandas() co2 = data.data animate(co2, '../output/co2.mp4', axis=1, step=25, autoscale=False) animate(co2, '../output/co2_autoscale.mp4', axis=1, step=25, autoscale=True) animate(co2, '../output/co2_bar_auto.mp4', axis=1...
# Copyright 2018 Google Inc. 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...
#예제 3-6 number1 = input("숫자 10을 입력하세요") print (number1) print (type(number1))