code
stringlengths
1
199k
props = lambda process, current: { "IceDiscovery.Timeout": 50, "IceDiscovery.RetryCount": 5, "IceDiscovery.Port": current.driver.getTestPort(10), "Ice.Plugin.IceDiscovery": current.getPluginEntryPoint("IceDiscovery", process) } serverProps = lambda process, current: dict(itertools.chain({ "Ice.Plugi...
from meresco.core import Observable, Transparent from meresco.html import DynamicHtml from os.path import abspath, dirname, join from meresco.oai import VERSION from meresco.components.http import StringServer, PathFilter, PathRename, FileServer from meresco.components.http.utils import ContentTypePlainText from weight...
import impressive import unittest class Geometry(unittest.TestCase): def testParsing(self): c = impressive.FrameCoordinates.parse("1024x768+1280+0") self.assertEquals(1280, c.offset_x) self.assertEquals(0, c.offset_y) self.assertEquals(1024, c.width) self.assertEquals(768, c....
import datetime from django.contrib.auth.models import User, AbstractUser, BaseUserManager, AbstractBaseUser, PermissionsMixin from django.core.validators import RegexValidator from django.db.models.fields import URLField, EmailField, CharField, DateTimeField, BooleanField, TextField from django.db import models from d...
import datetime,operator,regex,sqlite3 class SubmissionParser(object): con = sqlite3.connect('reds.db') con.row_factory = sqlite3.Row cur3 = con.cursor() cur3.execute('select * from locations where type in (1,6) and location_id not in (select * from view_false_match_cities) and location_id not in (select * from...
''' Created on Mar 12, 2013 @author: dwalker @change: 02/16/2014 ekkehard Implemented self.detailedresults flow @change: 02/16/2014 ekkehard Implemented isapplicable @change: 04/18/2014 ekkehard ci updates @change: 2015/04/17 dkennel updated for new isApplicable @change: 2015/09/09 eball Improved feedback @change: 2016...
""":mod:`pghstore` --- PostgreSQL hstore formatter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This small module implements a formatter and a loader for hstore_, one of PostgreSQL_ supplied modules, that stores simple key-value pairs. .. sourcecode:: pycon >>> dumps({u'a': u'1'}) '"a"=>"1"' >>> loads('"...
import sys import types from sqlobject.include.pydispatch import dispatcher from weakref import ref subclassClones = {} def listen(receiver, soClass, signal, alsoSubclasses=True, weak=True): """ Listen for the given ``signal`` on the SQLObject subclass ``soClass``, calling ``receiver()`` when ``send(soClass...
""" This module defines iperf3 test """ import logging import time import errno import re from lnst.Common.TestsCommon import TestGeneric from lnst.Common.ExecCmd import exec_cmd from lnst.Common.ShellProcess import ShellProcess from lnst.Common.Utils import is_installed class Iperf3(TestGeneric): def _compose_iper...
import thread import commands import getopt, sys import os import subprocess import random from time import localtime, strftime, sleep import socket import urllib2 head = "" tail = "" level = 0 folder = "l1" def filename(word): word = word.replace("'", "_") word = word.replace(" ", "_") return word def translate(wor...
"""distutils extensions for GTK+/GObject/Unix This module contains a Distribution subclass (GDistribution) which implements build and install commands for operations related to Python GTK+ and GObject support. This includes installation of man pages and gettext/intltool support. """ import os try: from py2exe impor...
__author__ = 'zappyk' import sys, re from lib_zappyk._pdf2txt import pdf2txt file_name_1 = None file_name_2 = None if len(sys.argv) > 1: file_name_1 = str(sys.argv[1]) if len(sys.argv) > 2: file_name_2 = str(sys.argv[2]) setup = {} setup['_Periodo'] = "Y=806|X=210:280" setup['_CF_Dipe'] = "Y=775|X=300:360" setu...
from mico.lib.aws import * USERDATA = """#cloud-config hostname: %s fqdn: %s manage_etc_hosts: true locale: C timezone: Europe/Madrid apt_update: true apt_upgrade: true """ def main(*args): for arg in args: deploy(arg) @async def deploy(host): """Generic deploy system for a number of hosts. Example:...
from psychopy import visual, core, event, gui #import some libraries from PsychoPy, import random import datetime import csv import os from os import listdir from os.path import isfile, join mypath = '/home/jesmasta/downloads/bg/' path_save_csv = '/home/jesmasta/downloads/psychopy_sample/' onlyfiles = [ f for f in list...
from SquareGrid import * class GridWithWeights(SquareGrid): def __init__(self, width, height): super(GridWithWeights, self).__init__(width, height) self.weights = {} def cost(self, a, b): return self.weights.get(b, 1)
from microbit import * display.show(Image.HAPPY) sleep(1000) def forward(steps): pause = 5 display.off() # Left pin13.write_digital(1) pin14.write_digital(0) pin15.write_digital(0) pin16.write_digital(1) # Right pin6.write_digital(1) pin7.write_digital(0) pin9.write_digital(0...
r"""A raw docstring. """ def look_busy(): # pylint: disable=duplicate-code xxxx = 1 yyyy = 2 zzzz = 3 wwww = 4 vvvv = xxxx + yyyy + zzzz + wwww return vvvv def look_busy_two(): xxxx = 1 yyyy = 2 zzzz = 3 wwww = 4 vvvv = xxxx + yyyy + zzzz + wwww return vvvv
from typing import List from injector import inject from booking.spider import BaseSpider from booking.spider.uniweb.math import ArchimedeTowerSpider, LuzzatiSpider, PaolottiSpider class SpiderFactory: @inject def __init__(self): self._spiders = [ArchimedeTowerSpider(), LuzzatiSpider(), PaolottiSpider()...
import json from urllib.parse import quote_plus from xl import common, covers, event, providers API_KEY = '3599c79a97fd61ce518b75922688bc38' API_ROOT_URL = 'https://ws.audioscrobbler.com/2.0/' LASTFM = None def enable(exaile): if exaile.loading: event.add_callback(_enable, "exaile_loaded") else: ...
import os import replicate from mysql.utilities.exception import MUTLibError class test(replicate.test): """setup replication This test attempts to replicate among a master and slave whose innodb settings are different. It uses the replicate test for inherited methods. """ def check_prerequisite...
__author__ = 'bromix' from youtube_plugin.kodion import service service.run()
import os import sys if __name__ == "__main__": os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "{{project_name}}.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from __future__ import division from openerp.osv import fields, orm, osv from openerp.tools.translate import _ import time from datetime import * import math from openerp.tools import float_compare import pytz class stock_production_lot(osv.osv): _inherit = 'stock.production.lot' _name = 'stock.production.lot' ...
from decoder import get_character_data from inventory import Inventory from random import gauss, randint import inventory LIST_CARAC = ["name", "maxhealth", "range_attack", "attack", "defense", "initiative", "abilities"] class UnexistingCharacterException(Exception): pass class Character...
""" * sVimPy - small Virtual interpreting machine for Python * (c) 2012 by Tim Theede aka Pez2001 <pez2001@voyagerproject.de> / vp * * python vm api wrapper * * This program 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 ...
""" *************************************************************************** Heatmap.py --------------------- Date : November 2016 Copyright : (C) 2016 by Nyall Dawson Email : nyall dot dawson at gmail dot com *********************************************...
__author__ = 'bromix' from six import PY2 import re import time from ... import kodion from ...kodion import utils from ...youtube.helper import yt_context_menu try: import inputstreamhelper except ImportError: inputstreamhelper = None __RE_SEASON_EPISODE_MATCHES__ = [re.compile(r'Part (?P<episode>\d+)'), ...
"""Zenodo records views.""" from __future__ import absolute_import, print_function import json from datetime import datetime, timedelta import pytest from flask import current_app, render_template, render_template_string, url_for from helpers import login_user_via_session from invenio_indexer.api import RecordIndexer f...
import datetime import unittest2 as unittest import requests from selenium.webdriver.support.ui import Select from bkr.server.model import SystemStatus, SSHPubKey, RenderedKickstart, \ ConfigItem, User, Provision, SystemPermission from bkr.inttest.server.selenium import WebDriverTestCase from bkr.inttest.server...
""" This page is in the table of contents. Skeiniso is an analyze viewer to display a gcode file in an isometric view. The skeiniso manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Skeiniso ==Operation== The default 'Activate Skeiniso' checkbox is off. When it is on, the functions described b...
from django.contrib import admin from .models import Apuesta, Juego class ApuestaAdmin(admin.ModelAdmin): list_display = ('fecha', 'nombre', 'juego', 'apuestas', 'fecha_juego') list_filter = ('fecha', 'fecha_juego', 'juego') search_fields = ('nombre',) class JuegoAdmin(admin.ModelAdmin): list_display = ...
from numpy import * from matplotlib.pyplot import * from numpy.testing import dec,assert_,assert_raises,assert_almost_equal,assert_allclose from scipy.sparse.linalg import eigsh from scipy.linalg import eigvalsh import pdb,time,copy,sys sys.path.insert(0,'../') from tba.hgen import SpinSpaceConfig,SuperSpaceConfig,Spac...
import os import sys from config import * DEBUG = True TEMPLATE_DEBUG = DEBUG ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT, 'apps')) sys.path.insert(0, os.path.join(ROOT, 'middlewares')) path = lambda *a: os.path.join(ROOT, *a) ADMINS = ( # ('Your Name', 'your_email@example...
from django.test import TestCase import datetime from apartmentApp.models import Message from lib.dynamo import Dynamo class MessageTestCase(TestCase): def test_message_create(self): message_id = 0 timestamp = datetime.datetime.now() message_text = 'Hello, tenant' urgency = 1 ...
__author__ = 'oskyar' from django import forms from django.utils.translation import ugettext_lazy as _ from s3direct.fields import S3DirectWidget from .models import Subject class CreateSubjectForm(forms.ModelForm): template_name = "subject_create.html" error_messages = dict(field_required=_("Es obligatorio rel...
import json from django.contrib import messages class AjaxMessaging(object): def process_response(self, request, response): if request.is_ajax(): print("ajax done: %s" % response['Content-Type']) if response['Content-Type'] in ["application/javascript", "application/json"]: ...
__author__ = 'Lenusik' from fixture.orm import ORMFixture from model.group import Group db = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="") try: l = db.get_contacts_not_in_group(Group(id='106')) for item in l: print(item) print(len(l)) finally: pass #db.destroy()
import os import sys import unittest import mock from ansible.errors import AnsibleError, AnsibleFileNotFound from ansible.playbook.play import Play sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import pyansible # noqa class TestTask(unittest.TestCase): def test_no_roles(self): ...
import unittest, os import common from autotest_lib.client.common_lib.test_utils import mock from autotest_lib.client.common_lib import error, utils as common_utils from autotest_lib.server import utils, hosts from autotest_lib.server.hosts import bootloader class test_bootloader_install(unittest.TestCase): def set...
from ...ggettext import gettext as _ from .. import CustomFilters from . import Rule class MatchesFilterBase(Rule): """ Rule that checks against another filter. This is a base rule for subclassing by specific objects. Subclasses need to define the namespace class attribute. """ labels = [_(...
import readfiles as rf import dataclean as dclean import dbcalls as dbc import infovisualisation as iv if __name__ == '__main__': path2csv = rf.getcsvpath() dtt = ["Supermarket", "ATM", "Kiosk", "Shopping", "Night Out", "Eating Out", "Transport", "Money In", "House", "Rent and Bills", "Hobbies", "Mis...
import random import time from PyQt4 import QtCore, QtGui from Code import ControlPosicion from Code.QT import Colocacion from Code.QT import Controles from Code.QT import Iconos from Code.QT import QTUtil2 from Code.QT import QTVarios from Code.QT import Tablero class WDatos(QtGui.QDialog): def __init__(self, wPar...
import argparse import signal import glob import os import ffmpy class convert_avi_to_mp4(file_list): def main(): done = False def sigint_handler(signal, frame): global done print( "\nShutting down...") done = True signal.signal(signal.SIGINT, sigint_handler) files = glob.glob(args...
""" Romulus. A manager for easy downloading of ROMs for your Retropie. Author: Arthur Moore <arthur.moore85@gmail.com> Date: 2016-11-19 License: GPLv2 """ from __future__ import unicode_literals import os from threading import Thread from PyQt4 import QtGui from PyQt4.QtCore import * import time from PyQt4.QtGui import...
from naoqi import ALProxy robot_ip = "192.168.2.100" robot_port = 9559 # default port : 9559 tts = ALProxy("ALTextToSpeech", robot_ip, robot_port) tts.setLanguage("English") tts.say("Hello, world! I am Nao robot!")
from sage.all import FiniteField, Infinity, Matrix, NumberField, PolynomialRing, QQ, cyclotomic_polynomial, sage_eval, sqrt from sage.all import HyperellipticCurve, ZZ, GF, next_prime from endomorphisms.newton import lmfdb def is_ordinary(a): assert len(a) == 5 p = sqrt(a[-1]); return not ((p**2).divides(a[...
from xml.dom.minidom import parse import string import os class DomainConfigError(Exception): pass class DataType: ATTRIBUTE = "attribute" VALUE = "value" class DomainConfigItem: def __init__(self, path, data_type): self.path = path self.data_type = data_type class DomainConfig: ...
import sys __version__ = "0.3.5" def main(): inputfile = 'apnames-utf8.csv' ofile = open('apnames-utf8-%s.yaml' % __version__,'wb') ofile.write("%%APNAMES %s # Copyright OMNILab\n" % __version__) ofile.write("---\n") ofile.write("apprefix_sjtu:\n") for line in open(inputfile, 'rb'): line...
import tornado.ioloop import tornado.web import tornado.websocket import liblo import os, string, hashlib, threading SOCKETS = {} template_path = os.path.join(os.path.dirname(__file__), "templates") static_path = os.path.join(os.path.dirname(__file__), "static") messagec = False # For caching. class MainHa...
import os import diff from mysql.utilities.exception import MUTLibError _FORMATS = ['unified','context','differ'] _DIRECTIONS = ['server1', 'server2'] class test(diff.test): """check parameters for diff This test executes a series of diff database operations on two servers using a variety of parameters. It ...
""" @author: zengchunyun """ import redis pool = redis.ConnectionPool(host="127.0.0.1", port=6379) r = redis.Redis(connection_pool=pool) """ print(r.delete("oo")) # 返回删除的列表个数 print(r.lpush('oo', 11,22,33)) # 返回的是列表的长度,从右向左添加每个元素,也就是['33', '22', '11'] print(r.lrange(name="oo", start=0, end=-1)) print(r.lpushx(name="oo...
import sys import unittest from scapy.asn1.asn1 import ASN1_PRINTABLE_STRING, ASN1_OID from scapy.layers.x509 import X509_RDN, X509_AttributeTypeAndValue from tests.utils import data_filename from pysap.SAPCredv2 import (SAPCredv2, SAPCredv2_Cred_Plain, CIPHER_ALGORITHM_3DES, CIPHER_ALGORIT...
"""convert20database.py -- Convert version 2.0 (and before) databases. In this module "old-style" means before version 80, where objects were are stored in pickled form in a single table. "new-style" means version 80, where objects were separated into different tables based on their class and each attribute was stored...
""" keeping track of your measurement files @author: MP, AS, TW, HR@KIT / 2018 @license GPL file info database ================== lets introduce a set of fid configuration settings (defaults) ===================================== fid_scan_datadir = True Indicates whether you want to scan your datadir for h5 files a...
''' Message Queue Producer @author: Bin Zhang @email: sjtuzb@gmail.com ''' import datetime import json import random import time import pika from config import * credentials = pika.PlainCredentials(broker_username, broker_password) parameters = pika.ConnectionParameters(broker_url, broker_port, vhost, crede...
import portage from portage import os from portage.dep import Atom from portage.exception import InvalidAtom from portage.package.ebuild._ipc.IpcCommand import IpcCommand from portage.util import normalize_path from portage.versions import best class QueryCommand(IpcCommand): __slots__ = ('settings',) _db = None def...
""" %HERE% """
"""Publish static resources under /static/""" import os import re from webob.exc import HTTPFound from repoze.bfg.url import model_url from repoze.bfg.view import static from karl.views.utils import get_user_home here = os.path.abspath(os.path.dirname(__file__)) static_view = static('static', cache_max_age=157680000) v...
""" The :mod:`~openlp.plugins.custom.lib.customtab` module contains the settings tab for the Custom Slides plugin, which is inserted into the configuration dialog. """ from PyQt4 import QtCore, QtGui from openlp.core.common import Settings, translate from openlp.core.lib import SettingsTab class CustomTab(SettingsTab):...
import os import sys import pdb import glob import httplib import urlparse import time import commands import rpm import rpmUtils import rpmUtils.miscutils try: import hashlib as md5 except: import md5 import logging import signal from ParallelFetch import ParallelFetch from KickstartFetch import KickstartFetch...
from enigma import eTimer, eDVBSatelliteEquipmentControl, eDVBResourceManager, \ eDVBDiseqcCommand, eDVBFrontendParametersSatellite, eDVBFrontendParameters,\ iDVBFrontend from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Plugins.Plugin import PluginDescriptor from Components.Label impor...
""" Created on Thursday 16 April 2015 @author: Andrew Horsfield, Marc Coury and Max Boleininger This module contains functions that are needed once the molecular orbitals are populated by electrons. """ import numpy as np import math import TBH import sys import time import myfunctions from Verbosity import * import ra...
""" FILE: css.py @author: Cody Precord @summary: Lexer configuration file for Cascading Style Sheets. """ __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: _css.py 69877 2011-12-01 03:04:21Z CJP $" __revision__ = "$Revision: 69877 $" import wx import wx.stc as stc import synglob import syndata CSS1_KE...
import addonHandler addonHandler.initTranslation() def onInstall(): import gui import wx import winVersion currentWinVer = winVersion.getWinVer() # Windows App Essentials requires Windows 10 or later. # Translators: title of the error dialog shown when trying to install the add-on in unsupported systems. # Unsup...
'''Test rearrangement of color components using the OpenGL color matrix. The test will be skipped if the GL_ARB_imaging extension is not present. You should see the RGB test image correctly rendered. Press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: MATRIX_RGB.py 1393 2007-11-10 01:...
import argparse import os import signal import sys from .tags import Tags from collections import OrderedDict default_format = '{{EXIF.DateTimeOriginal:%Y{sep}%m - %B{sep}%d}}'.format(sep=os.sep) default_unknown = 'Unknown' class Sorter(object): """Image sorter. Uses EXIF data to put images in particular directorie...
import httplib import array import httplib import StringIO import socket import errno import unittest TestCase = unittest.TestCase from test import test_support HOST = test_support.HOST class FakeSocket: def __init__(self, text, fileclass=StringIO.StringIO): self.text = text self.fileclass = filecla...
""" This module defines the BasePackageManager Class which provides an implementation of the packaging system API providing methods to fetch, upload and remove packages. Site specific extensions to any of these methods should inherit this class. """ import fcntl, logging, os, re, shutil from autotest.client import os_d...
import itertools rank_to_val = {0: '2', 1: '3', 2: '4', 3: '5', 4: '6', 5: '7', 6: '8', 7: '9', 8: 'T', 9: 'J', 10: 'Q', 11: 'K', 12: 'A'} val_to_rank = {} for r, val in rank_to_val.items(): val_to_rank[val] = r def make_deck(): suits = '♣♦♥♠' ranks = '23456789T...
import os import sys import time def getDateTime(): timeFormat = '%Y%m%d_%H%M%S' return time.strftime( timeFormat, time.localtime(time.time()) ) def getHostname(): sys = os.name if sys == 'nt': hostname = os.getenv('computername') return hostname elif sys == 'posix': host = os.popen('echo $HOSTNAME') try: ...
import unittest import sys import os sys.path.append(os.pardir) import metadata import os.path import errno import tempfile import shutil class TestMetadataMngComponent(unittest.TestCase): """In these test, the results of usual os method and metadata management methods (fs and db) are compared. """ def ...
from vector import Vector from matrix import Matrix from _token_scanner import TokenScanner class HiddenMarkovModel: """ Implementation of a hidden Markov model, a statistical Markov model in which the system being modeled is assumed to be a Markov process with unobserved (hidden) states. """ de...
import os import sys from toolib.util.paths import iterFilePaths from toolib.util.reprs import repr from wmlib.webkit.FormDom import Dom from gettext_config import FORMS, FORMS_OUTPUT, FORMS_ATTRS import time import xml.dom from toolib.util import strings def main(output = FORMS_OUTPUT, *inputPaths): inputPaths = inpu...
from __future__ import unicode_literals from collections import OrderedDict from django.core.exceptions import PermissionDenied from django.http import Http404 from django.utils.encoding import force_text from rest_framework.fields import empty from rest_framework.metadata import SimpleMetadata from rest_framework impo...
import random class KnuthShuffle: '''使用knuth_shuffle方法进行数组的随机排列''' @classmethod def shuffle(self, l): for i in range(len(l)): r = random.randint(0,i) l[i], l[r] = l[r], l[i] if __name__ == '__main__': l = [0,1,2,3,4,5,6,7,8,9] KnuthShuffle.shuffle(l) print(l)
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('stories', '0005_auto_20150820_0817'), ] operations = [ migrations.AlterField( model_name='story', ...
from sos.report.plugins import CosPlugin, IndependentPlugin from sos.policies import LinuxPolicy def _blank_or_comment(line): """Test whether line is empty of contains a comment. Test whether the ``line`` argument is either blank, or a whole-line comment. :param line: the line of text to be ...
import thread import time from math import sin, cos, radians from Colorduino import Colorduino from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM, \ SOL_SOCKET, SO_REUSEADDR from sys import argv SQUARE_ROOT_OF_TWO = 1.4143 COLOR_RED = 0xFF0000 COLOR_YELLOW = 0xFF8000 COLOR_GREEN = 0x00FF00 COLOR_WR...
from PIL import Image,ImageGrab import win32gui,win32con,win32api import logging,os,time import hashlib,pickle def wdict(dictfile,dic): if os.path.isfile(dictfile): oldict = open(dictfile,'rb') oldata = pickle.load(oldict) oldata.update(dic) output = open(dictfile,'wb') pickl...
from . import orm class User (orm.getBase()) : __tablename__ = 'myuser' def __init__ (self, name='', fullname='', pwd='') : self.name = name self.fullname = fullname self.password = pwd id = orm.Column(orm.Integer, primary_key=True) name = orm.Column(orm.String) fullname = or...
from ansible.playbook import PlayBook from ansible import callbacks, utils def playbook_run(inventory, playbook, default_user=None, default_port=None, default_pri_key_path=None): stats = callbacks.AggregateStats() playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_cb = callbacks.Playb...
""" Classes associated with dynamic module loading Copyright: John Stowers, 2006 License: GPLv2 """ import gobject import os, os.path import traceback import pydoc import logging log = logging.getLogger("Module") import conduit.dataproviders import conduit.ModuleWrapper as ModuleWrapper import conduit.Knowledge as Know...
''' Created on 2015. 6. 8. @author: jongyeob ''' from __future__ import absolute_import import logging from ..utils import datetime as dt from ..utils import download as dl from . import aia __all__ = [] LOG = logging.getLogger(__name__) REMOTE_DATA_DIR = 'http://jsoc.stanford.edu/data/aia/synoptic/%Y/%m/%d/H%H00/' ...
import math import random from quodlibet import _ from quodlibet.order.reorder import Reorder from quodlibet.plugins.playorder import ShufflePlugin from quodlibet.order import OrderRemembered from quodlibet.qltk import Icons from quodlibet.compat import iteritems class PlaycountEqualizer(ShufflePlugin, OrderRemembered)...
import os import sys import string def usage(): sys.stderr.write('result.py [file]\n') def optimal(pkt): opt=0.0 if pkt<=12: opt=0.0000804+pkt*0.0000012 elif pkt<=36: opt=2*0.0000804+(pkt-12)*0.0000012 elif pkt<=84: opt=3*0.0000804+(pkt-36)*0.0000012 else: opt=3*0.0000804+(pkt-84)*0.0000012 return opt de...
import sys def is_divisible(x, y, n): result = "" for i in range(n): j = i + 1 if j % x == 0 and j % y == 0: result += " FB" elif j % x == 0: result += " F" elif j % y == 0: result += " B" else: result += " "+str(j) retu...
import heapq class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if not intervals: return intervals sortedIntervals = self.sort(intervals) start = sortedIntervals[0].start lates...
import os import unittest import tempfile import testing_config import app from app.models.users import KBUser class ThreatKBTestCase(unittest.TestCase): def setUp(self): app.app.config.from_object("testing_config") self.app = app.app.test_client() with app.app.app_context(): # R...
import emsa_pkcs1_v15 import primitives import exceptions import hashlib def sign(private_key, message, hash_class=hashlib.sha1): '''Produce a signature of string using a RSA private key and PKCS#1.5 padding. Parameters: private_key - a RSA private key message - a string to sign R...
import random import LCEngine4 as LCEngine import chess import chess.syzygy class T4: def __init__(self): self.tb = chess.syzygy.Tablebases("./IntFiles/syzygy") def better_moves(self, fen, move): dic = self.checkFen(fen) def x_wdl(xwdl): li_xmin_pv = [] xmin_dtz =...
from startup import * from resources.picture import Picture class TestPictureFunctions(unittest.TestCase): def setUp(self): # Instantiate a Picture object self.picture = Picture() def tearDown(self): # Release instantiated objects del self.picture def test_init(self): ...
def pascals_triangle(n): x = [[1]] for i in range(n - 1): x.append([sum(i) for i in zip([0] + x[-1], x[-1] + [0])]) return x s = pascals_triangle(5) for i in s: print i print 'test'
""" Time domain filtering class """ from __future__ import absolute_import from __future__ import print_function import Obit, _Obit, FFT class TimeFilter(Obit.TimeFilter): """ Python Obit interface to display server This class is for creating and using the interface to a plot TimeFilter Members with python ...
import sys import os from utilities import languageTranslate, log, hashFile from pn_utilities import OSDBServer import xbmc import urllib def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input ok = False msg = "" osdb_server = O...
from client import ServerCommandHandle, Encrypter, Client import sys from MyEncrypter import * class HandleInstance(ServerCommandHandle): def errorHandle(self, message): print "error", message def onlineHandle(self, onlineList): print "online", onlineList def offlineHandle(self, offlineList)...
from Host import Host class HostManager: def __init__(self, hosts): self.hosts = hosts """ self.filename = filename f = open(self.filename, 'r') for line in f: e = unicode(line.replace("\n","")) self.hostList.append(e) self.hosts.append(Hos...
from typing import Any import asyncio import contextlib import logging import os import os.path from noisidev import unittest from noisidev import unittest_mixins from noisidev import demo_project from noisicaa.constants import TEST_OPTS from noisicaa import audioproc from noisicaa import node_db from noisicaa import e...
class Base(object): """base class for all other bookbrainz db classes Role of fetch_from_json is to parse data from JSON to the object on which it is called. If data is None or empty then default constructor without any parameters is called. If it is not, then fetch_from_json_filled is called, which...
"""Dictionary/Set lab assignment""" chris = { 'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate' } print chris del chris['cake'] print chris chris['fruit'] = 'Mango' print "keys:", chris.keys() print "vals:", chris.values() print "cake is key in dict 'chris'?", 'cake' in chris print "Mango is val in di...
import sys import pts sys.exit(pts.main())