content
stringlengths
5
1.05M
from django.test import TransactionTestCase class APITests(TransactionTestCase): def test_tutorials_page_status_code(self): response = self.client.get('/tutorials/') self.assertEquals(response.status_code, 200) def test_tags_page_status_code(self): response = self.client.get('/tags/'...
import logging import warnings import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import PowerNorm from matplotlib.figure import Figure from matplotlib.patheffects import withStroke from pyqtgraph import Qt as qt logger = logging.getLogger('ds.'+__name__) # The logging level for signals SIGNAL...
# Copyright(c) 2017-2021 CloudNetEngine. 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 applica...
from pylab import * x = linspace(-1., 1., 1001) y = x.copy() [x, y] = meshgrid(x, y) y = y[::-1, :] sample = atleast_2d(loadtxt("sample.txt")) figure(figsize=(8, 8)) ion() hold(False) for i in xrange(0, sample.shape[0]): plot([]) # Circle radii and positions width = sample[i, 5:1005] xc = sample[i, 100...
import logging from io import BytesIO import uvicorn from fastapi import Body, Depends, FastAPI, File, Request, UploadFile from sqlalchemy.orm import Session from .database import SessionLocal, UserIn, add_user, delete_user, get_user, get_users from .yolo_minimal.detect import detect_init, detect, parse_name app = ...
from django.urls import path from .import views urlpatterns=[ path('register/',views.register,name='register'), path('manufacturer_register/',views.manufacturer_register.as_view(),name='manufacturer_register'), path('distributor_register/',views.distributor_register.as_view(),name='distributor_register'), ...
import pytest from lupa._lupa import LuaRuntime from dredis.keyspace import Keyspace from dredis.exceptions import RedisScriptError from dredis.lua import LuaRunner, RedisLua def test_lua_return_redis_types_run(): k = Keyspace() runner = LuaRunner(k) lua_script = """return {'test', true, false, 10, 20.3...
""" Marquee plugin: replicate the html <marquee/> tag with message corrections. Usage of this plugin is not recommended. Commands -------- .. glossary:: /marquee <text> Send the following text with <marquee/> behavior Configuration ------------- .. glossary:: :sorted: refresh **Defaul...
"""Initializes the header dash html """ from typing import List from dash.development.base_component import ComponentMeta from dash_html_components import Div, A from chime_dash.app.components.base import Component class Header(Component): """ """ localization_file = "header.yml" def get_html(self...
from __future__ import unicode_literals from django.template import Library register = Library() @register.simple_tag def get_api_image_url(obj, **kwargs): return obj.get_api_image_url(**kwargs)
import argparse import os from google.cloud import bigquery from google.cloud.bigquery.job import ExtractJobConfig DATASET = "taxifare" TRAIN_TABLE = "feateng_training_data" VALID_TABLE = "feateng_valid_data" TRAIN_SQL = """ CREATE OR REPLACE TABLE taxifare.feateng_training_data AS SELECT (tolls_...
# This file is part of JST. # # JST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # JST is distributed in the hope that it will b...
from .config import Config from .oss import Oss
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches plt.rcParams["figure.figsize"] = (10,6) fox_data = [] cannon_data = [] simple_matrix_data = [] order = [] i = 4 with open('fox_data.txt','r') as file: for line in file: j = 0 sum = 0 for word in line.spl...
# (c) Copyright 2014,2015,2016 Hewlett-Packard Development Company, L.P. # # 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 ...
#%% import tensorflow as tf from tensorflow import keras from tensorflow.keras import Input, Model, layers, Sequential from tensorflow.keras.layers import Layer, Conv2D, MaxPool2D,\ Flatten, BatchNormalization, Dense, GlobalAveragePooling2D, Dropout #Allow the GPU memory growth for deep learning ph...
from __future__ import absolute_import, division, print_function from .fcn8 import * from .fcn16 import * from .fcn32 import * from .unet import * from .pspnet import * from .fast_scnn import * model_from_name = {} model_from_name["fcn8_vgg11"] = fcn8_vgg11 model_from_name["fcn8_vgg13"] = fcn8_vgg13 model_from_name[...
""" 工具类 其实里面都只是数值计算函数 """ import numpy as np def cut_img_3D(img): """ 将3D的数据进行剪裁,去除3D黑边 img:numpy array return a cut img with same axis number but not a fixed one """ # print(img.shape,img.dtype) buf=[] for i in range(img.shape[0]): temp = img[i,:,:] if(temp.sum()!=0): ...
import asyncio from .ModbusProtocolRtu import ModbusProtocolRtu import logging _logger = logging.getLogger(__name__) class Transport: def __init__(self, **kwargs): self.logger = kwargs.get('logger', _logger) pass async def connect(self, serial): pass async def send(self, data): ...
#!/usr/bin/env python import sys import math points = [] #files = ['Control182localeq','Control189localeq','Control239localeq'] class Plot3d(): def getNodesAndEdges(infile): inpath = 'csv/' outpath = 'graphml/' filename = infile.name[:-4} if infile.name.endswith('.csv') else infile.name infilename = inpath...
from flask_sqlalchemy import SQLAlchemy from datetime import datetime import random ##### Init class ##### db = SQLAlchemy() ##### Models ##### class User(db.Model): id = db.Column(db.Integer, primary_key=True, nullable=False) username = db.Column(db.String(100), unique=True, nullable=False) password...
#Bit server start and requesr handiling file # there will be a peice of updated code that get parameteters from the path from urlparse import urlparse #Import the map file from map import mapRequest #import the scripts needed to run the http server request import SocketServer from BaseHTTPServer import BaseH...
from ex112.utilidadescev import moeda from ex112.utilidadescev import dado p= dado.leiaDinheiro('Digite o Preço R$: ') moeda.resumo(p, 35, 22)
from django.conf.urls import patterns, include, url from django.contrib.auth.views import login, logout from main_menu import admin_custom as admin from django.views.generic.base import RedirectView #from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'my...
# Author: Luka Maletin from data_structures.stack import Stack OPERATORS = '&|!' def calculate(d1, d2, operator): if operator == '&': return intersection(d1, d2) elif operator == '|': return union(d1, d2) elif operator == '!': return difference(d1, d2) def evaluate(expression...
import sys from requests import get from core.colors import bad, info, red, green, end def honeypot(inp): honey = 'https://api.shodan.io/labs/honeyscore/%s?key=C23OXE0bVMrul2YeqcL7zxb6jZ4pj2by' % inp try: result = get(honey).text except: result = None sys.stdout.write('%s No inform...
from django.contrib.auth import get_user_model from django_analyses.models.run import Run from django_analyses.serializers.analysis_version import ( AnalysisVersionSerializer, ) from rest_auth.serializers import UserDetailsSerializer from rest_framework import serializers User = get_user_model() class MiniUserSe...
# Hand of Straights # Alice has a hand of cards, given as an array of integers. # Now she wants to rearrange the cards into groups so that each group is size W, # and consists of W consecutive cards. Return true if and only if she can. # hand = [1,2,3,6,2,3,4,7,8], W = 3 => True # hand = [5,1], W = 2 => False # Note: c...
from anonapi.client import WebAPIClient def anonymize_files_sop_class_filter(): """Create an IDIS job that pulls files from the hospital information system""" # Create a client that will talk to the web API client = WebAPIClient( hostname="https://umcradanonp11.umcn.nl/sandbox", username=...
# Copyright 2020 The DDSP 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 wri...
#!/usr/bin/env python """ Converts between chromosome names. """ import sys import argparse from argparse import RawDescriptionHelpFormatter as Raw import pkg_resources import gzip import pandas as pd import pysam import pybedtools from Bio import SeqIO def arguments(): """ Function to pull command line argument...
# Solving problems in statistics import math from my_utils import probability, union_probability from my_utils.testing import test_equal, test_close import my_utils.counting as C print("\nSOME PROBABILITY PROBLEMS\n") # Question 1 print("Q: Find the probability of getting a head when you toss a fair coin?") p_head =...
import pyctopod def handle_message(from_id, topic, msg): """ Publishes "blah" to :test everytime a message is received. """ msg = "blah" pyctopod.publish("test", msg.encode('utf8'), from_id="pyctotest_keepalive_receiver") def main(): pyctopod.subscribe(topics=["test_topic"], handlers=[handle_m...
""" Copyright 2021, BYU-Idaho. Author(s): Matt Manley, Jacob Oliphant Version: 1.0 Date: 27-01-2021 """ from abc import ABC class Trait(ABC): """A distinguishing quality. The responsibility of Trait is to define the common methods for an actor's specific qualities or features. Even though this version o...
#!/usr/bin/env python3 """ Módulo Main: Programa principal (controlador). Playlist - Ejecute "ayuda" para más información """ from lista import Lista from estante import Estante from repl import REPL from repl import strip class Main: """Clase principal.""" def __init__(self): """Constructor: Inicia...
import wikipedia from .baseprovider import BaseProvider class WikipediaProvider(BaseProvider): @staticmethod def get(query, config, params={}, lang='en'): wikipedia.set_lang(lang) search = wikipedia.search(query) if not search: return { 'content': 'nan' ...
import traceback from contextlib import contextmanager import pytz import signal from datetime import datetime from typing import Union, Any @contextmanager def signal_context(signals=(signal.SIGINT, signal.SIGTERM), handler: Union[int, Any] = signal.SIG_IGN): prev_hdlrs = [signal.signal(s, handler) for s in sig...
# -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Tigera, 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 # # Unle...
import matplotlib.pyplot as plt import pylab data = pylab.loadtxt('../out/plotdata.txt', delimiter=',', usecols=(0, 1, 2, 3, 4, 5, 6)) pylab.plot(data[:, 0], data[:, 1], linestyle='solid', linewidth=0.5, marker='.', markersize=2, label='L0', color='blue') pylab.plot(data[:, 0], data[:, 2], linestyle='dashed', linewid...
import torch class MovingAverage: def __init__(self, moving_average_size=256): self.count = 0 self.i = 0 self.moving_average_size = moving_average_size self.values = self.moving_average_size * [0] def reset(self): self.count = 0 self.i = 0 def moving_averag...
# -*- coding: utf-8 -*- import sys import os import shutil import warnings import re from setuptools import setup, Extension from setuptools import find_packages ######### # settings ######### project_var_name = "csharpyml" project_owner = "sdpython" sversion = "0.1" versionPython = "%s.%s" % (sys.version_info.major,...
#!/usr/bin/python DOCUMENTATION = ''' --- module: targetcli_backstore short_description: TargetCLI backstore module description: - module for handling backstore objects in targetcli ('/backstores'). version_added: "2.0" options: backstore_type: description: - Type of storage in TargetCLI (block, filei...
import logging from abc import ABC, abstractmethod from flask import Blueprint LOG = logging.getLogger(__name__) class AbstractController(ABC): def __init__(self): self.api = Blueprint(self.__class__.__name__, __name__) self._routes() @abstractmethod def _routes(self): pass
"""The 21 BC functionality.""" import requests.sessions from two1.lib.bitrequests import BitTransferRequests from two1.commands.config import Config from two1.lib.wallet import Wallet wallet = Wallet() username = Config().username bt_requests = BitTransferRequests(wallet, username) class BitTransferSession(requests...
#!/usr/bin/python # -*- encoding: utf-8 -*- import torchvision import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torchvision.transforms import Resize,ToTensor,Compose,CenterCrop import cv2 import numpy as np class DeepLabLargeFOV(nn.Module): def __init__(s...
# The pipeline API requires imports. from zipline.api import attach_pipeline, pipeline_output, update_universe from zipline.pipeline import Pipeline from zipline.pipeline.data import USEquityPricing from zipline.pipeline.factors import SimpleMovingAverage def initialize(context): # Create, register and name a pip...
#!/usr/bin/env python3 import collections import enum # TODO we may need to change this to Enum since only a few valid values are allowed. class CrimeLevel(object): """ Crime Level. Describes crime level. e.g. Felony Class A. Attributes: type_: A string describing the type of crime. clas...
''' for else ''' variavel = ['Daniel', "Wolter", "Martins"] for valor in variavel: if valor.startswith('D'):# startswith verifica se existe uma variavel que comeca com carcter d print('começa com D', valor) else: print('nao começa com D', valor)
from . import safe_str as _safe_str from .iterutils import listify as _listify from .path import InstallRoot as _InstallRoot, install_path as _install_path def file_install_path(file, cross=None): return _install_path(file.path, file.install_root, directory=isinstance(file, Directory), cr...
#!/usr/bin/env python3 import subprocess import sys from pathlib import Path _WELL_KNOWN_FILE = Path("tests", "pyright_test.py") _PYRIGHT_COMMAND = ["npx", "-p", "pyright@1.1.114", "pyright"] def main() -> None: assert_npm_is_installed() ret = subprocess.run(_PYRIGHT_COMMAND).returncode sys.exit(ret) ...
# Copyright 2021 Peng Cheng Laboratory (http://www.szpclab.com/) and FedLab Authors (smilelab.group) # 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/LICEN...
import torch import torch.nn as nn from torch.nn import functional as F import numbers import math from .blocks import ConvBlock, DeconvBlock, MeanShift class GaussianSmoothing(nn.Module): def __init__(self, channels, kernel_size, sigma, dim=2): super(GaussianSmoothing, self).__init__() i...
""" Takes a JSON file and visualizes the annotation boxes on images. Outputs visualized at OUT_DIR/<json_file_basename>/../..*.jpg srun --mem 10000 python tools/face/viz_json.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ impor...
from django import forms from django.contrib.auth.models import User from rest.models import ApiToken class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password') class TokenForm(forms.ModelForm): class Meta: model = ApiToken fields = ('token_cl...
from dataclasses import dataclass, field from typing import Dict, List import json settings_path = "newsletters/config.json" @dataclass class Settings(): mailgunApiKey: str def load(): j = '{ "mailgunApiKey": "123!" }' j_dict = json.loads(j) return Settings(**j_dict) def save(config): print("Sav...
""" A package for generating various graphs in networkx. """ from networkx.generators.atlas import * from networkx.generators.bipartite import * from networkx.generators.classic import * from networkx.generators.degree_seq import * from networkx.generators.directed import * from networkx.generators.ego import * from ...
from django.urls import path from . import views urlpatterns = [ path('register', views.register, name='register') ]
from .base_schema import BaseResponseSchema from marshmallow import Schema, fields class ImageSchema(Schema): """ The image records from database will be deserialized to this this type and then will be sent to the client as array of images using ImageResponseSchema """ image_url = fields.String() ...
from machines import Edison2015,Edison from datetime import datetime from generate import TimeController from stats.trace import ResultTrace from stats import Histogram, NumericStats class ExperimentDefinition(object): """ This class contains the definition and state of a single scheduling experiment. The ...
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
"""This module provides an interface to the program DSSP. For more information on DSSP see [4]_. References ---------- .. [4] Kabsch W, Sander C (1983) "Dictionary of protein secondary structure: pattern recognition of hydrogen-bonded and geometrical features", Biopolymers, 22, 2577-637. """ import subprocess ...
import string from unittest import TestCase from xsdata.utils.text import alnum from xsdata.utils.text import camel_case from xsdata.utils.text import capitalize from xsdata.utils.text import classify from xsdata.utils.text import kebab_case from xsdata.utils.text import mixed_case from xsdata.utils.text import mixed_...
#!/usr/bin/env python3 import os from jobmonitor.api import ( kubernetes_schedule_job, kubernetes_schedule_job_queue, register_job, upload_code_package, ) from jobmonitor.connections import mongo excluded_files = [ "core", "output.tmp", ".vscode", "node_modules", "scripts", "....
from netmiko import ConnectHandler from netmiko.ssh_exception import * import json from nuaal.utils import get_logger, check_path, write_output from nuaal.utils import Filter from nuaal.definitions import DATA_PATH, OUTPUT_PATH import timeit import os class CliBaseConnection(object): """ This class represents ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Description A simple script for testing either in-built methods or newly added methods """ import torch import numpy as np from ptranking.ltr_global import ltr_seed from ptranking.ltr_adhoc.eval.ltr import LTREvaluator np.random.seed(seed=ltr_seed) torch.manual_seed...
import vcs, numpy, os, sys, cdms2, vcs.testing.regression as regression x=regression.init() f=cdms2.open(os.path.join(vcs.sample_data,"clt.nc")) data=f("clt",slice(0,1,)) gm = x.createisoline() gm.levels = range(0,110,10) gm.linecolors = ["green","red","blue","bisque","yellow","grey", [100,0,0,50], [0,100,0],"...
import torch import torch.nn as nn import math import numpy as np __all__ = ['regnetx_002', 'regnetx_004', 'regnetx_006', 'regnetx_008', 'regnetx_016', 'regnetx_032', 'regnetx_040', 'regnetx_064', 'regnetx_080', 'regnetx_120', 'regnetx_160', 'regnetx_320'] class ResStemIN(nn.Module): """ResNet stem f...
class IdpConstants: # endpoints PICKUP_ENDPOINT = "/ext/ref/pickup" DROPOFF_ENDPOINT = "/ext/ref/dropoff" AGENTLESS_BASE = "AgentlessIdPSample/app" START_SP_SSO = "/sp/startSSO.ping" # attribute keys SUBJECT = "subject" AUTH_INST = "authnInst" # POST keys USERNAME = "username" ...
#################################################################### ######### Copyright 2016-2017 BigSQL ########### #################################################################### import os import platform from twisted.internet.defer import inlineCallbacks, returnValue from autobahn.twisted...
""" Run all doctest examples inside the `polars` module using Python's built-in doctest module. How to check examples: run this script, if exits with code 0, all is good. Otherwise, the errors will be reported. How to modify behaviour for doctests: 1. if you would like code to be run and output checked: add the outpu...
#!/usr/bin/env python2 # coding: utf-8 import logging import threading import time from collections import OrderedDict import psutil from geventwebsocket import Resource from geventwebsocket import WebSocketApplication from geventwebsocket import WebSocketError from geventwebsocket import WebSocketServer from pykit ...
a = int(input('Digite o ano de nascimento: ')) i = 2020 - a if i <= 9: print('A categoria é mirim') elif 14 >= i > 9: print('A categoria é infantil') elif 19 >= i > 14: print('A categoria é junior') elif 20 >= i > 19: print('A categoria é senior') else: print('A categoria é master')
from threading import Thread import socket import json from jnpr.junos import Device from jnpr.junos.exception import ConnectError from junospyez_ossh_server.log import logger __all__ = ['OutboundSSHServer'] def gather_basic_facts(device): """ Using the provide Junos Device object, retrieve basic facts abou...
from app import app from config import RUN_HOST, RUN_PORT app.run(host=RUN_HOST, port=RUN_PORT)
import multiprocessing import queue import threading import json from datetime import datetime import enum import logging from sqlalchemy import MetaData, Table from ..db.datamodel import db, app, project, portscanner, target, vulnLookupTable from ..utils import Ports, PortStatus class WorkerCommand(enum.Enum): STO...
# Module with same api as built-in platform but different implementation of linux_distribution that uses distro's one. from __future__ import absolute_import from platform import * def linux_distribution(): import distro id_name, version, codename = distro.linux_distribution(full_distribution_name=False) ...
""" Implementation of a function the set the WIFI configuration. This function is primarily developed for a Raspberry PI """ from cloudmesh.burn.wifi.raspberryos import Wifi as WifiRaspberryOs from cloudmesh.burn.wifi.ubuntu import Wifi as WifiUbuntu # noinspection PyPep8Naming def Wifi(card_os="raspberry"): if ...
from snuba.query.conditions import ( BooleanFunctions, ConditionFunctions, binary_condition, get_first_level_and_conditions, get_first_level_or_conditions, is_binary_condition, is_condition, is_in_condition, is_in_condition_pattern, is_not_in_condition, is_not_in_condition_pa...
from ctypes import * msvcrt = cdll.msvcrt message = b"Hello, world!" msvcrt.printf(b"Testing: %s\n", message)
import matplotlib.pyplot as plt import queue as Q utilNum = 0 pktDrop = 0 # class for pcket class DATAPACKET: def __init__(self,pid=0,gtime=0.0,sourceid=0): self.packetId = pid self.sourceId = sourceid self.gentime = gtime self.qInTIme = -1 self.qOutTime = -1 # class for ...
import toml import watcher import signal import watcher import requests import os from argparse import ArgumentParser parser = ArgumentParser(description="QueueWatchClient") parser.add_argument("path_to_google_home", type=str, help="URL to Google Home") parser.add_argument("--local", action='store_true', help="Run wit...
# # Contains the logic to decide, based on the policy, which graphs # to transform to JitCodes or not. # from rpython.jit.codewriter import support from rpython.jit.codewriter.jitcode import JitCode from rpython.jit.codewriter.effectinfo import (VirtualizableAnalyzer, QuasiImmutAnalyzer, RandomEffectsAnalyzer, eff...
# Minimum Unavailable Coin Problem # (30m, 128MB) # 부분 집합을 만드는 로직에 대해서 파악하는 것이 중요하다. # 1 <= N <= 1,000 n = int(input()) data = list(map(int, input().split())) flag = [0] * n power_set_sum_list = [] # Powerset은 2^n -1 의 개수를 가진다. def make_power_set(flag, index): if n == index: sum = 0 for i in ran...
from torch import Tensor import torch.nn as nn from gnnff.nn.functional import shifted_softplus from gnnff.nn.base import Dense __all__ = ["OutputModuleError", "ForceMapping", "EnergyMapping"] class OutputModuleError(Exception): pass class ForceMapping(nn.Module): """ From edge embedding tensor, calc...
r""" \file se2_sam.py. Created on: Jan 11, 2021 \author: Jeremie Deray --------------------------------------------------------- This file is: (c) 2021 Jeremie Deray This file is part of `manif`, a C++ template-only library for Lie theory targeted at estimation for robotics. Manif is: (c) 2021 Jeremie Deray -------...
import re from robobrowser import RoboBrowser # Browse to Rap Genius browser = RoboBrowser(history=True) browser.open('https://www.patricbrc.org') # Search for Queen form = browser.get_form(action='/dijit__WidgetsInTemplateMixin_6/') form["username"] = 'gresch' form["password"] = 'sequencing' browser.session.header...
puan= 0 #soru1 print("Türkiyede kaç yaşından itibaren ehliyet sahibi olabilirsiniz?") cevap=input("Cevabı yazınız: ") if cevap=="18": puan+=20 print("Cevabınız doğrudur.") print("Mevcut puan durumunuz:"+" "+str(puan)) else: print("Cevabınız yanlış") print("Bu soru için hiç puan toplayamadı...
from collections import OrderedDict from typing import Any, Optional, Union import networkx as nx import numpy as np import pytorch_lightning as pl import scipy.linalg as slin from sklearn.metrics import precision_score, recall_score, accuracy_score, roc_auc_score from xgboost import XGBClassifier import torch import ...
from flask import Flask, render_template, request import pickle import numpy as np filename='HeartPatients-prediction-model.pkl' classifier = pickle.load(open(filename, 'rb')) app = Flask(__name__, static_folder='static') @app.route('/') def home(): return render_template('home.html') @app.ro...
#!/usr/bin/env python # -*- coding: utf-8 -*- import __future__ import sys import json def banner(): ban = '====' * 30 print("{}\nSAMPLE INP:\n{}\n{}".format(ban,ban,open(ip, 'r').read())) print("{}\nSAMPLE OUT:\n{}\n{}".format(ban,ban,open(op, 'r').read())) print("{}\nSTART:\n{}".format(ban,ban)) ...
#!/usr/bin/env python #-*- coding:utf-8 _*- """ @author: HJK @file: env.py @time: 2019-01-08 全局变量 """ import logging FAKE_HEADERS = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # noqa 'Accept-Charset': 'UTF-8,*;q=0.5', 'Accept-Encoding': 'gzip,deflate,sdch', '...
from piece import Piece from itertools import groupby from move import Move class Board(object): def __init__(self, size=8): self.board = [[None]*size for _ in range(size)] self.size = size self.castling = { "W": {"k": False, "q": False}, "B": {"k": False, "q": Fals...
import frappe from frappe.utils import now def create_gl_entry(doc_type, account, dr, cr, party=None): if not party: party = doc_type.party options = { 'doctype': 'GL Entry', 'voucher_type': doc_type.doctype, 'voucher_no': doc_type.name, 'posting_date': doc_type.postin...
#!/usr/bin/python # # Copyright 2018-2020 Polyaxon, 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 ...
from ronglian_sms_sdk import SmsSDK from celery_tasks.main import celery_app from . import constants accId = '8aaf0708732220a60173b6f78b5542a6' accToken = '02cfd485898847cca52798061c8703cf' appId = '8a216da87ce04099017cfac0226105b4' # 使用装饰器装饰异步任务,保证celery识别任务 @celery_app.task(bind=True, name='send_sms_code', retry...
from __future__ import unicode_literals import django from django.test import TestCase from node.resources.exceptions import InvalidResources from node.resources.json.resources import Resources class TestResources(TestCase): def setUp(self): django.setup() def test_successful_validation(self): ...
""" Font metrics for the Adobe core 14 fonts. Font metrics are used to compute the boundary of each character written with a proportional font. The following data were extracted from the AFM files: http://www.ctan.org/tex-archive/fonts/adobe/afm/ """ ### BEGIN Verbatim copy of the license part # # Adobe Core...
# -*- coding: utf-8 -*- # Copyright (c) 2015-2020, Exa Analytics Development Team # Distributed under the terms of the Apache License 2.0 """ Parser for 'A D F' Calculations ###################################### This module provides the main parser (user facing) for parsing 'A D F' output files. Although there are som...
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import xlsxwriter import logging import os from xmind2testcase.utils import get_xmind_testcase_list_dict, get_absolute_path """ Convert XMind fie to qq testcase excel file """ def xmind_to_qqtestcase_file(xmind_file): """Convert XMind file to a qqtestcase file""" ...
from multipledispatch import dispatch from pyspark.sql import DataFrame from pyspark.sql import functions as F # Helpers import optimus.create as op from optimus.functions import filter_row_by_data_type as fbdt from optimus.helpers.checkit import is_list_of_str_or_int from optimus.helpers.constants import * from optim...