code
stringlengths
1
199k
__author__ = 'Ahmed Hani Ibrahim' import numpy as np class ArmedBandit(object): __mue = 0.0 __sigma = 0.0 def __init__(self, mue, sigma): self.__mue = mue self.__sigma = sigma def printData(self): return np.random.normal(self.__mue, self.__sigma)
''' Use feather plot to examine differences in the cleaned image to Arecibo. ''' import os from glob import glob import numpy as np import astropy.units as u import matplotlib.pyplot as plt from radio_beam import Beam from astropy.utils.console import ProgressBar import astropy.io.fits as fits from image_tools.radialpr...
def make_sandwich(*ingredients): """Print the ingredients in the sandwich""" print ("Making a sandwich with the following ingredients:") for ingredient in ingredients: print("\t- " + ingredient) print("\n") make_sandwich("Flatbread", "American Cheese", "Green Peppers") make_sandwich("Italian bread", "Swiss cheese...
import Code, EventList, VeriTime, VeriSignal import VeriExceptions import datetime, sys class Global(object): # Debug values (bit vector) DBG_STATS = 1<<1 DBG_EVENT_LIST = 1<<2 #Options values (opt_vec) OPT_NO_WARN = 1<<1 # Dont print warnings def __init__(self, sim_end_time_fs=0xfffffff...
from django.contrib import admin from django import forms from models import Gallery, Photo class GalleryAdmin(admin.ModelAdmin): exclude = ['cover'] prepopulated_fields = {"slug": ("name",)} class PhotoAdminForm(forms.ModelForm): is_cover = forms.BooleanField(required=False) class Meta: model =...
class TheThing(object): def __init__(self): self.number = 0 def some(self): print "I got called" def add(self, more): self.number += more return self.number a = TheThing() b = TheThing() a.some() b.some() print a.add(20) print b.add(30) print a.number print b.number class TheMultiplier(object): ...
import functools from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import Pipe...
from .unitclass import UnitClass class ClassBuildOrder: """Represents a generic build order, that is, an order to be given to an engineer to construct a structure as part of a template, but specified using a UnitClass rather than any specific Unit.""" @staticmethod def safely_create(unit_class: UnitClas...
"""FinalYearProject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') ...
from command_line_interpreter import * from plugin_docker import * from plugin_dockyard import * from plugin_stack import *
print("Hello world from Python!")
from netaddr import IPNetwork, AddrFormatError, IPAddress from elasticsearch import Elasticsearch from elasticsearch import exceptions from collections import OrderedDict from pathlib import Path import configparser import argparse import string import json import sys import os import re def get_es_cluster_ip(): ""...
"""Auto-generated file, do not edit by hand. NF metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_NF = PhoneMetadata(id='NF', country_code=672, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[13]\\d{5}', possible_number_pattern='\\d...
from unit_testing import * import unittest class UnitTests(unittest.TestCase): def setUp(self): print('setUp()...') self.hash1 = Hash('1234') self.email1 = Email('zmg@verizon.net') def test(self): print('testing hash...') self.assertEqual(self.hash1, self.hash1) #failed ...
from check_grad import check_grad from utils import * from logistic import * import matplotlib.pyplot as plt def run_logistic_regression(hyperparameters): # TODO specify training data train_inputs, train_targets = load_train() valid_inputs, valid_targets = load_valid() # N is number of examples; M is th...
""" The MIT License (MIT) Copyright (c) 2012 Martin Hammerschmied 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, ...
''' This checks if all command line args are documented. Return value is 0 to indicate no error. Author: @MarcoFalke ''' from subprocess import check_output import re FOLDER_GREP = 'src' FOLDER_TEST = 'src/test/' CMD_ROOT_DIR = '`git rev-parse --show-toplevel`/%s' % FOLDER_GREP CMD_GREP_ARGS = r"egrep -r -I '(map(Multi...
import epmsdk.communication as epmcomm import epmsdk.dataaccess as epmda import epmsdk.historicaldata as epmhda import datetime TAGNAME = 'wb_Tin' SERVER = 'localhost' USER = 'sa' PSW = 'admin' conexao = epmcomm.epmConnect(hostname=SERVER, username=USER, password=PSW) data_object = epmda.epmGetDataObjectAnnotation(cone...
from matplotlib import gridspec import math import matplotlib import nanopores as nano import nanopores.geometries.pughpore as pughpore import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter import numpy as np import os import sys import nanopores.tools.fields as f HOME = os.path.expanduser("~...
""" utility classes for Event Registry """ import six, warnings, os, sys, re, datetime, time mainLangs = ["eng", "deu", "zho", "slv", "spa"] allLangs = [ "eng", "deu", "spa", "cat", "por", "ita", "fra", "rus", "ara", "tur", "zho", "slv", "hrv", "srp" ] conceptTypes = ["loc", "person", "org", "keyword", "wiki", "concep...
""" COSMO TECHNICAL TESTSUITE Various tools used to read and modify fortran namelists """ import os, sys, re from ts_error import StopError, SkipError __author__ = "Xavier Lapillonne, Nicolo Lardelli" __email__ = "cosmo-wg6@cosmo.org" __maintainer__ = "xavier.lapillonne@meteoswiss.ch" namelist_pattern=re.compi...
import configparser from enigma import rotor from enigma import reflect from enigma import plugboard from enigma import enigma_exception config = configparser.ConfigParser(interpolation=configparser. ExtendedInterpolation()) class EnigmaMachine: """Enigma Machine""" def __init...
"""py_pesa URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
from Task import Task from User import User from Markdown import Markdown from utils import * from stasis.ActiveRecord import ActiveRecord, link class Note(ActiveRecord): task = link(Task, 'taskid') user = link(User, 'userid') def __init__(self, taskid, userid, body, timestamp = None, id = None): ActiveRecord.__in...
"""Standard authentication backend.""" from __future__ import unicode_literals import logging from django.conf import settings from django.contrib.auth import hashers from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from django.utils import six from django.utils.translat...
""" Tests for the :py:class:`luma.core.device.parallel_device` class. """ from unittest.mock import Mock, call from luma.core.device import parallel_device def test_4bit(): serial = Mock(unsafe=True) serial._bitmode = 4 serial._pulse_time = 1 pd = parallel_device(serial_interface=serial) pd.command(...
def printname(): print("Server Module")
import subprocess import logging import os try: subprocess.call(['git pull origin master'], shell=True) subprocess.call(['sudo /etc/init.d/apache2 restart'], shell=True) except Exception as e: logging.error(e)
from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import pprint import re import sys import traceback from inspect import CO_VARARGS from inspect import CO_VARKEYWORDS from weakref import ref import attr import pluggy import py import six from si...
from typing import Optional from mitmproxy.contrib.wbxml import ASCommandResponse from . import base class ViewWBXML(base.View): name = "WBXML" __content_types = ( "application/vnd.wap.wbxml", "application/vnd.ms-sync.wbxml" ) def __call__(self, data, **metadata): try: ...
import functools from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline impo...
import uuid, os import codecs from scrapy.exceptions import IgnoreRequest from scrapy.http import TextResponse from registry.settings import PDFTOHTML_TEMP_DIR as tmp from scrapy.contrib.downloadermiddleware.retry import RetryMiddleware from twisted.internet.error import TimeoutError as ServerTimeoutError, \ DNSLoo...
from test_framework.test_framework import KcoinTestFramework from test_framework.util import * class ZapWalletTXesTest (KcoinTestFramework): def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 3) def setup_network(self, spl...
import re from ..field import Field class Text(Field): min = None max = None multiline = False pattern = None options = None trim = True messages = { 'min': 'Must be at least {min} characters long.', 'max': 'Must have no more than {max} characters.', 'multiline': 'Mus...
from __future__ import absolute_import import json import os from StringIO import StringIO from urlparse import urlparse, parse_qs import threading import re from functools import partial import hashlib from datetime import datetime import time import disco from disco.core import Disco from .io import puts from . imp...
import gzip, base64 _g = ("Ah+LCAAAAAAABACT7+ZgAAEWhrc3HLsvO4gwPNg/ybdMn3Pr5JTbtzaw6N+zrdLIDTzdsEZC7O1J+fchYbp5u7vWeJTv57eacOaM9tJ+c/2badaPC7+9evb499nb/jdP" + "n78+e3bOlt11xXt/Trjqy8bQH8rIQBPwwSP1A/+Xn7trospKJW7tOXl6HaezJb/z5bZEo5k2+qc/GfEsXNv+duLbyHutZStuK3NXzPpnIb2O726MbncpTy7P58OfbUJr" + "/1nlO/uwasfpXDLIW60Y+/1...
"""Support for Tibber sensors.""" from __future__ import annotations import asyncio from datetime import timedelta import logging from random import randrange import aiohttp from homeassistant.components.recorder.models import StatisticData, StatisticMetaData from homeassistant.components.recorder.statistics import ( ...
"""Constants that define defaults.""" import re EXCLUDE = ( ".svn", "CVS", ".bzr", ".hg", ".git", "__pycache__", ".tox", ".eggs", "*.egg", ) IGNORE = ("E121", "E123", "E126", "E226", "E24", "E704", "W503", "W504") SELECT = ("E", "F", "W", "C90") MAX_LINE_LENGTH = 79 TRUTHY_VALUES = {...
import random import string def random_ascii(length): return ''.join(random.choice(string.ascii_letters) for i in range(length))
import os import sys from fnmatch import fnmatchcase from distutils.util import convert_path standard_exclude = ('*.py', '*.pyc', '*~', '.*', '*.bak', '*.swp*') standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info') def find_package_data( ...
{ 'name': 'Chapter 06, Recipe 01 code', 'summary': 'Define onchange methods', 'depends': ['my_module'], }
from jsonrpc import ServiceProxy access = ServiceProxy("http://127.0.0.1:6668") pwd = raw_input("Enter wallet passphrase: ") access.walletpassphrase(pwd, 60)
r''' Here we define the basic Node class for LatexTree objects - defines only parent and children fields - defines basic recursive functions for tree traversal These functions will be used by `LatexTree` objects for document processing - e.g. tree.write_xml(), tree.write_unicode(), tree.xref_table(), etc ''...
from gmrf import CovKernel from mesh import QuadMesh from mesh import Mesh1D from mesh import convert_to_array from fem import QuadFE from fem import DofHandler from plot import Plot import matplotlib.pyplot as plt import numpy as np import unittest class TestCovKernel(unittest.TestCase): def test_eval(self): ...
from django.conf import settings from mediasync import JS_MIMETYPES, CSS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realp...
""" Provides --format=syslog results formatter - pushes JSON messages via syslog """ from __future__ import absolute_import import json import syslog from collections import OrderedDict import indexdigest def _format_report(database, report): """ :type database indexdigest.database.Database :type report ind...
import unittest import gray class BitflipTestCase(unittest.TestCase): def test_run(self): prev = None seen = set() w = 8 hamming_compares = 0 for cur in gray.run(w): if prev is not None: hamming_compares += 1 self.assertEqual(hammin...
from haystack import indexes from myaccount.models import bizProject class ProjectIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) created_at = indexes.DateTimeField(model_attr='created_at') updated_at = indexes.DateTimeField(model_attr='updated_at') ...
import imp from migrate.versioning import api from app import db from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO migration = SQLALCHEMY_MIGRATE_REPO + '/versions/%03d_migration.py' % (api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) + 1) tmp_module = imp.new_module(...
"""Gives a picture of the CPU activity between timestamps. When executed as a script, takes a loading trace, and prints the activity breakdown for the request dependencies. """ import collections import logging import operator import request_track class ActivityLens(object): """Reconstructs the activity of the main r...
import sys import re def extract(s, pos=False): p = '' if pos else '-?' return [int(x) for x in re.findall(fr'{p}\d+', s)] def solved(board): for i in range(5): if all(board[i][j] is None for j in range(5)): return True for i in range(5): if all(board[j][i] is None for j in r...
import collectd import re DEBUG = False def values_to_dict(values): """ Convert `collectd.Values` instance to dictionary. :param values: Instance of `collectd.Values`. :returns: Dictionary representing `collectd.Values`. """ assert isinstance(values, collectd.Values) values_dict = {'time': v...
from django.conf.urls import patterns, url from syslogs.views import system_log, new_logs urlpatterns = patterns( '', url(r'^$', system_log), url(r'^new_logs/$', new_logs), )
from ._kmer_counter import KmerCounter __license__ = "MIT" __version__ = "0.2.1" __author__ = "Nikolay Romashchenko" __maintainer__ = "Nikolay Romashchenko" __email__ = "nikolay.romashchenko@gmail.com" __status__ = "Development"
from django import forms from olcc.models import Store COUNTIES = ( (u'baker', u'Baker'), (u'benton', u'Benton'), (u'clackamas', u'Clackamas'), (u'clatsop', u'Clatsop'), (u'columbia', u'Columbia'), (u'coos', u'Coos'), (u'crook', u'Crook'), (u'curry', u'Curry'), (u'deschutes', u'Desch...
import uuid from django.core.mail import send_mail from django.core.management import call_command from django.http import Http404 from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from populus import Project from main.forms import RegistryEmailForm from ma...
from parity import parse_conferences from nose.tools import assert_equals from StringIO import StringIO CONFERENCE_2010 = StringIO(""" 3 Major Teams ACC Boston College" Clemson" Big 12 Colorado" Iowa State" Texas A&M" """) OUTPUT_2010 = { "year": 2010, "conferences": [ { "name": ...
""" Create the heartbeat evaluation model. """ import neurokit as nk import numpy as np import pandas as pd import biosppy import matplotlib.pyplot as plt import seaborn as sns import sklearn import sklearn.neural_network data = nk.read_nk_object("PTB-Diagnostic_database-ECG.nk") All = [] for participant in data["Contr...
from django.test import TestCase from myproject.core.forms import PersonForm, AddressForm, ProductForm class PersonFormTest(TestCase): # def test_cpf_is_digit(self): # 'CPF must only accept digits.' # form = self.make_validated_form(cpf='ABCD0000000') # self.assertItemsEqual(['cpf'], form.er...
""" Sample a 1D function to given tolerance by adaptive subdivision. The result of sampling is a set of points that, if plotted, produces a smooth curve with also sharp features of the function resolved. This routine is useful in computing functions that are expensive to compute, and have sharp features — it makes more...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0111_auto_20200513_2252'), ] operations = [ migrations.AlterField( model_name='contentkind', name='kind', ...
import json import Queue import random import re import sys MAX_NGRAM = 10 SAMPLING = 1000000 DICT_SIZE = 4096 def conv_to_binary(string): n = 0 for i in string: n = n << 1 if i == '1': n = n + 1 return n class HuffmanNode(object): def __init__(self, left=None, right=None, ro...
import logging from moonreader_tools.parsers.base import BookParser from moonreader_tools.utils import ( get_book_type, get_moonreader_files_from_filelist, get_same_book_files, title_from_fname, ) from .drobpox_utils import dicts_from_pairs, extract_book_paths_from_dir_entries class DropboxDownloader(ob...
from django.test import TestCase, override_settings from django.contrib import admin from django.contrib.auth import get_user_model from django.conf.urls import url from django.urls import reverse from django.utils.encoding import force_bytes from .models import Author, Play, Poem, Kingdom, King, Soldier User = get_use...
""" ideas: - direct word search - daily notifications - practice common SAT/GRE words (optional for now) -- will requre a separate API """ print ("Initial commit, project begins soon")
from __future__ import print_function, unicode_literals import ConfigParser from os import getenv import luigi from tasks.transform import StopListText, CreateTokens, CreateTokenLinks from ops.transform import process_text from orm.tables import Meetingdate, Token, Tokenlink from ops.loading import load_token_links_to_...
import numpy as np foo = np.array([ (1, 'Sirius', -1.45, 'A1V'), (2, 'Canopus', -0.73, 'F0Ib'), (3, 'Rigil Kent', -0.1, 'G2V') ], dtype='int16, a20, float32, a10') print(foo) print(foo.dtype) foo = np.array([ (1, '...
from django.template.loader import render_to_string from django.http import JsonResponse from prescription.views import CreatePrescriptionView from prescription.forms import (CreatePrescriptionForm) from prescription.models import (Prescription, PrescriptionHasMedicine, ...
import unittest import json import mock import runabove class TestRunabove(unittest.TestCase): application_key = 'test_apkey' application_secret = 'test_apsecret' consumer_key = 'test_conkey' access_rules = [ {'method': 'GET', 'path': '/*'}, {'method': 'POST', 'path': '/*'}, {'me...
import itertools from typing import ( Any, AnyStr, Callable, Dict, Iterable, Iterator, List, Optional, TypeVar, Union, cast, overload, ) T = TypeVar("T") class TableError(RuntimeError): pass def format_timespan(seconds: float): if seconds < 60: return "{:....
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('chat', '0001_initial'), ] operations = [ migrations.CreateModel( name='Member', fields=[ ...
import os, sys, time import urllib2 def main(): host = "http://localhost:30001/write?port=/dev/ttyUSB0" try: req = urllib2.urlopen(host, "[data to write]") print("Reply data:") print(req.read()) except Exception as e: print("exception occurred:") print(e) retu...
""" spaceshooter.py Author: <your name here> Credit: <list sources used, if any> Assignment: Write and submit a program that implements the spacewar game: https://github.com/HHS-IntroProgramming/Spacewar """ from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame SCREEN_WIDTH = 640 SCREEN_HEI...
import functools int2 = functools.partial(int, base=2) print (int2('1001001')) maxWith1000 = functools.partial(max,1000) print (maxWith1000(1,100,200))
"""This tutorial introduces the LeNet5 neural network architecture using Theano. LeNet5 is a convolutional neural network, good for classifying images. This tutorial shows how to build the architecture, and comes with all the hyper-parameters you need to reproduce the paper's MNIST results. This implementation simplif...
from sqlalchemy.test.testing import eq_, assert_raises, assert_raises_message import StringIO, unicodedata from sqlalchemy import types as sql_types from sqlalchemy import schema from sqlalchemy.engine.reflection import Inspector from sqlalchemy import MetaData from sqlalchemy.test.schema import Table, Column import sq...
try: from django.conf.urls.defaults import patterns, url except ImportError: from django.conf.urls import patterns, url urlpatterns = patterns('ratings.views', url(r'^vote/$', 'vote', name='ratings_vote'), )
from django.core.exceptions import ImproperlyConfigured from django.views.generic.base import TemplateView from django.views.generic.list import ListView from limbo.context import PageContext class GenericDatatableAjaxView(ListView): datatable = None response_type='json' is_ajax=True template_name='data...
__VERSION__ = '0.0.1'
import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * import threading from termcolor import colored os.system("clear") print(""" .____________ _____ __________ | \_ ___ \ / ______ ) | / \ \/ / \ / \| ___) ...
"""UserEmailAddressVerificationHandlerFunction Validates an e-mail address for a new user registration or a changed e-mail address from an existing user with a token provided by the user after being retrieved from the message sent to their e-mail address. """ from __future__ import print_function import os import json ...
from circuits.net.events import connect from circuits import Event, Component, Timer from ..plugin import BasePlugin class reconnect(Event): """reconnect Event""" class Reconnector(Component): def init(self, host, port, interval=5, increment=5): self.host = host self.port = port self.int...
""" Example script that shows how to use PyOTA to send a transfer to an address. """ from argparse import ArgumentParser from sys import argv from iota import ( __version__, Address, Iota, ProposedTransaction, Tag, TryteString, ) from .address_generator import get_seed, output_seed def main(address, depth, ...
from django.conf.urls import * urlpatterns = patterns('', url(r'^$', views.blog, name='blog'))
import MaxPlus from anima.dcc.base import DCCBase def get_max_version(): """Encapsulates the very cumbersome 3ds Max version string retrieval process and returns a simple string that contains the current MAX version. :return: """ versions_LUT = {17000: "2015", 18000: "2016", 19000: "2017"} c...
import ConfigParser import datetime import logging import os import arrow import tapioca_toggl logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('TOGGL') config = ConfigParser.RawConfigParser() config.read(os.path.expanduser('~/.togglrc')) logger.debug('Reading auth from user config') api = tapioca_to...
import uuid from io import StringIO from simtk import unit try: from nglview import Trajectory as _NGLViewTrajectory except ImportError: _NGLViewTrajectory = object class _OFFTrajectoryNGLView(_NGLViewTrajectory): """ Handling conformers of an OpenFF Molecule as frames in a trajectory. Only to be us...
from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.urls import reverse from guardian.shortcuts import assign_perm from feder.users.factories import UserFactory class PermissionStatusMixin: """Mixin to verify object permission status codes for different users Req...
from shapely.wkt import loads as wkt_loads import dsl from . import FixtureTest class NeMinZoomRoads(FixtureTest): def setUp(self): super(NeMinZoomRoads, self).setUp() # note: uses existing fixture from 976-fractional-pois self.generate_fixtures(dsl.way(1, wkt_loads('LINESTRING (-74.34536905...
import unittest import os import json from dbreportingwrapper import database class SqliteTestCase(unittest.TestCase): """ Creates dummy sqlite file to test database functions """ def setUp(self): # Create the testing directory self.testDir = os.path.abspath('test_data') if not os.pa...
from aioriak.datatypes import TYPES def bucket_property(name, doc=None): def _prop_getter(self): return self.get_property(name) def _prop_setter(self, value): return self.set_property(name, value) return property(_prop_getter, _prop_setter, doc=doc) class Bucket: ''' The ``Bucket`` o...
import os import shutil import unittest from collections import namedtuple from conans.client.cmd.export import _replace_scm_data_in_conanfile from conans.client.loader import _parse_conanfile from conans.client.tools import chdir from conans.model.ref import ConanFileReference from conans.model.scm import SCMData from...
""" ProcessTools ============ Module which groups the main functions and utilities to manage large processes in which we need common tasks of logging, storing and measuring the process. """ from test_processtools import test from processer import Processer
""" 模拟器 采用面向对象的离散时间模拟框架 """ from random import randint from prio_queue import PrioQueue class Simulation(object): """模拟器基类""" def __init__(self, duration): """""" self._eventq = PrioQueue() # 事件队列 self._time = 0 # 当前时间 self._duration = duration # 模拟总时长 def run(self): ...
from aldryn_client.forms import BaseForm, CharField, NumberField, CheckboxField class Form(BaseForm): email_host = CharField('SMTP Host', initial='localhost') email_port = NumberField('SMTP Port', initial=25) email_host_user = CharField('SMTP User', initial='') email_host_password = CharField('SMTP Pass...
__author__ = 'ipetrash' from pluginmanager_ui import Ui_PluginManager from PySide.QtGui import * from PySide.QtCore import * from pluginmodel import PluginModel from pluginsloader import PluginsLoader class PluginManager(QDialog, QObject): def __init__(self, data_singleton, parent=None): super().__init__(pa...
import logging from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ import stripe from .models import Supporter log = logging.getLogger(__name__) class SupporterForm(forms.ModelForm): class Meta: model = Supporter fields = ( 'l...
from flask import Blueprint admin_module = Blueprint( "admin", __name__, url_prefix = "", template_folder = "templates", static_folder = "static" ) from . import views
"""Test the bumpfee RPC. Verifies that the bumpfee RPC creates replacement transactions successfully when its preconditions are met, and returns appropriate errors in other cases. This module consists of around a dozen individual test cases implemented in the top-level functions named as test_<test_case_description>. T...
from db.common import Base from db.common import session_scope class SpecificEvent(): @classmethod def find_by_event_id(self, event_id): # retrieving table name for specific event table_name = self.__tablename__ # finding class associated with table name for c in Base._decl_class...