code
stringlengths
1
199k
from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) exce...
import sys def main(): args = sys.argv print str(args) extract_symbols(args[1], args[2]) def extract_symbols(input_file, output_file): fin = open(input_file, 'r') fout = open(output_file, 'w') for line in fin: if '|' in line: cols = line.split('|') if not '$' in cols[1]: # Skip preferred sh...
import unittest from vps.console import get_headers, column_size class TestDisplay(unittest.TestCase): def test_headers(self): h = [ {'h0': 0, 'h1': 1, }, {'h0': 0, 'h1': 1, }, ] self.assertEqual(get_headers(h), ['h0...
__author__ = 'Tom Schaul, tom@idsia.ch' from random import choice from scipy import zeros from twoplayergame import TwoPlayerGame class CaptureGame(TwoPlayerGame): """ the capture game is a simplified version of the Go game: the first player to capture a stone wins! Pass moves are forbidden.""" # CHECKME: s...
"""Two different implementations of merge sort. First one is the standard sort that creates the result to new list on each level. Second one is an in-place sort that uses two alternating buffers and offsets to limit memory usage to O(2n). """ def sort(lst): """Standard merge sort. Args: lst: List to sor...
import os import unittest import vtk, qt, ctk, slicer import math import sys class AstroMomentMapsSelfTest: def __init__(self, parent): parent.title = "Astro MomentMaps SelfTest" parent.categories = ["Testing.TestCases"] parent.dependencies = ["AstroVolume"] parent.contributors = [""" Davide Punzo...
""" Display network speed and bandwidth usage. Configuration parameters: cache_timeout: refresh interval for this module (default 2) format: display format for this module *(default '{nic} [\?color=down LAN(Kb): {down}↓ {up}↑] [\?color=total T(Mb): {download}↓ {upload}↑ {total}↕]')* nic: net...
from django.db import models from django.utils.translation import ugettext_lazy as _ from lfs.catalog.models import Product from lfs.order.models import Order class Topseller(models.Model): """Selected products are in any case among topsellers. """ product = models.ForeignKey(Product, verbose_name=_(u"Produ...
from collections import namedtuple from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed from corehq.apps.change_feed.document_types import GROUP from corehq.apps.groups.models import Group from corehq.elastic import stream_es_query, get_es_new, ES_META from corehq.pillows.mappings.user_mapping import USER_...
class JobCancelled(Exception): "The user has cancelled the job" class JobInProgressError(Exception): "A job is already being performed, you can't perform more than one at the same time." class JobCountError(Exception): "The number of jobs started have exceeded the number of jobs allowed" class Job: """M...
from sympy import symbols, Symbol, sinh, nan, oo, zoo, pi, asinh, acosh, log, sqrt, \ coth, I, cot, E, tanh, tan, cosh, cos, S, sin, Rational, atanh, acoth, \ Integer, O, exp, sech, sec, csch from sympy.utilities.pytest import raises def test_sinh(): x, y = symbols('x,y') k = Symbol('k', integer=True) ...
DEBUG = True TESTING = True SECRET_KEY = 'SECRET_KEY' DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1/git_webhook' CELERY_BROKER_URL = 'redis://:@127.0.0.1:6379/0' CELERY_RESULT_BACKEND = 'redis://:@127.0.0.1:6379/0' SOCKET_MESSAGE_QUEUE = 'redis://:@127.0.0.1:6379/0' GITHUB_CLIENT_ID = '123' GITHUB_CLIENT_SECRET =...
import numpy as np from numpy import array from numpy import float32 bin7 = array([ [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, ...
from sqlalchemy.orm import create_session, relationship, mapper, \ contains_eager, joinedload, subqueryload, subqueryload_all,\ Session, aliased, with_polymorphic from sqlalchemy import Integer, String, ForeignKey from sqlalchemy.engine import default from sqlalchemy.testing import AssertsCompiledSQL, fixtures ...
from flappy.display3d.vertexbuffer3d import VertexBuffer3D, VertexBuffer3DFormat from flappy.display3d.indexbuffer3d import IndexBuffer3D from flappy.display3d.program3d import Program3D from flappy.display3d.texture import Texture from flappy.display3d.scene3d import Scene3D
import socket import os import sys import imp import md5 import sha import codecs import base64 import platform import shutil protocol = imp.load_source('protocol', '../protocol.py') nxDSCLog = imp.load_source('nxDSCLog', '../nxDSCLog.py') LG = nxDSCLog.DSCLog CONFIG_PATH = '/etc/opt/microsoft/omsagent/conf/' SERVER_AD...
from bitfinex.client import Client, TradeClient
from . import tests from . import defaults from .scripting import ( registeredTests, testGlyph, testLayer, testFont, formatGlyphReport, formatLayerReport, formatFontReport )
import unittest from frappe.model.base_document import BaseDocument class TestBaseDocument(unittest.TestCase): def test_docstatus(self): doc = BaseDocument({"docstatus": 0}) self.assertTrue(doc.docstatus.is_draft()) self.assertEquals(doc.docstatus, 0) doc.docstatus = 1 self.assertTrue(doc.docstatus.is_submit...
from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/components/engine/shared_eng_moncal_ifs32.iff" result.attribute_template_id = 8 result.stfName("space/space_item","eng_moncal_ifs32_n") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return res...
"""Utility functions to perform Xcode-style build steps. These functions are executed via gyp-mac-tool when using the Makefile generator. """ import fcntl import fnmatch import glob import json import os import plistlib import re import shutil import string import struct import subprocess import sys import tempfile def...
EXCEPTION_INFO = 'exception_info' MESSAGE = 'message' PAYLOAD = 'payload' _event_handlers = { EXCEPTION_INFO: [], MESSAGE: [], PAYLOAD: [] } def _check_type(typ): if typ not in _event_handlers: raise ValueError('Unknown type: %s. Must be one of %s' % (typ, _event_handlers.keys())) def _add_handl...
def bigdigits(line_splitted): line_splitted = list(line_splitted) string_row_one = '-**----*--***--***---*---****--**--****--**---**--' list_row_one = list(string_row_one) string_row_two = '*--*--**-----*----*-*--*-*----*-------*-*--*-*--*-' list_row_two = list(string_row_two) string_row_three = '*--*---*---**---...
from __future__ import unicode_literals from django.db import migrations, models faq_en = ''' <p> <b>Why statistics on the site does not coincide with the statistics in the game?</b> </p> <p> Algorithms collection statistics IL2 stats differs from statistics in-game. As a consequence of these statistics will not coinci...
import wx from wx.lib.newevent import NewEvent from wx.lib.buttons import GenButton (FontSelectEvent, EVT_FONTSELECT) = NewEvent() class FontSelect(GenButton): def __init__(self, parent, size=(75, 21), value=None): GenButton.__init__(self, parent, wx.ID_ANY, label="Select...", siz...
from sofi.ui import TableRow def test_basic(): assert(str(TableRow()) == "<tr></tr>") def test_text(): assert(str(TableRow("text")) == "<tr>text</tr>") def test_custom_class_ident_style_and_attrs(): assert(str(TableRow("text", cl='abclass', ident='123', style="font-size:0.9em;", attrs={"data-test": 'abc'}))...
import os SITE_ROOT = os.path.dirname(os.path.abspath(__file__)) DEBUG = True # 调试模式 TEMPLATE_DIR = os.path.join(SITE_ROOT, 'templates') # 模板目录 BASE_TEMPLATE = 'base' # 基础模板 URLS = ( '/', 'Index', '(/j)?/shorten', 'Shorten', '/([0-9a-zA-Z]{5,})', 'Expand', '/j/expand', 'Expand', '/.*', 'Index', )...
import csv from meerkat_abacus.config import config def data_types(param_config=config): with open(param_config.config_directory + param_config.country_config["types_file"], "r", encoding='utf-8', errors="replace") as f: DATA_TYPES_DICT = [_dict for _dict in csv.DictReader(f)] ...
class Options: instance = None def __init__(self,options): self.options = options @classmethod def set(cls,options): """Create an Options instance with the provided dictionary of options""" cls.instance = Options(options) @classmethod def inst(cls): """Get...
from __future__ import absolute_import import logging import warnings from pip.basecommand import Command from pip.exceptions import DistributionNotFound from pip.index import PackageFinder from pip.req import InstallRequirement from pip.utils import get_installed_distributions, dist_is_editable from pip.utils.deprecat...
""" homeassistant.components.graphite ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Component that records all events and state changes and feeds the data to a graphite installation. For more details about this component, please refer to the documentation at https://home-assistant.io/components/graphite/ """ import logging import ...
class Solution(object): def findTilt(self, root): """ :type root: TreeNode :rtype: int """ def postOrderTraverse(root, tilt): if not root: return 0, tilt left, tilt = postOrderTraverse(root.left, tilt) right, tilt = postOrde...
""" discovery and running of std-library "unittest" style tests. """ from __future__ import absolute_import, division, print_function import sys import traceback import _pytest._code from _pytest.config import hookimpl from _pytest.outcomes import fail, skip, xfail from _pytest.python import transfer_markers, Class, Mo...
from swgpy.object import * def create(kernel): result = Static() result.template = "object/static/structure/tatooine/shared_planter_hanging_style_01.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
""" Project Bluebox Copyright (C) <2015> <University of Stuttgart> This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details. """ from mcm.Bluebox import app from mcm.Bluebox import configuration app.run( host=configuration.my_bind_host, port=int(con...
import subprocess from genes.mac.traits import only_osx @only_osx def systemsetup(*args): subprocess.call(['systemsetup'] + list(args))
import os import sys import yaml import argparse from code import interact def parse_options(argv): parser = argparse.ArgumentParser(description='Macumba Shell', prog='macumba-shell') parser.add_argument('--v1', action='store_true', dest='v1', help='U...
''' TODO: Init package docs ''' import logging import uuid from grader.models import Grader from grader.utils.config import is_grader_dir logger = logging.getLogger(__name__) help = 'Initialize grader by creating grader.yml' def setup_parser(parser): parser.add_argument('--course-id', default=str(uuid.uuid4()), ...
from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/powerup/weapon/fs_quest_sad/shared_melee_speed_quest.iff" result.attribute_template_id = -1 result.stfName("powerup_n","weapon_melee_speed_quest") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### retu...
from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_sean_trenwell.iff" result.attribute_template_id = 9 result.stfName("npc_name","sean_trenwell") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/attachment/weapon/shared_hutt_medium_weapon1_s02.iff" result.attribute_template_id = 8 result.stfName("item_n","ship_attachment") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
import pytest from bottle import Bottle, debug, request, response from webtest import TestApp from webargs import ValidationError, fields from webargs.bottleparser import BottleParser hello_args = { 'name': fields.Str(missing='World', validate=lambda n: len(n) >= 3), } hello_multiple = { 'name': fields.List(fie...
import socks """SOCKS 4 proxy server class. Copyright (C) 2001 Xavier Lagraula See COPYRIGHT.txt and GPL.txt for copyrights information. Build upon the TCPServer class of the SocketServer module, the Socks4Proxy class is an implementation of the SOCKS protocol, version 4. This server uses one thread per connection req...
from swgpy.object import * def create(kernel): result = Static() result.template = "object/static/structure/general/shared_fountain_generic_style_1.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
""" Copyright (c) 2019 Alex Forencich 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, merge, publish, distribute, ...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "collegeassist.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue i...
"""Support for programmatically generating markup streams from Python code using a very simple syntax. The main entry point to this module is the `tag` object (which is actually an instance of the ``ElementFactory`` class). You should rarely (if ever) need to directly import and use any of the other classes in this mod...
from .utils import PyKEArgumentHelpFormatter import numpy as np from astropy.io import fits as pyfits from matplotlib import pyplot as plt from tqdm import tqdm from . import kepio, kepmsg, kepkey, kepfit, kepstat, kepfunc __all__ = ['kepoutlier'] def kepoutlier(infile, outfile=None, datacol='SAP_FLUX', nsig=3.0, steps...
from headers.BeaEnginePython import * from nose.tools import * class TestSuite: def test(self): # 66 0F 38 3d /r # pmaxsd mm1, mm2/m64 Buffer = bytes.fromhex('660f383d9011223344') myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(hex(myDisasm.infos.Instruction.Op...
import json from django import template from django.conf import settings register = template.Library() from django_iceberg.auth_utils import init_iceberg @register.inclusion_tag('django_iceberg/javascript_sdk.html', takes_context=True) def iceberg_javascript_sdk(context): """ To Finish """ if getattr(se...
from flask import jsonify, session from marshmallow import INCLUDE, fields from marshmallow_enum import EnumField from indico.modules.categories.controllers.base import RHDisplayCategoryBase from indico.modules.events.controllers.base import RHDisplayEventBase from indico.modules.search.base import SearchOptions, Searc...
"""Tests for documenteer.sphinext.mockcoderefs.""" from shutil import rmtree from tempfile import mkdtemp import pytest from sphinx.application import Sphinx import documenteer.sphinxext.mockcoderefs as mockcoderefs try: from unittest.mock import Mock except ImportError: from mock import Mock @pytest.fixture() ...
from utils import load_data, save_data def run(): # load in members, orient by bioguide ID print("Loading current legislators...") current = load_data("legislators-current.yaml") current_bioguide = { } for m in current: if "bioguide" in m["id"]: current_bioguide[m["id"]["bioguide"]] = ...
import shapelibc import dbflibc import sys from xmlwriter import * #AUTO_REMOVED by make from vec import * #AUTO_REMOVED by make def castSpecific(shpobj): """ if given a SHPObject, this will return a more specific version like SHPPointObject depending on the SHPType of the given obje...
u""" Основной скрипт запуска ДЗ. Данный скрипт призван запускать на выполнение домашнее задание #6. """ __author__ = "Elena Sharovar" __date__ = "2014-11-23" from hw6_solution1 import modifier def runner(): u"""Запускает выполнение всех задач""" print "Modifying file..." modifier("data.csv") print "Modi...
from PyQt5.QtCore import pyqtSlot, QThread, pyqtSignal import os from PyQt5.QtWidgets import QFileDialog, QProgressDialog, QMessageBox from PyQt5.QtCore import pyqtSlot, QObject from books.soldiers import processData import route_gui from lxml import etree import multiprocessing import math class XmlImport(QObject): ...
"""GIFImage by Matthew Roe""" import Image import pygame from pygame.locals import * import time class GIFImage(object): def __init__(self, filename): self.filename = filename self.image = Image.open(filename) self.frames = [] self.get_frames() self.cur = 0 self.ptime...
import string __version__ = string.split('$Revision: 1.6 $')[1] __date__ = string.join(string.split('$Date: 2001/11/17 14:12:34 $')[1:3], ' ') __author__ = 'Tarn Weisner Burton <twburton@users.sourceforge.net>' __doc__ = 'http://oss.sgi.com/projects/ogl-sample/registry/SUN/convolution_border_modes.txt' __api_version__ ...
"""Mock HTTPretty. HTTPretty fix related to SSL bug: https://github.com/gabrielfalcao/HTTPretty/issues/242 """ import httpretty import httpretty.core from httpretty import HTTPretty as OriginalHTTPretty try: from requests.packages.urllib3.contrib.pyopenssl import \ inject_into_urllib3, extract_from_urllib3 ...
import struct import os from sys import maxint from enigma import eTimer, eHdmiCEC, eActionMap from config import config, ConfigSelection, ConfigYesNo, ConfigSubsection, ConfigText from Tools.StbHardware import getFPWasTimerWakeup from Tools.Directories import fileExists config.hdmicec = ConfigSubsection() config.hdmic...
from wrappers import * from inspect import getdoc @plugin class Help: @command("list") def list(self, message): """list the loaded plugins""" return message.reply(list(self.bot.plugins.keys()), "loaded plugins: " + ", ".join(self.bot.plugins.keys())) @command("commands") def listcoms(sel...
import imp import inspect import logging import os import shutil import sys import tarfile from xl.nls import gettext as _ from xl import ( common, event, settings, xdg ) logger = logging.getLogger(__name__) class InvalidPluginError(Exception): def __str__(self): return str(self.args[0]) cla...
import code import unittest import os import pcbnew import pdb import tempfile from pcbnew import * class TestBoardClass(unittest.TestCase): def setUp(self): self.pcb = LoadBoard("data/complex_hierarchy.kicad_pcb") self.TITLE="Test Board" self.COMMENT1="For load/save test" self.FILEN...
''' This is the development documentation of zim. B{NOTE:} There is also some generic development documentation in the "HACKING" folder in the source distribution. Please also have a look at that if you want to help with zim development. In this API documentation many of the methods with names starting with C{do_} and ...
from PyQt4.QtCore import Qt, QString from PyQt4.QtGui import QFont, QFontMetrics, QColor, QIcon, QLabel, QWidget, QVBoxLayout from PyQt4.Qsci import QsciScintilla, QsciLexerPython class EditorBase(QsciScintilla): def __init__(self, mainwindow): QsciScintilla.__init__(self, mainwindow) self.mainwindo...
SD_PROTO_VER = 0x02 SD_SHEEP_PROTO_VER = 0x0a SD_EC_MAX_STRIP = 16 SD_MAX_COPIES = SD_EC_MAX_STRIP * 2 - 1 SD_OP_CREATE_AND_WRITE_OBJ = 0x01 SD_OP_READ_OBJ = 0x02 SD_OP_WRITE_OBJ = 0x03 SD_OP_REMOVE_OBJ = 0x04 SD_OP_DISCARD_OBJ = 0x05 SD_OP_NEW_VDI = 0x11 SD_OP_LOCK_VDI = 0x12 SD_OP_RELE...
""" EasyBuild support for SNPyhlo, implemented as an easyblock @authors: Ewan Higgs (HPC-UGent) @authors: Kenneth Hoste (HPC-UGent) """ import os import re import shutil import stat from easybuild.framework.easyblock import EasyBlock from easybuild.tools.build_log import EasyBuildError from easybuild.tools.filetools im...
"""Cursor classes """ import sys import weakref import re import itertools from mysql.connector import constants from mysql.connector import errors from mysql.connector import utils RE_SQL_COMMENT = re.compile("\/\*.*\*\/") RE_SQL_INSERT_VALUES = re.compile( r'VALUES\s*(\(\s*(?:%(?:\(.*\)|)s\s*(?:,|)\s*)+\))', ...
import os.path import string import urllib import duplicity.backend from duplicity.errors import BackendException class GDocsBackend(duplicity.backend.Backend): """Connect to remote store using Google Google Documents List API""" ROOT_FOLDER_ID = 'folder%3Aroot' BACKUP_DOCUMENT_TYPE = 'application/binary' ...
import pytest from cfme.infrastructure import repositories from utils.update import update from utils.wait import TimedOutError, wait_for @pytest.mark.tier(2) @pytest.mark.meta(blockers=[1188427]) def test_repository_crud(soft_assert, random_string, request): repo_name = 'Test Repo {}'.format(random_string) rep...
import datetime import json import PyQt4 from PyQt4.QtGui import * from PyQt4.QtCore import * import PyQt4.QtCore as QtCore from electrum_xvg import transaction from electrum_xvg.bitcoin import base_encode from electrum_xvg.i18n import _ from electrum_xvg.plugins import run_hook from util import * dialogs = [] # Other...
""" Support for plotting vector fields. Presently this contains Quiver and Barb. Quiver plots an arrow in the direction of the vector, with the size of the arrow related to the magnitude of the vector. Barbs are like quiver in that they point along a vector, but the magnitude of the vector is given schematically by the...
""" Application ... """ from queue import Empty import multiprocessing as mp import datetime as dt import time import csv from tools.tools import now, fromISO, existFile from tools.ssa import * from rdflib import Variable, URIRef, Literal from lxml import etree # http://lxml.de/index.html#documentation from lib.bgp im...
'''euclid graphics maths module Documentation and tests are included in the file "euclid.txt", or online at http://code.google.com/p/pyeuclid ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' __revision__ = '$Revision$' import math import operator import types _use_slots = True _enable_swizzle_set = False if ...
"""Sets up the logger.""" import logging import os logger = logging.getLogger('dictonator') GEDIT_PLUGIN_PATH = os.path.dirname(os.path.abspath(__file__)) if not os.path.exists(GEDIT_PLUGIN_PATH + '/.logs'): os.makedirs(GEDIT_PLUGIN_PATH + '/.logs') LOG_DIR_PATH = GEDIT_PLUGIN_PATH + "/.logs/" def setup_logger(): ...
""" worldcat/request/xid.py -- Request objects for xID APIs xID APIs as of this writing include xISBN, xISSN, and xOCLCNUM. 'Alternate request formats' (such as OpenURL and unAPI) have not been implemented. """ from worldcat.exceptions import EmptyRecordNumberError from worldcat.request import WorldCatReque...
__author__ = "Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel" __license__ = "GPLv3" __maintainer__ = "Steffen Vogel" __email__ = "post@steffenvogel.de" """ This file is part of transWhat transWhat is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Lice...
class Solution(object): def longestPalindrome(self, s): max_len = 0 max_str = '' if len(s) <= 2: return s for i, ch in enumerate(s): delta = 1 count = 0 # center is ch while (i - delta) >= 0 and (i + delta) < len(s): ...
import logging import os import math from collections import defaultdict from gensim import corpora from .Matcher.matcher import Matcher class Evaluator(Matcher): """ 讀入一串推文串列,計算出當中可靠度最高的推文 """ def __init__(self,segLib="Taiba"): #FIXME 若「線上版本」受記憶體容量限制,需考慮更換為 jieba! super().__init__(segLi...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Removing unique constraint on 'Customer', fields ['company_name', 'contact_name', 'contact_mail'] db.delete_unique('readings_customer...
import sys import imp import os import os.path import zipfile from cStringIO import StringIO import math from random import randint import numpy from PIL import Image, ImageEnhance, ImageOps, ImageDraw import logging import functools import util from c_overviewer import alpha_over class TextureException(Exception): ...
""" Plotting Service generates graphs according to the client specifications and data """ __RCSID__ = "$Id$" import os import hashlib from types import DictType, ListType from DIRAC import S_OK, S_ERROR, rootPath, gConfig, gLogger, gMonitor from DIRAC.ConfigurationSystem.Client import PathFinder from DIRAC.Core.DIS...
from data import Access, Entry, EntryError from Queue import Queue class EntryQueue(Queue): def __init__(self, transverse, maxsize=0): self.reddit = transverse.reddit self.events = transverse.events Queue.__init__(self, maxsize) def _init(self, maxsize): Queue._init(self, maxsize...
from config import Prefix from sigma.core.blacklist import check_black async def custom_command_detection(ev, message, args): if message.guild: if message.content.startswith(Prefix): cmd = message.content[len(Prefix):].lower() if cmd not in ev.bot.plugin_manager.commands: ...
"""This sample demonstrates some very simple lightning effects.""" import math import d3d11 import d3d11x from d3d11c import * def heightCallback(x, z, byteIndex, data): return data[byteIndex] * 0.03 class SampleLights(d3d11x.Frame): def onCreate(self): #Heightmap. #self.heightmap = d3d11x.Heigh...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: aci_switch_leaf_selector short_description: Add a leaf Selecto...
import time import numpy import os import pmt from gnuradio import gr, gr_unittest from gnuradio import blocks class test_multiply_matrix_ff (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () self.multiplier = None def tearDown (self): self.tb = None self.multipl...
../../../../../../../share/pyshared/orca/scripts/apps/evolution/formatting.py
"""Estimating the spectral contribution to inspiral range We have seen how the binary neutron star (BNS) inspiral range of a gravitational-wave detector can be measured directly from the strain readout. In this example, we will estimate the average spectral contribution to BNS range from the strain record surrounding G...
from django.utils.translation import ugettext_lazy as _ class MultiFieldsValidator(object): fields = () error_messages = { 'invalid' : _(u'Value is not valid.') } def raise_error(self, form, error="invalid"): for field in self.fields: form._errors[field] = form.error_class([s...
from pylab import * from matplotlib.ticker import AutoMinorLocator prec = loadtxt("precisionSph.dat") fig1 = figure(figsize=(7,3)) ax1 = fig1.add_subplot(111) ax1.plot(prec[:,0],prec[:,1], 'b-') ax1.plot(prec[:,0],prec[:,2], 'r') ax1.plot(prec[:,0],prec[:,3], 'k') minorLocator = AutoMinorLocator() ax1.xaxis.set_minor...
from abjad import * def test_pitchtools_PitchClass_is_pitch_class_number_01(): assert pitchtools.PitchClass.is_pitch_class_number(0) assert pitchtools.PitchClass.is_pitch_class_number(0.5) assert pitchtools.PitchClass.is_pitch_class_number(11) assert pitchtools.PitchClass.is_pitch_class_number(11.5) def...
import logging import os import signal import time import re import hostapd import wpaspy import utils from wpasupplicant import WpaSupplicant import fst_test_common logger = logging.getLogger() def parse_fst_iface_event(ev): """Parses FST iface event that comes as a string, e.g. "<3>FST-EVENT-IFACE attached if...
from django.contrib import admin from . import models
import sys import numpy import scipy import json import itertools import random import os from sys import stderr, exit, argv from scipy.sparse.linalg import spsolve from sklearn.metrics.pairwise import euclidean_distances from nltk.stem import SnowballStemmer def load_data_sparse(prefix) : return scipy.sparse.csr_m...
""" Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 2 of the License, or (at your option) any lat...
import base64 import os import io import six from tempfile import _TemporaryFileWrapper from pretty_bad_protocol._util import _STREAMLIKE_TYPES from cryptography.exceptions import AlreadyFinalized from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers.algorithms import AES ...
'''This file is part of the privacyidea service It is used for importing SafeNet (former Aladdin) XML files, that hold the OTP secrets for eToken PASS. ''' import defusedxml.ElementTree as etree import re import binascii import base64 from privacyidea.lib.utils import modhex_decode from privacyidea.lib.utils import mod...
from openerp.osv import orm, fields class asset_assign_category(orm.TransientModel): _name = 'asset.assign.category' _description = 'Assign category to a new asset product' _columns = { 'category_id': fields.many2one('asset.category', 'Asset Category', required=False), } def assign_category(...
from ..utils import * class AT_019: "Dreadsteed" deathrattle = Summon(CONTROLLER, "AT_019") class AT_021: "Tiny Knight of Evil" events = Discard(FRIENDLY).on(Buff(SELF, "AT_021e")) AT_021e = buff(+1, +1) class AT_023: "Void Crusher" inspire = Destroy(RANDOM_ENEMY_MINION | RANDOM_FRIENDLY_MINION) class AT_026: "W...