prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
def action_vakai_load_more(context, action, parent_entity_bundle, last_id, parent_entity_id, **args): try: parent_entity_type = 'Vakai' parent_entity_id = int(parent_entity_id) last_id = int(last_id) output = Object() db = IN.db connection = db.connection # TODO: paging # get total ...
ity_bundle)s AND field_vakai_parent.value = %(parent_id)s AND vakai.id < %(last_id)s AND vakai.status != 0 ORDER BY vakai.weight LIMIT %(limit)s ''', { 'parent_entity_bundle' : parent_entity_bundle, 'parent_id' : parent_entity_id, 'last_id' : last_id, 'limit' : limit...
r: # reverse reference ids.append(row['entity_id']) last_id = ids[-1] # last id vakais = IN.entitier.load_multiple('Vakai', ids) for id, vakai in vakais.items(): obj = ThemeArgs(vakai, {'view_mode' : 'adminlist'}) output.add(obj) remaining = total - limit if remaining > 0 a...
Error("Path already registered to an endpoint") self._endpoints[path] = callback def register_mux_endpoint(self, path, key, value, callback): prev = self._mux_endpoints.get(path) if prev is None: self.register_endpoint(path, self._handle_mux) self._mux_endpoints[path...
r: def __init__(self, printer): self.printer = printer self.clients = {} self.pending_queries = [] self.query_timer = None self.last_query = {} # Register webhooks webhooks = printer.lookup_object('webhooks') webhooks.register_endpoint("objects/list", ...
le_query) webhooks.register_endpoint("objects/subscribe", self._handle_subscribe) def _handle_list(self, web_request): objects = [n for n, o in self.printer.lookup_objects() if hasattr(o, 'get_status')] web_request.send({'objects': objects}) def _do_query(self, eventti...
# -*- coding: utf-8 -*- import pytest from django.core.urlresolvers import reverse pytestmark = pytest.mark.django_db global_footer_links = [ 'About', 'Developers', 'Privacy', 'Report an issue', ] def assert_title_and_links_on_page(
browser, url, title, links_text): browser.visit(url) assert title in browser.title for link_text in links_text: assert browser.find_link_by_text(link_text) def test_homepage(browser): url = reverse('pages:home') assert_title_and_links_on_page(browser, url, "FossEvents", global_footer_links...
l_footer_links) def test_privacy_page(browser): url = reverse('pages:privacy') assert_title_and_links_on_page(browser, url, "Privacy", global_footer_links)
import werkzeug from openerp import http, SUPERUSER_ID from openerp.http import request class MassMailController(http.Controller): @http.route('/mail/track/<int:mail_id>/blank.gif', type='http', auth='none') def track_mail_open(self, mail_id, **post): """ Email trac
king. """ mail_mail_stats = request.registry.get('mail.mail.statistics') mail_mail_stats.set_opened(request.cr, SUPERUSER_ID, mail_mail_ids=[mail_id]) response = werkzeug.wrappers.Response() response.mimetype = 'image/gif' res
ponse.data = 'R0lGODlhAQABAIAAANvf7wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='.decode('base64') return response @http.route(['/mail/mailing/<int:mailing_id>/unsubscribe'], type='http', auth='none') def mailing(self, mailing_id, email=None, res_id=None, **post): cr, uid, context = request.cr, reque...
on't need to add two spaces at the end of a line. """ self.linebreak = re.compile(r'^ *\n(?!\s*$)') self.text = re.compile( r'^[\s\S]+?(?=[\\<!\[_*`~]|https?://| *\n|$)' ) class InlineLexer(object): """Inline level lexer for inline grammars.""" default_feat...
ent: content of current table row. """ return '<tr>\n%s</tr>\n' % content def table_cell(self, content, **flags): """Rendering a table cell. Like ``<th>`` ``<td>``. :param content: content of current table cell. :param
header: whether this is header or not. :param align: align of current table cell. """ if flags['header']: tag = 'th' else: tag = 'td' align = flags['align'] if not align: return '<%s>%s</%s>\n' % (tag, content, tag) return '<%s ...
# -*- coding: utf-8 -*- # # zambiaureport documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values ...
'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of sourc
e files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'zambiaureport' copyright = u'2014, Andre Lesa' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in variou...
from .binary_searc
h_tree import BinarySe
archTree
# -*- coding: utf-8 -* from distutils.core import setup import os PACKA
GE_NAME = "railgun" def recurse(d): ret = [] for f in os.listdir(d): if f.startswith("."): continue df = os.path.join(d, f) if os.path.isfile(df): ret.append(df) elif f != "bu
ild": ret += recurse(df) return ret def structure(fs): s = {} for f in fs: d = os.path.dirname(f) if not d.startswith("meta/"): continue d = PACKAGE_NAME + d[4:] v = s.get(d, []) s[d] = v v.append(f) return s.items() setup(name='docke...
rn hasattr(os, 'getuid') and os.getuid() == 0 def determine_num_of_cpus(): ''' Number of virtual or physical CPUs on this system ''' # Python 2.6+ try: import multiprocessing return multiprocessing.cpu_count() except (ImportError, NotImplementedError): return 1 def to_winpat...
DistroVersion.REDHAT_6 elif d[1].startswith('7.'): distro_version = DistroVersion.REDHAT_7
else: # FIXME Fill this raise FatalError("Distribution '%s' not supported" % str(d)) elif d[0].strip() in ['openSUSE']: distro = Distro.SUSE if d[1] == '12.1': distro_version = DistroVersion.OPENSUSE_12_1 elif d[1] == '...
from __future__ import unicode_literals from django.test import TestCase from accelerator.tests.factories import ProgramPartnerTypeFactory
class TestProgramPartnerType(TestCase): def test_str(self): program_partner_type = ProgramPartnerTypeFactory() assert program_partner_
type.partner_type in str(program_partner_type) assert program_partner_type.program.name in str(program_partner_type)
ors frameRotor = Frame(frame, background='white') var4 = StringVar() spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]", "rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]", "rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]"), textvariable=var4...
4) var5.set("rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]") spin
box.grid(row=1, column=1) var6 = StringVar() spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]", "rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]", "rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]"), textvariable=var6, width=44) var6.set("ro...
# encoding: utf-8 from yast import import_module import_module('U
I') from yast import * class Frame1Client: def main(self): UI.OpenDialog( VBox( Frame("Hey! I&mportant!", Label("Hello, World!")), PushBu
tton("&OK") ) ) UI.UserInput() UI.CloseDialog() Frame1Client().main()
import django_filters from django_filters import r
est_framework as filters from django_rv_apps.apps.believe_his_prophets.models.book import Book from django_rv_apps.apps.believe_his_prophets.models.bible_read import BibleRead from django_rv_apps.apps.believe_his_prophets.models.te
stament import Testament class BookFilter(django_filters.FilterSet): testament = filters.ModelChoiceFilter( queryset=Testament.objects.all()) class Meta: model = Book fields = ('id', 'testament', 'book_order')
s required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License....
tes admin api.""" from webob import exc from nova.api.openstack.compute.contrib import aggregates from nova import context fr
om nova import exception from nova import test from nova.tests.api.openstack import fakes from nova.tests import matchers AGGREGATE_LIST = [ {"name": "aggregate1", "id": "1", "availability_zone": "nova1"}, {"name": "aggregate2", "id": "2", "availability_zone": "nova1"}, {"name": "aggregate3", "...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016 CERN. # # Invenio 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 later version. # # Invenio is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY
; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite ...
e given filename and retrieve registry settings for me""" return self.inventory.loadConfiguration(filename) def updateConfiguration(self, registry): """load the user setting in <registry> into my inventory""" return self.inventory.updateConfiguration(registry) def applyConfiguration(...
s) print "For more information:" print " --help-properties: prints details about user settable properties" print " --help-components: prints details about user settable facilities and components" return def showCurator(self): """print a description of
the manager of my persistence store""" self.inventory.dumpCurator() return # default implementations of the various factories def createRegistry(self, name=None): """create a registry instance to store my configuration""" if name is None: name = self.name ...
import synapse.tests.utils as s_t_utils class UsGovTest(s_t_utils.SynTest): async def test_models_usgov_cage(self): async with self.getTestCore() as core: input_props = { 'street': '123 Main St', 'city': 'Smallville', 'state': 'Kansas', ...
'phone0': '17035551212', 'phone1': '17035551213', 'name0': 'kent labs', } formname = 'gov:us:cage' valu = '7qe71' expected_ndef = (formname, va
lu) async with await core.snap() as snap: n0 = await snap.addNode(formname, valu.upper(), input_props) self.eq(n0.ndef, expected_ndef) for prop, valu in expected_props.items(): self.eq(n0.get(prop), valu)
self, message): console = {} console['type'] = 'console' console['identifier'] = self.identifier console['message'] = message self.write_message(json.dumps(console)) def sendPath(self, message): console = {} console['type'] = 'path' console[...
wrm = write_message(m)
sock.send(wrm) def checkPlan(self): if not self.planner.is_alive(): print 'DLV ended.' try: self.planner.readresult() global temporaryresult temporaryresult = self.planner.getresult() if self.currentproble...
xt displayed before user input, cannot be edited by user (this can be changed later via the prefix property) :param font: the font to use :param pt_size: the point size of the text to draw :param color: color of the font for this widget :param aspect: constrain the widget size to a specified aspect ratio :par...
ght = Frame(self, size=self.frame.size, border=0, options=BGUI_NO_FOCUS | BGUI_CENTERY | BGUI_NO_NORMALIZE) self.cursor = Frame(self, size=[1, 1], border=0, options=BGUI_NO_FOCUS | BGUI_CENTERY | BGUI_NO_NORMALIZE) self.label = Label(self, text=text, font=font, pt_size=pt_size, sub_theme=self.theme['LabelSubTheme']...
I_NO_FOCUS | BGUI_DEFAULT) #Color and setting initialization self.colormode = 0 theme = self.theme self.colors["text"] = [None, None] self.colors["text"][0] = theme['InactiveTextColor'] self.colors["text"][1] = theme['TextColor'] self.colors["frame"] = [None, None] self.colors["frame"][0] = theme['I...
} # Athena query statement length limit MAX_QUERY_LENGTH = 262144 def add_partition_statements(partitions, bucket, table_name): """Generate ALTER TABLE commands from existing partitions. It wil yield Athena statement string(s), the length of each string should be less than Athena query statement length l...
nvelope_keys = configuration_options.get('envelope_keys')
if envelope_keys: sanitized_envelope_key_schema = FirehoseClient.sanitize_keys(envelope_keys) # Note: this key is wrapped in backticks to be Hive compliant athena_schema['streamalert:envelope_keys'] = logs_schema_to_athena_schema( sanitized_envelope_key_schema, Fals...
from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import fq_name from ansible.module_utils.network.f5.common import f5_argument_spec from ansible.module_utils.network.f5.comm...
d) def _update_changed_options(self): diff = Difference(self.want, self.have) updatables = Parameters.updatables changed = dict() for k in updatables: change = diff.c
ompare(k) if change is None: continue else: if isinstance(change, dict): changed.update(change) else: changed[k] = change if changed: self.changes = UsableChanges(params=changed) ...
import numpy as np from ..filters import gaussian def binary_blobs(length=512, blob_size_fraction=0.1, n_dim=2, volume_fraction=0.5, seed=None): """ Generate synthetic binary image with several rounded blob-like objects. Parameters ---------- length : int, optional Linear...
Output binary image Examples -------- >>> from skimage import data >>> data.binary_blobs(length=5, blob_size_fraction=0.2, seed=1) array([[ True, False, True, True, True], [ True, T
rue, True, False, True], [False, True, False, True, True], [ True, False, False, True, True], [ True, False, False, False, True]], dtype=bool) >>> blobs = data.binary_blobs(length=256, blob_size_fraction=0.1) >>> # Finer structures >>> blobs = data.binary_blobs(lengt...
reate = False ## Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # Default: False # c.Bas...
inalIPythonApp.ignore_cwd = False ## Cla
ss to use to instantiate the TerminalInteractiveShell object. Useful for # custom Frontends # Default: 'IPython.terminal.interactiveshell.TerminalInteractiveShell' # c.TerminalIPythonApp.interactive_shell_class = 'IPython.terminal.interactiveshell.TerminalInteractiveShell' ## # See also: BaseIPythonApplication.ipyt...
"""SCons.Tool.zip Tool-specific initialization for zip. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCon...
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/zip.py 2014/01/04 01:12:18 root" import os.path import SCons.Builder impor...
ile.ZIP_DEFLATED def zip(target, source, env): compression = env.get('ZIPCOMPRESSION', 0) zf = zipfile.ZipFile(str(target[0]), 'w', compression) for s in source: if s.isdir(): for dirpath, dirnames, filenames in os.walk(str(s)): for fname in fi...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # (C) XXN, 2017 # from __future__ import absolute_import, unicode_literals import os, re, sys, time import pywikibot def main(): site = pywikibot.Site('wikidata', 'wikidata') repo = site.data_repository() mylist = \ [ u"Q3001778", ...
'pt-br', 'ro', 'ru', 'sco', 'sh', 'sk', 'sl', 'sr', 'sv', 'tr', 'uk', ] for q in mylist[0:]: item = pywikibot.ItemPage(repo, q) item.get() if 'P577' in item.claims and item.claims['P31'][0].getTarget().title() == 'Q7889': try: myclaim = item.get()['claims']['P...
recision'] >= 9: year = str(int(Text[8:12])) for targetlang in targetlangs: translations = { 'bg': 'видеоигра от ~YEAR~ година', 'bs': 'videoigra', 'ca': 'videojoc de ~YEAR...
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
script>""" % MATHJAX_URI) footer = tags.html_string_to_element_tree('') return (h
eader, footer) def get_icon_url(self): return RESOURCES_URI + '/math.png' def get_schema(self, unused_handler): reg = schema_fields.FieldRegistry(MathTag.name()) reg.add_property( schema_fields.SchemaField( 'input_type', 'Type', 'string', i18n=False, ...
""" ICS Ops Common Library """ import os from os.path import dirname from os.path import realpath from os.path import join as pathjoin import boto __version__ = "0.0.3.3" __release__ = "alpha" CONFIG = "opslib.ini" LOG_NAME = "opslib" AWS_ACCESS_KEY_NAME = "aws_access_key_id" AWS_SECRET_KEY_NAME = "aws_secret_acces...
pwdpath = dirname(realpath(__file__)) filepath = pathjoin(pwdpath, CONFIG) if enable_boto: # Initialize credentials for boto from boto.pyami.config import Config boto.config = Config(filepath) access_key = boto.config.get('Credentials', AWS_ACCESS_KEY_NAME, None) ...
ick when the value is empty if not access_key or not secret_key: boto.config.remove_section('Credentials') if enable_botocore: # Initialize credentials for botocore import botocore.credentials if access_key and secret_key: def get_credentials(session, metada...
logger.error(l) logger.error(ptraj.dtype) logger.error(l.dtype) d = metric.one_to_all(ptraj, pmedoids, l) argmin = np.argmin(d) new_assignments[l] = new_medoids[argmin] new_distances[l] = d[argmin] new_...
assignments = initial_assignments distance_to_current = initial_distance medoids = initial_medoids pgens = ptraj[medoids] k = len(initial_medoids) obj_func = p_norm(distance_to_current, p=norm_exponent) max_norm = p_norm(distance_to_current, p='max') if not np.all(np.unique(medo
ids) == np.sort(medoids)): raise ValueError('Initial medoids must be distinct') if not np.all(np.unique(assignments) == sorted(medoids)): raise ValueError('Initial assignments dont match initial medoids') for iteration in xrange(num_iters): for medoid_i in xrange(k): if not ...
# Copyright 2014
Cloudbase Solutions Srl # #
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 writing, software # distr...
"""timezone
at metavj level Revision ID: 224621d9edde Revises: 14346346596e Create Date: 2015-12-21 16:52:30.275508 """ # revision identifiers, used by Alembic. revision = '224621d9edde' down_revision = '5a590ae95255' from alembic import op import sqlalchemy as sa import geoalchemy2 as ga def upgrade(): op.create_table(...
lumn('name', sa.TEXT(), nullable=False), sa.PrimaryKeyConstraint('id'), schema='navitia' ) op.create_table('tz_dst', sa.Column('id', sa.BIGINT(), nullable=False), sa.Column('tz_id', sa.BIGINT(), nullable=False), sa.Column('beginning_date', sa.DATE(), nullable=False), sa.Column('end_date'...
__author__ = 'mk' import matplotlib.pyplot as plt import sys import math import numpy as np da
taDir = sys.argv[1] resDir = sys.argv[2] plt.figure(figsize=(8,4)) algLabel=['naive','cou','zigzag','pingpong','MK','LL'] for i in range(0,6,1): filePath = dataDir + str(i) + '_overhead.dat' file = open(filePath) x = [] y = [] for eachLine in file.readlines(): xStr,yStr = eachLine.split(...
) file.close() plt.plot(x,y,label=algLabel[i],linewidth=1) plt.xlabel("Data Size") plt.ylabel("Overhead") plt.title("Overhead Per Checkpoint") plt.legend() plt.savefig(resDir + "OverheadPerCheckpoint.pdf")
fro
m django.utils.translation import ugettext_lazy as _ # Legend Position def get_legend_class(position): return 'legend-' + str(position) class LEGEND_POSITIONS: BOTTOM = _('bottom') TOP = _('top') LEFT = _('left') RIGHT = _('right') get_choices = ((get_legend_class(BOTTOM), BOTTOM), ...
t_legend_class(LEFT), LEFT), (get_legend_class(RIGHT), RIGHT),) def get_chart_position_class(position): return 'chart-' + str(position) class CHART_POSITIONS: CENTER = _('center') LEFT = _('left') RIGHT = _('right') get_choices = ((get_chart_position_class(CENTER), CENTER), ...
import asyncio from collections import OrderedDict from functools import partial import logging from quamash import QtGui, QtCore from pyqtgraph import dockarea from pyqtgraph import LayoutWidget from artiq.protocols.sync_struct import Subscriber from artiq.tools import short_format from artiq.gui.tools import DictSy...
ues(): display.update_data(self.table_model.backing_store) return if mod["path"]: source = mod["path"][0] elif mod["action"] == "setitem": source = mod["key"] else: return for dis
play in self.displays.values(): if source in display.data_sources(): self.update_display_data(display) def create_dialog(self, ty): dlg_class = display_types[ty][0] dlg = dlg_class(self.dialog_parent, None, dict(), sorted(self.table_model.backing_store.keys()...
#!/usr/bin/env python # Load common imports and system envs to build the core object import sys, os # Load the Environment: os.environ["ENV_DEPLOYMENT_TYPE"] = "JustRedis" from src.common.inits_for_python import * ##################################################################### # # Start Arg Processing: # act...
"DSName" : str(ds_name), #
Dataset name for pulling out of the cache "S3Loc" : str(s3_loc), # S3 location to store the model file "DeleteAfter" : False, # Optional delete after upload "SaveDir" : data_dir, # Optional dir to save the model file - ...
from PLC.Faults import * from PLC.Method import Method from PLC.Parameter import Parameter, Mixed from PLC.NetworkMethods import NetworkMethod, NetworkMethods from PLC.Auth import Auth class AddNetworkMethod(Method): """ Adds a new network method. Ret
urns 1 if successful, faults otherwise. """ roles = ['admin'] accepts = [ Auth(), NetworkMethod.fields['method'] ] returns = Parameter(int, '1 if successful') def call(self, auth,
name): network_method = NetworkMethod(self.api) network_method['method'] = name network_method.sync(insert = True) return 1
#!/usr/bin/env python3 # Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module 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 ...
f create_widgets(self): self.wordWrapLabel = ttk.Label(self, text="Wrap:") self.wordWrapCombobox = ttk.Combobox(self, state="readonly", values=["None", "Character", "Word"], textvariable=self.__wordWrap, width=10) self.blockCursorCheckbutton = ttk.Checkbutton(self...
.lineSpacingLabel = ttk.Label(self, text="Line Spacing:") self.lineSpacingSpinbox = tk.Spinbox(self, from_=0, to=32, width=3, validate="all", justify=tk.RIGHT, textvariable=self.__lineSpacing) self.lineSpacingSpinbox.config(validatecommand=( self.lineSpaci...
# Copyright 2014 NEC Corporation. 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 ...
vor(flavor_id) self.admin_flavors_client.wait_for_resource_deletion(flavor_id) except exceptions.NotFound: pass @decorators.idempotent_id('33f1fec3-ba18-4470-8e4e-1d888e7c3593') @testtools.skipU
nless(CONF.compute_feature_enabled.resize, 'Resize not available.') def test_resize_server_revert_deleted_flavor(self): """Test reverting resized server with original flavor deleted Tests that we can revert the resize on an instance whose original flavor has been d...
# This module should be imported from REPL, not run from command line. import socket import uos import network import uwebsocket import websocket_helper import _webrepl listen_s = None client_s = None def setup_conn(por
t, accept_handler): global listen_s listen_s = socket.socket() listen_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ai = socket.getaddrinfo("0.0.0.0", port) addr = ai[0][4] listen_s.bind(addr) listen_s.listen(1) if accept_hand
ler: listen_s.setsockopt(socket.SOL_SOCKET, 20, accept_handler) for i in (network.AP_IF, network.STA_IF): iface = network.WLAN(i) if iface.active(): print("WebREPL daemon started on ws://%s:%d" % (iface.ifconfig()[0], port)) return listen_s def accept_conn(listen_sock): ...
from .g
ame
import Board for i in range(10): Board.all() print(i)
identifiers from PyQt4.QtGui import QPushButton try: from sh import inxi except: print(" 'inxi' not found, install it to get this info") try: from sh import mhwd except: print(" 'mhwd' not found, this is not Manjaro?") try: from sh import hwinfo except: print(" 'hwinfo' not found") try: from...
f.write(str(inxi('-Fxxxzc0'))) except: " 'inxi' not found, install it to get this info" f.write('\n') if self.checks[1]: print("Getting info about installed graphical driver") f.write(HEADER.format("Installed drivers", "Shows which graphic...
print(" 'mhwd' not found, this is not Manjaro?") f.write('\n') if self.checks[2]: print("Getting list of all drivers supported on detected gpu's") f.write(HEADER.format("Available drivers", "list of all drivers supported on detected gpu's")) try: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_browserstep ---------------------------------- Tests for `browserstep` module. """ import sys import
unittest from browserstep import browserstep class TestBrowserstep(unittest.TestCase): def setUp(self): pass def tearDown(se
lf): pass def test_000_something(self): pass if __name__ == '__main__': sys.exit(unittest.main())
assert z.is_even is True assert z.is_odd is False assert z.is_finite is True assert z.is_infinite is False assert z.is_comparable is True assert z.is_prime is False assert z.is_composite is False assert z.is_number is True def test_one(): z = Integer(1) assert z.is_commutative...
onpositive is False assert r.is_positive is True assert r.is_negative is False assert r.is_nonnegative is True r
= Rational(5, 4) assert r.is_negative is False assert r.is_positive is True assert r.is_nonpositive is False assert r.is_nonnegative is True r = Rational(5, 3) assert r.is_nonnegative is True assert r.is_positive is True assert r.is_negative is False assert r.is_nonpositive is False ...
recording = '''jtfxgqec zxoeuddn anlfufma dxuuyxkg ttnewhlw sjoyeiry rgfwwdhw qymxsllk forftdvy rzmnmewh hogawihi mtsyexba mrjzqqfk ypmkexpg pjuyopgv rtqquvaj evubmlrq bqlrtuce ndidnbps vqukosam mzdyfkcd rrbwdimb uhnvxgly aaimxpcv acxvinqj muaeikzy lhzbosjd fflqqiit unfhzfrs gmwoyvob cculubmy zqbugcwa ijouicwt bildjjww...
gvvaibqu lwjotuil srflotab ibnblmjm kvcsdivb wqrpzmvr gcmqdezs vrizdyfo vtqnsjbf jwocjmvb fjkiiowl ctjhmmrq pcckqfki wqolxgfg gbsdyrbc giqmfqwb fodfpvyl nxdzwvzz hpnatltw adjjyhjd aoguhvmv yyeanoir baojaygs ovkebbjb pmykvfex zeooykoa uuozuxjb kxxvbh
br jxbchjlr qhiwdonk dnvfwwfh kjfrlslh wionbrdf qgkjarob kwplsxso txgelygh vlmziqwf wbetqqkp qfkocear wrvonhyr sbiqrcri lnwzitce bctyrwph kallfwzc zfqwanet bevnljjr kwqsktan gjviqwlu zflsnpig wzaufqvr uvxhutav diejbica ojciaexn zyjoxrwi djkodeiz gsinkcqk jkonssuq eychyabp fkcogwnr kkioyrnn inqxlztu cqnbxxks ipwmpdmm mo...
ension; ``in_parts=(PartitionSpec(2,2), PartitionSpec(4,1), None)`` means the first argument should be partitioned over four devices by splitting both of its dimensions in half, the second argument should be partitioned over the four devices across the first dimension, and the third argument is ...
out) return wrapped def _sharding_constraint_impl(x, partitions): # TODO(skye): can we also prevent this from being called in other # non-sharded_jit contexts? (e.g. pmap, control flow) raise NotImplementedError( "with_sharding_constraint() should only be called inside sharded_jit()") def _sharding_co...
set_sharding(ctx.builder, x_node, partitions)] sharding_constraint_p = core.Primitive("sharding_constraint") sharding_constraint_p.def_impl(_sharding_constraint_impl) sharding_constraint_p.def_abstract_eval(lambda x, partitions: x) ad.deflinear2(sharding_constraint_p, lambda ct, _, partitions: (with_shar...
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ cl
ass ContactFormConfig(AppConfig): """The default AppConfig for admin which do
es autodiscovery.""" name = 'django_contact' verbose_name = _("Contact")
request, timeout=timeout, metadata=effective_metadata, credentials=_credentials(protocol_options)) except grpc.RpcError as rpc_error_call: raise _abortion_error(rpc_error_call) def _future_unary_unary(channel, group, method, timeout, protocol_opt...
data=None, protocol_options=None): return _unary_stream( self._channel, self._group, self._method, timeout, protocol_options, metadata, self._metadata_transformer, request, self._request_serializer, self._response_deserializer) def event(self, request, ...
metadata=None, protocol_options=None): raise NotImplementedError() class _StreamUnaryMultiCallable(face.StreamUnaryMultiCallable): def __init__(self, channel, group, method, metadata_transformer, request_serializer, response_deserializer): self._channel ...
import datetime class Historico: def __init__(self): self.data_abertura = datetime.datetime.to
day() self.transacoes = [] def imprime(self): print('data abertura: {}'.format(self.data_abertura)) print('transações: ') for t in self.transacoes: print('-', t) class Cliente: def __init__(self, nome, sobrenome, cpf): self.nome = no...
int('inicializando uma conta') self._numero = numero self._titular = cliente self._saldo = saldo self._limite = limite self._historico = Historico() def deposita(self, valor): self._saldo += valor self._historico.transacoes.append('depósito de {}'.for...
''' Created on 03.05.2015 @author: vvladych ''' from gi.repository import Gtk from forecastmgmt.model.organisation import Organisation from masterdata_abstract_window import AbstractAddMask class OrganisationAddMask(AbstractAddMask): def __init__(self, main_window, reset_callback): super(OrganisationAd...
f self.current_object!=None: self.uuid_text_entry.set_text(self.current_object.uuid) self.common_name_text_entry.set_text(self.current_object.common_name) else: self.uuid_text_entry.set_text("")
self.common_name_text_entry.set_text("") def create_object_from_mask(self): common_name = self.common_name_text_entry.get_text() if common_name is None: self.show_error_dialog("common name cannot be null") return organis...
import base64 import cPickle as pickle from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.hashcompat import md5_constructor class SessionManager(models.Manager): def encode(self, session_dict): """ Returns the gi...
e() # Clear sessions with no data. return s class Session(models.Model): """ Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and re...
ID -- not the data itself. The Django sessions framework is entirely cookie-based. It does not fall back to putting session IDs in URLs. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the "Referer" header. F...
ort sys import tempfile import datetime from xml.etree import ElementTree as etree from convert import read_messages, read_calls import yaffs def read_chunk(fd, size): s = fd.read(size) if len(s) > 0 and len(s) != size: raise IOError("Broken image file") return s def read_segment(fd): chunk_d...
me =
= "": continue if new_filename != "": filename = new_filename try: os.stat(filename) ans = raw_input("Warning: %s already exists, overwrite (y/n)? " % filename) if ans.lower().startswith("y"): break except OSError: ...
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2015, Continuum Analytics, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------...
self, topic): clientids = self.topic_clientid_map.get(topic) for clientid in clientids: self.clientid_topic_map.remove_val(clientid, topic) def subscribe_socket(self, socket, topic, clientid=None): if clientid is None : clientid = str(
uuid.uuid4()) self.subscribe(clientid, topic) self.add_socket(socket, clientid) def can_subscribe(self, clientid, topic): #auth goes here return True def register_auth(self, authtype, func): self.auth_functions[authtype] = func def auth(self, authtoken, topic): ...
coder_rnn_dropout_inputs = args.rnn_dropout_inputs _, decoder_rnn_dropout_states = args.rnn_dropout_states _, decoder_rnn_dropout_recurrent = args.rnn_dropout_recurrent config_decoder = decoder.RecurrentDecoderConfig( max_seq_len_source=max_seq_len_source, rnn_config=rnn...
None if len(source_vocab_sizes) > 1: source_factor_configs = [encoder.FactorConfig(size, dim) for size, dim in zip(source_factor_vocab_sizes, args.source_factors_num_embed)]
config_embed_source = encoder.EmbeddingConfig(vocab_size=source_vocab_size, num_embed=num_embed_source, dropout=embed_dropout_source, factor_configs=source_factor_co...
# -*- coding: utf-8 -*- import pytest import env # noqa: F401 from pybind11_tests import pickling as m try: import cPickle as pickle # Use cPickle on Python 2.7 exc
ept ImportError: import pickle @pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"]) def test_roundtrip(cls_name): cls = getattr(m, cls_name) p = cls("test_value") p.setExtra1(15) p.setExtra2(48) data = pickle.dumps(p, 2) # Must use pickle protocol >= 2 p2 = pickle.loads(...
assert p2.value() == p.value() assert p2.extra1() == p.extra1() assert p2.extra2() == p.extra2() @pytest.mark.xfail("env.PYPY") @pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"]) def test_roundtrip_with_dict(cls_name): cls = getattr(m, cls_name) p = cls("test_va...
# dialogs - provide common dialogs # # Copyright (c) 2006 FSF Europe # # Authors: # Sebastian Heinlein <glatzor@ubuntu.com> # Michael Vogt <mvo@canonical.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License...
NTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 # USA from gi.repository import Gtk def show_error_dialog(parent, primary, secondary): p = "<span weight=\"bold\" size=\"larger\">%s</span>" % primary dialog = Gtk.MessageDialog(parent,Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR,Gtk.ButtonsType.CLOSE,"") dial...
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 writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express...
tion as exc_msg: LOG.error("Exists
volume notification failed: %s", exc_msg, resource=volume_ref) def _snap_notify_usage(LOG, snapshot_ref, extra_info, admin_context): """snapshot_ref notify usage""" try: LOG.debug("Send notification for <snapshot_id: %(snapshot_id)s> " "<project_id %(project_id)s> <...
import graphene from ...core.permissions import DiscountPermissions from ...discount import models from ..core.mutations import ModelBulkDeleteMutation class SaleBulkDelete(ModelBulkDeleteMutation): class Arguments: ids = graphene.List( graphene.ID, required=True, description="List of sale ID...
ermissions.MANAGE_DISCOUNTS,) class VoucherBulkDelete(ModelBulkDeleteMutation): class Arguments: ids = graphene.List( graphene.ID, required=True, description="List of voucher IDs to delete." ) class Meta: description = "Deletes vouchers." model = models.Voucher ...
)
== exp_version @classmethod def _handle_event(cls, exploration_id, exp_version, aggregated_stats): if 'undefined' in aggregated_stats['state_stats_mapping']: logging.error( 'Aggregated stats contains an undefined state name: %s' % list(aggregated_stats['stat...
params, play_type): stats_models.StartExplorationEventLogEntryModel.create( exp_id, exp
_version, state_name, session_id, params, play_type) handle_exploration_start(exp_id) class MaybeLeaveExplorationEventHandler(BaseEventHandler): """Event handler for recording exploration leave events.""" EVENT_TYPE = feconf.EVENT_TYPE_MAYBE_LEAVE_EXPLORATION @classmethod def _ha...
''' ''' from __future__ import absolute_import from ...exceptions import ProtocolError index = {} def register(cls): ''' Decorator to add a Message (and its revision) to the Protocol index. ''' key = (cls.msgtype, cls.revision) if key in index: raise ProtocolError("Duplicate message specifi...
rn cls from .ack import * from .ok import * from .patch_doc import * from .pull_doc_req import * from .pull_doc_reply import * from .push_doc import * from .error import * from .server_info_reply import * from .server_info_req import * from .workin
g import *
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides the web interface for adding and editing sheriff rotations.""" from __future__ import print_function from __future__ import division from __futur...
query = table_config.TableConfig.query() table_config_list = query.fetch(keys_only=True) return_list = [] for config in table_config_list: return_list.append(config.id
()) self.response.out.write(json.dumps({ 'table_config_list': return_list, })) def _GetTableConfigDetails(self, config_name): config_entity = ndb.Key('TableConfig', config_name).get() if config_entity: master_bot_list = [] for bot in config_entity.bots: master_bot_list.app...
""" progressbar2 related utils""" from codekit.codetools import warn from public import public from time import sleep import progressbar import functools @public def setup_logging(verbosity=0): """Configure progressbar sys.stderr wrapper which is required to play nice with logging and not have strange format...
""" wait_for_user_panic(**kwargs) @public def eta_bar(msg, max_value): """Display an adaptive ETA / countdown bar with a message. Parameters
---------- msg: str Message to prefix countdown bar line with max_value: max_value The max number of progress bar steps/updates """ widgets = [ "{msg}:".format(msg=msg), progressbar.Bar(), ' ', progressbar.AdaptiveETA(), ] return progressbar.ProgressBar(widge...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.scala.goals.tailor import classify_source_files from pants.backend.scala.target_types imp
ort ( ScalaJunitTestsGeneratorTarget, ScalaSourcesGeneratorTarget, ScalatestTestsGeneratorTarget, ) def test_classify_source_files() -> None: scalatest_files = { "foo/bar/BazSpec.scala", } junit_files = { "foo/bar/BazTest.scala", } lib_files = {"foo/bar/Baz.scala"} ...
atest_files, ScalaJunitTestsGeneratorTarget: junit_files, ScalaSourcesGeneratorTarget: lib_files, } == classify_source_files(junit_files | lib_files | scalatest_files)
#===== # # Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios), # its affiliates and/or its licensors. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source cod...
ARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY...
VISED OF THE POSSIBILITY OF SUCH DAMAGE. # #===== # Subd Render # # This cookbook example demonstrates how to load & render a mesh primitive and # render it as a subdivision surface. # #===== from IECore import * class subdRender(ParameterisedProcedural) : def __init__(self) : ParameterisedPr...
import unittest import dbt.exceptions import dbt.utils from dbt.parser.schema_renderer import SchemaYamlRenderer class TestYamlRendering(unittest.TestCase): def test__m
odels(self): context = { "test_var": "1234", "alt_var": "replaced", } renderer = SchemaYamlRenderer(context, 'models') # Verify description is not rendered and misc attribute is rendered dct
= { "name": "my_model", "description": "{{ test_var }}", "attribute": "{{ test_var }}", } expected = { "name": "my_model", "description": "{{ test_var }}", "attribute": "1234", } dct = renderer.render_data(dct) ...
import urllib.parse import sys from ccs import core from ccs import constants from . import response def ticker(): s = __name__.split(".")[1] r = sys._getframe().f_code.co_name # complete request cr = core.request(s, r) return core.get(core.hostname(s), cr, core.header(s), core.compression(s), ...
) def orderbook(): s = __name__.split(".")[1] r = sys._getframe().f_code.co_na
me # complete request cr = core.request(s, r) return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.timeout(s))
T", __DFU_STATE_DFU_MANIFEST_WAIT_RESET: "STATE_DFU_MANIFEST_WAIT_RESET", __DFU_STATE_DFU_UPLOAD_IDLE: "STATE_DFU_UPLOAD_IDLE", __DFU_STATE_DFU_ERROR: "STATE_DFU_ERROR", } # USB device handle __dev = None # Configuration descriptor of the device __cfg_descr = None __verbose = None # USB DFU interface __...
te memory", __DFU_STATE_DFU_DOWNLOAD_BUSY) # Check command state check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_IDLE) xfer_count += 1 xfer_bytes += chunk def write_page(buf, xfer_offset): """Writes a single page. This routine assumes that memory has already been erased...
mem write address set_address(xfer_base + xfer_offset) # Send DNLOAD with fw data __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf, __TIMEOUT) # Execute last command check_status("write memory", __DFU_STATE_DFU_DOWNLOAD_BUSY) # Check command state check_status("write memor...
import argparse import configparser from codepunks.config import (Config, INISource, XMLSource, JSONSource, YAMLSource, ArgParserSource) ARGS1 = argparse.Namespace() ARGS1.apkey1 = "apval1" ARGS1.apkey2 = "apval2" ARGS1.apkey3 = "apval3" def testEmptyCfg(): Config() def testINISo...
onfig/config2.ini")]) c.load() def testXMLSource(): c = Config(XMLSource("tests/config/config.xml")) c.load() def testJSONSource(): c = Config(JSONSource("tests/config/config.json")) c.load() def testYAMLSource(): c = Config(YAMLSource("tests/config/config.yml")) c.load() def testArg...
/config/config.ini"), XMLSource("tests/config/config.xml"), JSONSource("tests/config/config.json"), YAMLSource("tests/config/config.yml"), ArgParserSource(ARGS1)]) c.load()
class Dudle(object): de
f __init__(self): self.baseurl = 'https://dudle.inf.tu-dresden.de/?create_poll=' def getDudle(self, name, type='time', url=''): return(self.baseurl + name + '&poll_type
=' + type + '&poll_url=' + url)
from django.apps import AppConfig
class UniversityCreditsConfig(AppConfig): name = 'university_c
redits'
#!/usr/bin/env python # 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 Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
for package in deps: if not smm.check_installed(package) and not smm.install(package): self.cancel("Failed to install %s, which is needed for" "the test to be run" % package) tarball = self.fetch_asset('vanilla_pathscale.zip', locations=[ ...
archive.extract(tarball, self.srcdir) self.sourcedir = os.path.join(self.srcdir, 'libunwind-vanilla_pathscale') os.chdir(self.sourcedir) process.run('./autogen.sh', shell=True) ''' For configure options on different architecture please refer https://github.com/pathsca...
""" pyfire.contact ~~~~~~~~~~ Handles Contact ("roster item") interpretation as per RFC-6121 :copyright: 2011 by the pyfire Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import xml.etree.ElementTree as ET from sqlalchemy import Table, Column, Boolean, Integ...
(jid, JID): self.jid = jid self.jid.validate(raise_error=True) else: raise AttributeError("Needs valid jid either as string or JID instance") # optional self.approved = False self.ask = None self.name = None self.subscription = "none" ...
self.groups = [] for k, v in kwds.iteritems(): setattr(self, k, v) def to_element(self): """Formats contact as `class`:ET.Element object""" element = ET.Element("item") if self.approved is not None: element.set("approved", 'true' if self.approved else 'fa...
) asts = set(_[1] for _ in ar) ar2 = set(_[:2] for _ in ar) aam, sam = missing(aabs, sabs) asm, ssm = missing(asts, ssts) ar2m, sr2m = missing(ar2, set(sr)) print('OK to skip') print(sorted(aam)) print('Need to be created') print(sorted(sam)) ...
return [l for l in f.read().split('\n') if l] @classmethod def processData(cls): out = {} recs = [] parent_stack = [None] old_depth = 0 layers = {} for l in cls.raw: depth, abbrev, _, name = l.split('
', 3) depth = len(depth) if old_depth < depth: # don't change parent = parent_stack[-1] parent_stack.append(abbrev) old_depth = depth elif old_depth == depth: if len(parent_stack) - 1 > depth: pare...
from __future__ import absolute_import from __future__ import print_function from .ChessFile import ChessFile, LoadingError from pychess.Utils.GameModel import GameModel from pychess.Utils.const import WHITE, BLACK, WON_RESIGN, WAITING_TO_START, BLACKWON, WHITEWON, DRAW from pychess.Utils.logic import getStatus from py...
return model def get_player_names (self, gameno): data = self.games[gameno] names = {} for key in "tcri", "tcsi": keyindex = data.find(key) if keyindex == -1: names[key] = _("Unknown") else: sem =...
1:sem] email, name = opcode.split(" ", 1) names[key] = name color = data.split(" ")[1] == "b" and BLACK or WHITE if color == WHITE: return (names["tcri"], names["tcsi"]) else: return (names["tcsi"], names["tcri"])
DFU=0x00D0, BATTERY_STATUS=0x1000, LED_CONTROL=0x1300, CHANGE_HOST=0x1814, BACKLIGHT=0x1981, REPROG_CONTROLS=0x1B00, REPROG_CONTROLS_V2=0x1B01, REPROG_CONTROLS_V2_2=0x1B02, # LogiOptions 2.10.73 features.xml REPROG_CONTROLS_V3=0x1B03, REPROG_CONTROLS_V4=0x1B04, WIRELESS_DEVICE_STATUS=0x1D4B, LEFT_RIGHT_SWAP=...
TODO: add here additional variants for other REPROG_CONTROLS if self.keys[index] is None: keydata = feature_request(self.device, FEATURE.REPROG_CONTROLS, 0x10, index) self.keyversion=1 if keydata is None: keydata = feature_request(self.device, FEATURE.REPROG_CONTROLS_V4, 0x10, index) self.keyve...
up, gmask = _unpack('!HHBBBB', keydata[:8]) ctrl_id_text = special_keys.CONTROL[key] ctrl_task_text = special_keys.TASK[key_task] if self.keyversion == 1: self.keys[index] = _ReprogrammableKeyInfo(index, ctrl_id_text, ctrl_task_text, flags) if self.keyversion == 4: try: mapped_dat...
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2016 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...
tware, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT O...
#!/usr/bin/env python import os import re import sys def stamp(html): """Stamp a Python HTML documentation page with the SourceF
orge logo""" def replace(m): return ('<span class="release-info">%s ' 'Hosted on <a href="http://sourceforge.net">' '<img src="http://sourceforge.net/' 'sflogo.php?group_id=82987&type=1" width="88" height="31"' 'border="0" alt="SourceForge Log...
>') return re.sub(mailRe, replace, html) # stamp() if __name__ == '__main__': for name in sys.argv[1:]: html = open(name, 'r').read() text = stamp(html) if text != html: os.remove(name) file = open(name, 'w') file.write(text) file.close(...
fro
m simpleGossip.gossiping.gossip import RemoteGossipService if __name__ == "__main__": from rpyc.utils.server import ThreadedServer t = ThreadedServer( RemoteGossipService, port=18861 ) t.start()
# Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. """PyCrypto AES implementation.""" from .cryptomath import * from .aes import * if pycryptoLoaded: import Crypto.Cipher.AES def new(key, mode, IV
): return PyCrypto_AES(key, mode, IV) class PyCrypto_AES(AES): def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "pycrypto") key = bytes(key) IV = bytes(IV) self.context = Crypto.Cipher.AES.new(key, mode, IV) de...
bytearray(self.context.encrypt(plaintext)) def decrypt(self, ciphertext): ciphertext = bytes(ciphertext) return bytearray(self.context.decrypt(ciphertext))
# -*- encoding: utf-8 -*- ############################################################################### # # # Copyright (C) 2016 Trustcode - www.trustcode.com.br # # Danimar Ribeiro <danimaribeiro@gmail.co...
e GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distribu...
ESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program...
clas
s SpellPickerController: de
f render(self): pass _controller_class = SpellPickerController
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import OrderedDict from nose.tools import eq_, assert_raises from mosql.query import select, insert, replace from mosql.util import param, ___, raw, DirectionError, OperatorError, autoparam def test_select_customize(): gen = select('person', Order...
%(my_param)s ' 'AND "auto_param" = %(auto_param)s AND "using_alias" = %(using_alias)s' ) eq_(gen, exp) def test_insert_dict(): gen = insert('p
erson', OrderedDict([ ('person_id', 'mosky'), ('name', 'Mosky Liu') ])) exp = ('INSERT INTO "person" ("person_id", "name") ' 'VALUES (\'mosky\', \'Mosky Liu\')') eq_(gen, exp) def test_insert_returing(): gen = insert('person', OrderedDict([ ('person_id', 'mosky'), ('name', '...
space and time. """ # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # Denis Engemannn <denis.engemann@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np from numpy.random import randn import matplotlib.pyplot ...
ustering statistic # ---------------------------- # # To use an algorithm optimized for spatio-temporal clustering, we # just pass the spatial connectivity matrix (instead of spatio-temporal). source_space = grade_to_tris(5) # as we only have one hemisphere we need only need half the connectivity lh_source_s
pace = source_space[source_space[:, 0] < 10242] print('Computing connectivity.') connectivity = spatial_tris_connectivity(lh_source_space) # Now let's actually do the clustering. Please relax, on a small # notebook and one single thread only this will take a couple of minutes ... pthresh = 0.0005 f_thresh = f_th...
#!/usr/bin/python # # convert .po to .js # import json import optparse import os import polib import re import string import sys parser = optparse.OptionParser(usage="usage: %prog [options] pofile...") parser.add_option("--callback", default="_.setTranslation", dest="callback", help="callback function to call with da...
ns, ar
gs) = parser.parse_args() if args == None or len(args) == 0: print("ERROR: you must specify at least one po file to translate"); sys.exit(1) paramFix = re.compile("(\\(([0-9])\\))") for srcfile in args: destfile = os.path.splitext(srcfile)[0] + ".js" if options.verbose: print("INFO: converting %s to %s" % (sr...
#!/usr/bin/python import unittest, pprint, sys sys.path.append( '../siux' ) import siuxlib class TestSourceInfo(unittest.TestCase): # config auth = '<YOUR_API_KEY>' def checkSourceInfo( self,retList ): """ Method tests sourceInfo structure :param retList: - structure reported by API """ self.assert...
ertTrue( 'timeoutErr' in retList ) self.assertTrue( isinstance( retList['timeoutErr'] ,int )) self.assertTrue( 'timeoutWarn' in retList ) self.assertTrue( isinstance( retList['timeoutWarn'] ,int )) self.assertTrue( 'timezone' in retList ) self.assertTrue( isinstance( retList['timezone'] ,int )) self.a...
rtTrue( isinstance( retList['timezoneId'] ,int )) self.assertTrue( 'timezoneName' in retList ) self.assertTrue( 'timezoneNick' in retList ) self.assertTrue( 'url' in retList ) self.assertTrue( 'urlNice' in retList ) def testSourceInfo(self): """ Test tests correct api sourceList call """ # init...
#!/usr/bin/env python from pymongo import MongoClient import json import sys # print message and die def msgDie(msg): print msg sys.exit(2) if len(sys.argv) != 4: msgDie("usage: unifi-minder.py config.json site-name minSNR") # load config cfgFile = sys.argv[1] siteName = sys.argv[2] minSNR = sys.argv[3] with ope...
ile: cfg = json.load(data_file) # get database dbCfg = cfg['database'] client = MongoClient(dbCfg['host'], dbCfg['port']) db = client[dbCfg['db']] sites = db['site'] site = sites.find_one({"name": siteName}) sid = str(site["_id"]) devices = db['device'] for device in devices.find({"site_id": sid}): mac = d...
config.minrssi.%s.%s=%s" % (mac, radtype, minSNR)
#!/usr/bin/env python ''' decode an stm32 ICSR register value ''' import sys import optparse def num(s): try: return int(s) except ValueError: return int(s, 16) parser = optparse.OptionParser(__file__) opts, args = parser.parse_args() if len(args) == 0: print(parser.usage) sys.exi...
e 225 def decoder_m4_vectactive(value): exceptions = { 0: "Thread mode", 1: "Reserved", 2: "NMI", 3: "Hard fault", 4: "Memory management fault", 5: "Bus fault", 6: "Usage fault", 7: "Reserved....", 10: "Reserved", 11: "SVCall", ...
exceptions[value]) else: exception = "IRQ%u" % (value - 16) sys.stdout.write(" (%s)" % exception) M4_BITS = [ ("0-8", "VECTACTIVE", decoder_m4_vectactive), ("9-10", "RESERVED1", None), ("11", "RETOBASE", None), ("12-18", "VECTPENDING", None), ("19-21", "RESERVED2", None), ("22...
import math def formatAmount(val, prec=3, lowest=0, highest=0, currency=False, forceSign=False): """ Add suffix to value, transform value to match new suffix and round it. Keyword arguments: val -- value to process prec -- precision of final number (number of significant positions to show) lo...
wise consider current results as acceptable break # Round mantissa according to our prec variable mantissa = roundToPrec(mantissa, prec) sign = "+" if force
Sign is True and mantissa > 0 else "" # Round mantissa and add suffix result = "{0}{1}{2}".format(sign, mantissa, suffix) return result def roundToPrec(val, prec): # We're not rounding integers anyway # Also make sure that we do not ask to calculate logarithm of zero if int(val) == val: ...
{} for n,m in sys.modules.items(): if n=='reportlab' or n=='rlextra' or n[:10]=='reportlab.' or n[:8]=='rlextra.': v = [getattr(m,x,None) for x in ('__version__','__path__','__file__')] if [_f for _f in v if _f]: v = [v[0]] + [_f for _f in v[1:] if...
list(v.keys()) K.sort() for k in K: vk = vk0 = v[k] if isinstance(vk,tuple): vk0 = vk[0] try: __import__(k)
m = sys.modules[k] d = getattr(m,'__version__',None)==vk0 and 'SAME' or 'DIFFERENT' except: m = None d = '??????unknown??????' self._writeln(' %s = %s (%s)' % (k,vk,d)) def _banner(self,k,what): self._writeln('##############...
""" A Printer for generating executable code. The most important function here is srepr that returns a string so that the relation eval(srepr(expr))=expr holds in an appropriate environment. """ from printer import Printer from sympy.core import Basic import sympy.mpmath.libmp as mlib from sympy.mpmath.libmp import p...
_"): l = [] for o in expr.args: l.append(self._print(o)) return expr.__class__.__name__ + '(%s)'%', '.join(l) elif hasattr(expr, "__module__") and hasattr(expr, "__name__"): return "<'%s.%s'>"%(expr.__module__, expr.__name__) else: ...
(expr) def _print_Add(self, expr): args = list(expr.args) args.sort(Basic._compare_pretty) args = map(self._print, args) return "Add(%s)"%", ".join(args) def _print_Function(self, expr): r = '%s(%r)' % (expr.func.__base__.__name__, expr.func.__name__) r+= '(%s)'...
# -*- coding: utf-8 -*- from eventlet import httpc from zenqueue.client.http.common import HTTPQueueClient class QueueClient(HTTPQueueClient): def send(self, url, data=''): # Catch non-successful HTTP requests and treat them as if they were. try: result = httpc.post(url, data=da...
ult
from django.contrib import admin from . import models from .models import
Hollywood, Profession, Artist, Xaxis, Yaxis, MovieImage, ArtistImage class ArtistInline(admin.StackedInline): model = Artist extra = 4 class ProfessionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['prof_name']}), ] inlines = [ArtistInline] admin.site.register(Pr...
dmin.site.register(ArtistImage)
""" Public views """ from django_future.csrf import ensure_csrf_cookie from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.conf import settings from edxmako.shortcuts import render_to_response from external_auth.views import (s...
csrf_cookie def signup(request): """ Display the signup form. """ csrf_token = csrf(request)['csrf_token'] if request.user.is_authenticated(): return redirect('/course/') if settings.FEATURES.get('AUTH_USE_CERTIFICATES_IMMEDIATE_SIGNUP'): # Redirect to course to login to process ...
ogin', request.GET, False) return render_to_response('register.html', {'csrf': csrf_token}) @ssl_login_shortcut @ensure_csrf_cookie def login_page(request): """ Display the login form. """ csrf_token = csrf(request)['csrf_token'] if (settings.FEATURES['AUTH_USE_CERTIFICATES'] and ...
#!/usr/bin/env python 'Unit test for debugger info file' import inspect, unittest from trepan import debugger as Mdebugger from trepan.processor.command import info as Minfo from trepan.processor.command.info_subcmd import files as MinfoFile from cmdhelper import dbg_setup class TestInfoFile(unittest.TestCase): ...
elf): self.msgs = [] self.errmsgs = [] self.last_was_newline = True return def msg_nocr(self, msg): if len(self.msgs) > 0: self.msgs[-1] += msg else: self.msgs += msg pass return def msg(self, msg): self.msgs +...
) d, cp = dbg_setup(d) command = Minfo.InfoCommand(cp, 'info') sub = MinfoFile.InfoFiles(command) self.setup_io(sub) sub.run([]) self.assertEqual([], self.msgs) cp.curframe = inspect.currentframe() for width in (80, 200): # sub.settings['width...
""" Test for the bandicoot.helper.group module. """ import bandicoot as bc from bandicoot.core import Record, Position import unittest import datetime from bandicoot.tests.generate_user import random_burst from bandicoot.helper.group import group_records from bandicoot.helper.tools import std, mean from datetime impor...
os.chdir(abspath) TestGroup._dir_changed = True self.maxDiff = None self.user = bc.io.read_orange("u_test", "samples", describe=False) self.random_int_list = np.random.randint(1, 1000, size=9001) self.sum_stats_list = [bc.helper.tools.SummaryStats(np.random.rand(), np...
m.rand(), np.random.rand(), np.random.rand(), np.random.rand(), []) for _ in range(9001)] def test_statistics(self): self.assertDictEqual(bc.helper.group.statistics(self.random_int_list, summary='default'), { 'mean': mean(self.random_int_list), 'std': std(self.random_int_list), ...
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # # Copyright (c) 2013, Intel Corporation. # All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General
Public License version 2 as # published by the Free Software Foundation. # # T
his program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # wit...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Lester R Claudio <claudiol@redhat.com> # # 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 Software Foundation, either version 3 of the License, or # (at your opti...
HOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __fut...
s description: - Manage Realms author: - "Lester R Claudio (@claudiol1)" options: name: description: - Name of the realm required: true type: str realm_proxy: description: - Proxy to use for this realm required: true type: str realm_type: description: - Realm type...
from s
rc.tools.enum import enum import pyxbmct.addonwindow as pyxbmct from src.tools.dialog import dialog EnumMode = enum(SELECT=0, ROTATE=1) class EnumButton(object): def __init__(self, label, values, current, default, changeCallback=None, saveCallback=None, customLabels=None, mode=EnumMode.SELECT, returnValue=False...
self.returnValue = returnValue self.changeCallback = changeCallback self.saveCallback = saveCallback self.currentValue = current self.defaultValue = default self.currentIndex = None self.defaultIndex = None ...
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest import os import numpy as np from rmgpy import getPath from rmgpy.qm.main import QMCalculator from rmgpy.molecule import Molecule from rmgpy.qm.mopac import MopacMolPM3, MopacMolPM6, MopacMolPM7 mopacEnv = os.getenv('MOPAC_DIR', default="/opt/mopac") if os....
oData() result = self.qmmol1.qmData self.assertTrue(self.qmmol1.thermo.comment.startswith('QM MopacMolPM3 calculation')) self.assertEqual(result.numberOfAtoms, 18) self.assertIsInstance(result.atomicNumbers, np.ndarray) if result.molecularMass.units=='amu': self.assertAlmostEqual(result.molecularMass.va...
to 1 decimal place def testLoadThermoData(self): """ Test that generateThermoData() can load thermo from a previous run. Check that it loaded, and the values are the same as above. """ self.qmmol1.generateThermoData() result = self.qmmol1.qmData self.assertTrue(self.qmmol1.thermo.comment.star...
coding: utf-8 -*- # # face_recognition documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # ...
no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'face_recognition', u'Face Recognition Do...
ptions for Texinfo output ---------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry,
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2017 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as publish...
gramObject, Location class Venue(TelegramObject): """This object represents a venue. Attributes: location (:class:`telegram.Location`): Venue location. title (:obj:`str`): Name of the venue. address (:obj:`str`
): Address of the venue. foursquare_id (:obj:`str`): Optional. Foursquare identifier of the venue. Args: location (:class:`telegram.Location`): Venue location. title (:obj:`str`): Name of the venue. address (:obj:`str`): Address of the venue. foursquare_id (:obj:`str`...
# -*- coding:utf-8 -*
- from django.utils.translation import ugettext_lazy as _ # SearchForm's strings SEARCH_FORM_KEYWORDS = _(u'Key Words / Profession') SEARCH_FORM_LOCATION = _(u'City, State or Zip Code') # SearchFiltersForm's strings SEARCH_FILTERS_FORM_JOB_POSITION = _(u'Job Position') SEARCH_FILTERS_FORM_EXPERIENCE_YEARS = _(u'Exper...
Distance') SEARCH_FILTERS_FORM_FULL_TIME = _(u'Full Time') SEARCH_FILTERS_FORM_PART_TIME = _(u'Part Time') SEARCH_FILTERS_FORM_VISA = _(u'Has a Visa / Visa required')