prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# -*- coding: utf-8 -*- # Amara, universalsubtitles.org # # Copyright (C) 2013 Participatory Culture Foundation # # This program is free software: you can redistri
bute it and/or modify # it under the terms of the 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 distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICU...
= 'none') and (not infos['ask'] or \ infos['ask'] == 'none') and not infos['name'] and \ not infos['groups']: # remove this useless item, it won't be shown in roster # anyway self.conn.connection.getRoster()....
= [] confs = self.storage_node.getTags('conference') for conf in confs: autojoin_val = conf.getAttr('autojoin') if autojoin_val is None: # not there (it's optional)
autojoin_val = False minimize_val = conf.getAttr('minimize') if minimize_val is None: # not there (it's optional) minimize_val = False print_status = conf.getTagData('print_status') if not print_status: print_status = conf.getTagDa...
# 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 it will be useful, # but...
U": # we should collect /proc/xen and /sys/hypervisor self.dom_collect_proc() # determine if hardware virtualization support is enabled # in BIOS: /sys/hypervisor/properties/capabilities
self.add_copy_spec("/sys/hypervisor") elif host_type == "hvm": # what do we collect here??? pass elif host_type == "dom0": # default of dom0, collect lots of system information self.add_copy_spec([ "/var/log/xen", "/...
# -*- coding: utf-8 -*- ## Copyright © 2012, Matthias Urlichs <matthias@urlichs.de> ## ## 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 op...
nit__(*a,**k) self.env_cache = {} def list_valves(self): return u"¦".join((d.name for d in self.valves.all())) def refresh(self): super(EnvGroup,self).refresh() self.env_cache = {} def env_factor_one(self, tws, h): p=4 # power factor, favoring nearest-neighbor qtemp,qwind,qsun = tws if qtemp and h....
temp__isnull=not qtemp) q &= Q(wind__isnull=not qwind) q &= Q(sun__isnull=not qsun) sum_f = 0 sum_w = 0 try: ec = self.env_cache[tws] except KeyError: self.env_cache[tws] = ec = list(self.items.filter(q)) for ef in ec: d=0 if qtemp: d += (h.temp-ef.temp)**2 if qwind: d += (h.wind-e...
import csv from dateutil.parser import parse from adoptarbol.tree.models import Tree def load(filename): with open(filename, encoding='utf-8') as f: reader = csv.reader(f) header = next(reader) def pos_for(field): return header.index(field) def float_or_none(string)...
], 'scientific_name': row[pos_for('cientifico')], 'family': row[pos_for('familia')], 'coord_utm_e': float_or_none(row[pos_for('utm_x')].replace(',', '.')), 'coord_utm_n': float_or_none(row[pos_for('utm_y')].replace(',', '.')), ...
], 'coord_utm_zone_n': row[pos_for('utm_south')], 'coord_lat': float_or_none(row[pos_for('lat')].replace(',', '.')), 'coord_lon': float_or_none(row[pos_for('long')].replace(',', '.')), 'photo': row[pos_for('fotos')], 'di...
from .endpoint import Endpoint from .exceptions import MissingRequiredFieldError from .fileuploads_endpoint import Fileuploads from .. import RequestFactory, DatasourceItem, PaginationItem, ConnectionItem import os import logging import copy import cgi from contextlib import closing # The maximum size of a file that c...
e ValueError(error) url = "{0}/{1}".format(self.baseurl, datasource_id) self.delete_request(url)
logger.info('Deleted single datasource (ID: {0})'.format(datasource_id)) # Download 1 datasource by id def download(self, datasource_id, filepath=None): if not datasource_id: error = "Datasource ID undefined." raise ValueError(error) url = "{0}/{1}/content".forma...
################ # Main ################################################################################################### def main(argv=None): ''' Runs the program. There are three ways to pass arguments 1) environment variables TFB_* 2) configuration file benchmark.cfg 3) command line flags In t...
sys.path.append('.') # 2) Ensure toolset/setup/linux is in the path so that the tests can "import setup_util". sys.path.append('toolset/setup/linux') # Update environment for shell scripts fwroot = setup_util.get_fwroot() if not fwroot: fwroot = os.getcwd() setup_util.replace_envi...
gparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False) conf_parser.add_argument('--conf_file', default='benchmark.cfg', metavar='FILE', help='Optional configuration file to provide argument defaults. All config options can be overrid...
from Cython.Compiler.ModuleNode import ModuleNode from Cython.Compiler.Symtab import ModuleScope from Cython.TestUtils import TransformTest from Cython.Compiler.Visitor import MethodDispatcherTransform from Cython.Compiler.ParseTreeTransforms import ( NormalizeTree, AnalyseDeclarationsTransform, AnalyseExpressi...
m(TransformTest): _tree = None
def _build_tree(self): if self._tree is None: context = None def fake_module(node): scope = ModuleScope('test', None, None) return ModuleNode(node.pos, doc=None, body=node, scope=scope, full_module_name='test', ...
""" Copyright (C) 2016 ECHO Wizard : Modded by TeamGREEN 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 option) any later v...
est, dp = None): if not dp: dp = xbmcgui.DialogProgress() # dp.create("[COLORgold]Download In Progress[/COLOR]"' ',' ', ' ') # dp.update(0) start_time=time.time() urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(nb, bs, fs, dp, start_time)) def auto(url, dest, dp = None): ...
start_time=time.time() urlretrieve(url, dest, lambda nb, bs, fs: _pbhookauto(nb, bs, fs, dp, start_time)) def _pbhookauto(numblocks, blocksize, filesize, url, dp): none = 0 def _pbhook(numblocks, blocksize, filesize, dp, start_time): try: percent = min(numblocks * blocksize * 1...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: info@andreacometa.it # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 ...
l, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <h...
gs(models.TransientModel): _inherit = 'account.config.settings' due_cost_service_id = fields.Many2one( related='company_id.due_cost_service_id', help='Default Service for RiBa Due Cost (collection fees) on invoice', domain=[('type', '=', 'service')]) def default_get(self, cr, uid,...
from notifications_utils.clients.antivirus.antivirus_client import ( AntivirusClient, ) from notifications_utils.clients.redis.redis_c
lient import RedisClient from notifications_utils.clients.zendesk.zendesk_client import ZendeskClient antivirus_client = AntivirusClient()
zendesk_client = ZendeskClient() redis_client = RedisClient()
masterSection.ms('Replicating each segment during replay', on_masters(lambda m: ( ((m.master.replicationTicks - m.master.logSyncTicks) / m.clockFrequency) / math.ceil((m.master.replicationBytes - m.master.logSyncBytes) / m.segmentSize) / m....
unit='Gb/s', summaryFns=[AVG, MIN, SUM]) diskSection = report.add(Section('Disk Utilization')) diskSection.line('Effective bandwidth', on_backups(lambda b: (b.backup.storageReadBytes + b.backup.storageWriteBytes) / 2**20 / recove...
unit='MB/s', summaryFns=[AVG, MIN, SUM]) def active_bandwidth(b): totalBytes = b.backup.storageReadBytes + b.backup.storageWriteBytes totalTicks = b.backup.storageReadTicks + b.backup.storageWriteTicks return ((totalBytes / 2**20) / (totalTicks / b.clockFreque...
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ from abc import ABCMeta, abstractmethod from django.contrib.auth.models import User, Group from xmodule.modulestore import Location from xmodule.modulest...
for user in users: if hasattr(user, '_groups'): del user._groups def remove_users(self, *users): """ Remove the supplied django users from this role. """ group, _ = Group.objects.get_or_create(name=self._group_names[0]) group.user_se
t.remove(*users) for user in users: if hasattr(user, '_groups'): del user._groups def users_with_role(self): """ Return a django QuerySet for all of the users with this role """ return User.objects.filter(groups__name__in=self._group_names) clas...
#!/usr/bin/python3 # -*- encoding: utf-8 -*- import unittest from model import * from example_data import expenses, payments, participations, persons, events kasse = Gruppenkasse.create_new() kasse.fill_with(expenses, payments, participations) class T
estGruppenkasse(unittest.TestCase): def setUp(self): ... def test_persons(self
): person_names = list(map(lambda p: p.name, kasse.persons)) for name in person_names: self.assertTrue(name in persons, msg=name) def test_events(self): print(kasse.person_dict) event_names = list(map(lambda p: p.name, kasse.events)) for name in event_names: ...
tories import WikiFactory, WikiVersionFactory from api.base.settings.defaults import API_BASE from api_tests.wikis.views.test_wiki_detail import WikiCRUDTestCase from framework.auth.core import Auth from osf_tests.factories import ( AuthUserFactory, ProjectFactory, OSFGroupFactory, RegistrationFactory, ...
n_url, auth=user.auth, expect_errors=True) assert res.status_code == 403 assert res.json['errors'][0]['detail'] == exceptions.PermissionDenied.default_detail def test_do_not_return_disabled_wiki(self, app, user, public_url, public_project): public_project.delete_addo...
ionship_links( self, app, user, public_project, private_project, public_registration, private_registration, public_url, private_url, public_registration_url, private_registration_url): # test_public_node_wikis_relationship_links res = app.get(public_url...
from __future__ import divisio
n # Read two integers from STDIN a = int(raw_input()) b = int(raw_input()) # Print integer division, a//b print(a // b) # Print float division, a/b print(a % b) # Print divmod of a and b print(d
ivmod(a, b))
le == # The specific variables and commands will be defined later, here are # examples on what the commands looks like in bytes. # This is an example of a command to toggle verbose setting. # Command is write (0x57), variable is 13 (0x0d) # and value is 0. The footer is x10 x03 # 0x02 0x57 0x0xd 0x00 0x10 0x03 PO...
binascii.unhexlify(data)) if variable_char == '01': self._power_state = int(data, 16) elif variable_char == '14':
self._inputname = data if self._boot_print is True: self._boot_print = False logger.info("""Connected to: Manufacturer: %s Model: %s SW Version: %s ...
from monitor import monitor_qlen from subprocess import Popen, PIPE from time import sleep, time from multiprocessing import Process from argparse import ArgumentParser
import sys import os parser = ArgumentParser(description="CWND/Queue Monitor") parser.add_argument('--exp', '-e', dest="exp", action="store", help="Name of the Experiment", required=True) # Expt parameters args = parser.parse_args() def...
obe >/dev/null 2>&1); modprobe tcp_probe full=1;") print "Monitoring TCP CWND ... will save it to ./%s_tcpprobe.txt " % args.exp Popen("cat /proc/net/tcpprobe > ./%s_tcpprobe.txt" % args.exp, shell=True) def qmon(): monitor = Process(target=monitor_qlen,args=('s0-eth2', 0.01, '%s_sw0-qlen.txt' % ...
# -*- coding: utf-8 -* from pymeasure.instruments.pyvisa_instrument import PyVisaInstrument from pymeasure.case import ChannelRead from pymeasure.instruments.oxford import OxfordInstrument import time class _QxfordILMChannel(ChannelRead): def __init__(self, instrument): ChannelRead.__init__(self) ...
status = status[5] if status == '4' or status == 'C': return False elif status == '2' or status == '3' or status == 'A' : return True else: time.sleep(1) p
ass @fast.setter def fast(self, boolean): if boolean: self._instrument.write('T1') else: self._instrument.write('S1') class QxfordILM(PyVisaInstrument): def __init__(self, address, name='', reset=True, defaults=True, isobus=6, **pyvisa): super().__init__(a...
# # The Python Imaging Library. # $Id: MicImagePlugin.py,v 1.2 2007/06/17 14:12:15 robertoconnor Exp $ # # Microsoft Image Composer support for PIL # # Notes: # uses TiffImagePlugin.py to read the actual image streams # # History: # 97-01-20 fl Created # # Copyright (c) Secret Labs AB 1997. ...
self.__fp = self.fp self.frame = 0 if len(self.images) > 1: self.category = Image.CONTAINER self.seek(0) def seek(self, frame): try: filename = self.images[frame] except IndexError: raise EOFError, "no such frame" ...
n.TiffImageFile._open(self) self.frame = frame def tell(self): return self.frame # # -------------------------------------------------------------------- Image.register_open("MIC", MicImageFile, _accept) Image.register_extension("MIC", ".mic")
#------------------------------------------------------------------------------ # Copyright (C) 2009 Richard Lincoln # # This program is free software; you can redistribute it and/or modify it under # the te
rms of the GNU Affero General Public License as published by the Free # Software Foundation; version 2 dated June,
1991. # # This software is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANDABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU Affero General Public L...
from __future__ import absolute_import, unicode_literals import os from appconf i
mport AppConf from django.conf import settings # noqa class SessionRedisConf(AppConf): HOST = '127.0.0.1' PORT = 6379 DB = 0 PREFIX = 'django_sessions' PASSWORD = None UNIX_DOMAIN_SOCKET_PATH = None URL = None CONNECTION_POOL = None JSON_ENCODING = 'latin-1' ENV_URLS ...
L', 'OPENREDIS_URL', 'REDISGREEN_URL', 'MYREDIS_URL', ) def configure(self): if self.configured_data['URL'] is None: for url in self.configured_data['ENV_URLS']: redis_env_url = os.environ.get(url) if redis_env_url: ...
""" Compute class """ import numpy as np import matplotlib matplotlib.use('Agg') import pylab as pl #TODO: Take care of the looks of these plots class Compute(object): """ Abstract compute class. It will never be used, but is parent of all the different computes. """ def __init__(self): """ Construc...
cause not all o
f the computes have the same structure, so the "average" is not standard. By default we do the usual average. """ self.idx += 1 self.value *= (self.idx - 1)/self.idx self.value += value/self.idx def zero(self): """ Zero out current tallies. """ self.value = 0 self.idx = 0 d...
from django.core.files.storage import default_storage from django.forms import widgets from django.urls import reverse from repanier.const import EMPTY_STRING from repanier.picture.const import SIZE_M from repanier.tools import get_repanier_template_name class RepanierPictureWidget(widgets.TextInput): template_n...
(value) context["repanier_display_picture"] = "inline" context["repanier_display_upload"] = "none" context["repanier_file_url"] = default_storage.url(file_path) else: context["repanier_file_path"] = EMPTY_STRING context["repanier_display_picture"] = "n...
self.size context["bootstrap"] = self.bootstrap return context class Media: js = ("admin/js/jquery.init.js",)
"""This will perform basic enrichment on a given IP.""" import csv import json import mmap import os import socket import urllib import dns.resolver import dns.reversename from geoip import geolite2 from IPy import IP from joblib import Parallel, delayed from netaddr import AddrFormatError, IPSet torcsv = 'Tor_ip_li...
pe", help="Either single or batch request") PARSER.add_argument("-v", required="false", metavar="value",
help="The value of the request") ARGS = PARSER.parse_args() if ARGS.t == "single": print(single(ARGS.v)) elif ARGS.t == "batch": batch(ARGS.v) else: PARSER.print_help() if __name__ == "__main__": main()
hemaError as exc: get_logger().error('downloads.ini failed schema validation (located in %s)', path) raise exc return new_data def __init__(self, ini_paths): """Reads an iterable of pathlib.Path to download.ini files""" self._data = configparser.ConfigParser() ...
nload_if_needed(file_path, url, show_progress, disable_ssl_verification): """ Downloads a file from url to the specified path file_path if necessary. If show_progress is True, download progress is printed to the console. """ if file_path.exists(): get_logger().info('%s already exists. Skipp...
return # File name for partially download file tmp_file_path = file_path.with_name(file_path.name + '.partial') if tmp_file_path.exists(): get_logger().debug('Resuming downloading URL %s ...', url) else: get_logger().debug('Downloading URL %s ...', url) # Perform download if ...
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not
use this file except in complianc
e 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or i...
nv python2 # # Copyright (C) 2013-2017(H) # Max Planck Institute for Polymer Research # # This file is part of ESPResSo++. # # ESPResSo++ 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 vers...
e, scale=10) for i in range(check): T = temperature.compute() P = pressure.compute() Eb = 0 EAng = 0 ETab=0 #for bd in bondedinteractions.values(): Eb+=bd.computeEnergy() #for ang in angleinteractions.values(): EAng+=ang.computeEnergy() #ELj= ljinteraction.computeEnergy() #EQQ= q...
Energy() ETab= tabulatedinteraction.computeEnergy() T = temperature.compute() Ek = 0.5 * T * (3 * num_particles) Etotal = Ek+Eb+EAng+ETab sys.stdout.write(fmt%(i*timestep,Eb, EAng, ETab, Ek, Etotal, T)) outfile.write(fmt%(i*timestep,Eb, EAng, ETab, Ek, Etotal, T)) #espressopp.tools.pdb....
# encoding: utf-8 from __future__ import absolute_import, division, print_function import numpy as np import tables from liam2.data import merge_arrays, get_fields, index_table_light, merge_array_records from liam2.utils import timed, loop_wh_progress, merge_items __version__ = "0.4" def get_group_fiel...
le.create_table(output_group, ent_name, np.dtype(output_fields)) if ent_name in ent_names1: table1 = getattr(group1, ent_name) # no
inspection PyProtectedMember print(" * indexing table from %s ..." % group1._v_file.filename, end=' ') input1_rows = index_table_light(table1, index_col) print("done.") else: table1 = None input1_rows = {} if ent_nam...
cale, UnknownLocaleError from babel.dates import format_datetime from babel.messages import checkers from babel.messages.plurals import PLURALS from babel.messages.pofile import read_po from babel.util import LOCALTZ from babel._compat import BytesIO class CheckersTestCase(unittest.TestCase): # the last msgstr[id...
# %(english_name)s translations for TestProject. # Copyright (C) 2007 FooBar, Inc. # This file is distributed under the same license as the TestProject # project. # FIRST AUTHOR <EMAIL@ADDRES
S>, 2007. # msgid "" msgstr "" "Project-Id-Version: TestProject 0.1\\n" "Report-Msgid-Bugs-To: bugs.address@email.tld\\n" "POT-Creation-Date: 2007-04-01 15:30+0200\\n" "PO-Revision-Date: %(date)s\\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n" "Language-Team: %(locale)s <LL@li.org>\n" "Plural-Forms: nplurals=%(num_...
+= [""] * len(extensionsList) self.session.openWithCallback(self.extensionCallback, ChoiceBox, title=_("Please choose an extension..."), list = list, keys = keys, skin_name = "ExtensionsList") def extensionCallback(self, answer): if answer is not None: answer[1][1]() def showPluginBrowser(self): from Scree...
if slist and self.session.pipshown: slist.togglePipzap() if slist.dopipzap: currentServicePath = self.servicelist.getC
urrentServicePath() self.servicelist.setCurrentServicePath(self.session.pip.servicePath, doZap=False) self.session.pip.servicePath = current
Return a list of objects of kind :class:`stripeline.timetools.TimeChunk`. ''' delta_time = time_length / num_of_chunks result = [] for chunk_idx in range(num_of_chunks): # Determine the time of each sample in this chunk cur_time = chunk_idx * delta_time chunk_time0 = np.c...
lement', 'num_of_elements']) FitsColumn = namedtuple( 'FitsColumn', ['hdu', 'column'] ) FitsTableLayout = namedtuple( 'FitsTableLayout', ['time_col', 'theta_col', 'phi_col', 'psi_col', 'signal_cols'] ) def _load_array_from_fits(segments: List[ToiFileSegment], cols_to_read: List[FitsC...
d are in `cols_to_read`. The function returns a tuple containing all the data from the columns (each in a NumPy array) in the same order as in `cols_to_read`.''' arrays = [np.array([], dtype=np.float64) for i in range(len(cols_to_read))] for cur_segment in segments: start = cur_segment.first_el...
class C:
''' <caret> '
''
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
he code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class OperationListResult(Model): """The operation list response that contains all operations for Azure Container Instance service. :param value: The list of oper...
: {'key': 'value', 'type': '[Operation]'}, } def __init__(self, value=None): self.value = value
import autograd.numpy as np from autograd.scipy.misc import logsumexp from features import num_atom_features, num_bond_features from util import memoize, WeightsParser from mol_graph import graph_from_smiles_tuple, degrees from build_vanilla_net import build_fingerprint_deep_net, relu, batch_normalize def fast_array...
normalize=normalize) write_to_fingerprint(atom_features, num_layers) return sum(all_layer_fps), atom_act
ivations, array_rep def output_layer_fun(weights, smiles): output, _, _ = output_layer_fun_and_atom_activations(weights, smiles) return output def compute_atom_activations(weights, smiles): _, atom_activations, array_rep = output_layer_fun_and_atom_activations(weights, smiles) ...
ackwards(self, orm): # Deleting field 'DamageScenario.customlandusegeoimage' db.delete_column('lizard_damage_damagescenario', 'customlandusegeoimage_id') models = { 'lizard_damage.benefitscenario': { 'Meta': {'object_name': 'BenefitScenario'}, 'datetime_cre...
{'primary_key': 'True'}), 'landuse_slugs': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'max_height': ('djang
o.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'min_height': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'repairtime_...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tully.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 ...
o is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you "...
tivate a virtual environment?" ) raise execute_from_command_line(sys.argv)
Size(32, 32)) self.saveToolButton.setObjectName(_fromUtf8("saveToolButton")) self.openToolButton = QtGui.QToolButton(self.frame) self.openToolButton.setGeometry(QtCore.QRect(30, 0, 32, 32)) icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(_fromUtf8(":/open.png")), QtGui.Q...
(QtCore.QRect(0, 0, 32, 32)) icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap(_fromUtf8(":/new.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.newToolButton.setIcon(icon4) self.newToolButton.setIconSize(QtCore.QSize(32, 32)) self.newToolButton.setObjectName(_fromUtf8("n...
ntToolButton.setGeometry(QtCore.QRect(770, 0, 32, 32)) icon5 = QtGui.QIcon() icon5.addPixmap(QtGui.QPixmap(_fromUtf8(":/print.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.printToolButton.setIcon(icon5) self.printToolButton.setIconSize(QtCore.QSize(32, 32)) self.printToo...
# Copyright 2015, Google, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
e 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. import re from getting_started import ma
in def test_main(cloud_config, capsys): main(cloud_config.project) out, _ = capsys.readouterr() assert re.search(re.compile( r'Query Results:.hamlet', re.DOTALL), out)
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Netw
orks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License a
t # # 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 or implied. # See the License for the specific language governin...
""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """...
import botocore.session
session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = ...
## @package csnStandardModuleProject # Definition of the methods used for project configuration. # This should be the only CSnake import in a project configuration. import csnUtility import csnProject import csnBuild import os.path import inspect from csnProject import GenericProject class StandardModuleProject(Gener...
_modulesFolder - Folder containing subfolders with applications. _modules = List of subfolders of _modulesFolder that s
hould be processed. _pch - If not "", this is the C++ include file which is used for building a precompiled header file for each application. """ for module in _modules: moduleFolder = "%s/%s" % (_modulesFolder, module) sourceFiles = [] headerFiles = [] ...
# This file is part of the MapProxy project. # Copyright (C) 2010 Omniscale <http://omniscale.de> # # 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...
ither express or implied. # See the License for the specific language governing permissions and # limitations under the License. from mapproxy.util.collections import LRU, ImmutableDictList from nose.tools import eq_, raises class TestLRU(object): @raises(KeyError) def test_missing_ke
y(self): lru = LRU(10) lru['foo'] def test_contains(self): lru = LRU(10) lru['foo1'] = 1 assert 'foo1' in lru assert 'foo2' not in lru def test_repr(self): lru = LRU(10) lru['foo1'] = 1 assert 'size=10' in repr(lru) assert 'foo1'...
#!/usr/bin/env python ######################################### # # fasta2tax.py # ######################################## import sys,os import argparse import pymysql as MySQLdb import json py_pipeline_path = os.path.expanduser('~/programming/py_mbl_sequencing_pipeline') #my $rdpFile = "$inputfile.rdp"; print "...
_h->execute or die "Unable to execute query: $loadQuery
\n"; # # if ($dbh->err) { # if ($use_transactions) { # # Encapsulate the changes to these tables in a transaction... # my $query = "ROLLBACK"; # my $handle = $dbh->prepare($query) or die "Unable to prepare query: $query\n"; # $handle->execute or die "Unable to execute query: $query\...
""" Project ad
ditional elements """ from .menu_button impo
rt * from .new_key_qframe import *
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # This software is licensed as described in the README.rst and LICENSE # files, which you should have received as part of this distribution. import setuptools # noinspection PyPep8Naming from raspi_pir impo
rt __version__
as VERSION DEPS = ['RPi.Sensor>=0.5.3'] CLASSIFIERS = [ 'Environment :: Console', 'Intended Audience :: System Administrators', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Operating System :: Unix', 'Operating System :: POSIX :: Linux', 'License :: OSI App...
#!/usr/bin/python #requires the following: #sudo apt-get install curl #curl http://apt.wxwidgets.org/key.asc | apt-key add - #sudo apt-get update #sudo apt-get install python-wxgtk2.8 python-wxtools wx2.8-i18n #sudo apt-get install python-gdata import wx import os import sys def pinger(): f = os.popen('ping -c 1 go...
lf.panel,-1,(30,120),(540,100),uplist, wx.LB_EXTENDED | wx.LB_HSCROLL) wx.StaticText(self.panel,-1,'*Upload to these sites may NOT work at the moment; developers are trying to fix the issues',pos=(30,225),size=(540,50)) if self.check==1: self.button_browse_files = wx.Button(self.panel,-1,'Browse for files',p...
tton(self.panel,-1,'Login to Megaupload Account',pos=(190,270),size = (220,30)) self.Bind(wx.EVT_BUTTON,self.browsefiles,self.button_browse_files) else: self.button_upload = wx.Button(self.panel,-1,'Start Upload',pos=(30,270),size=(265,30)) self.button_login_mupload = wx.Button(self.panel,-1,'Login to Megaup...
#
for Python3 we need a fully qualified name import from mappyscript._mappyscript import version, version_number, load, loads, dumps, create_request, load_map_from_params, Layer, convert_sl
d
import os import pytest import numpy as np from imageio import imread def compare_2_images(validator_path, output_path): val_abs_path = os.path.join(os.path.dirname(__file__), validator_path) out_abs_path = os.path.join(os.path.dirname(__file__), output_path) val_img = imread(val_abs_path, pilmode='RGB')...
def test_main_flip_voc(cli_args_voc): """ TODO: Add images :param cli_args_voc: :return: """ from pspnet import main main(cli_args_voc) compare_2_images("pascal_voc_test_probs.jpg", "validators/pascal_voc_test_probs.jpg") compare_2_images("pascal_voc_test_seg.jpg", "validators/pasca...
_test_seg_read.jpg") clean_test_results("pascal_voc_test")
from django.db import models # from django.contrib.gis.geoip import GeoIP # # g = GeoIP() # Create your models here. clas
s TempMail(models.Model): mailfrom = models.EmailField() mailsubj = models.CharField(max_length=20) mailrcvd = models.DateTimeField() mailhdrs = models.CharField() class SavedMail(models.Model): mailrcvd = models.DateTimeField() mailhdrs = models.CharField() organization = models.ForeignKey...
ength=255) class Follower(models.Model): email = models.EmailField()
from django.contrib import admin from api.models import * admin.site.register(Question) admin.site.register(Answer) ad
min.site.register(Sighting) admin.site.register(Picture) admin.site.register(UserComment) admin
.site.register(ExpertComment) admin.site.register(SightingFAQ)
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import pytest import functools from io import BytesIO from devtools_testutils.aio import recorded_by_proxy_async from azure.core.exceptions import Servic...
ed_by_proxy_async async def test_identity_documen
t_bad_endpoint(self, formrecognizer_test_endpoint, formrecognizer_test_api_key, **kwargs): with open(self.identity_document_license_jpg, "rb") as fd: my_file = fd.read() with pytest.raises(ServiceRequestError): client = FormRecognizerClient("http://notreal.azure.com", AzureKeyCre...
self.browser_integration.port) def search(self, text, type, adv=False): """Search on the MusicBrainz website.""" lookup = self.get_file_lookup() getattr(lookup, type + "Search")(text, adv) def browser_lookup(self, item): """Lookup the object's metadata on the MusicBrainz ...
files = self.get_files_from_objects(objs) for file in f
iles: file.set_pending() if self.use_acoustid: self._acoustid.analyze(file, partial(file._lookup_finished, 'acoustid')) # ======================================================================= # Metadata-based lookups # =============================================...
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HMM9_if_IsolatedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HMM9_if_IsolatedLHS. """ # Flag this instance as c...
eter and returns the node corresponding to that label. """ #========================================
======================================= # This code is executed after the nodes in the LHS have been matched. # You can access a matched node labelled n by: PreNode('n'). # To access attribute x of node n, use: PreNode('n')['x']. # The given constraint must evaluate to a boolean expressi...
#!/usr/bin/env python import argpa
rse import logging import os import shutil import sys import glob # Location of saved templates SAVE_DIR = os.environ.get("RECYCLE_TEMPLATES_DIR", "~/.recycle") try: input = raw_input except NameError: pass def should_overwrite(typeOfThing, path): assert os.path.exists(path) nameOfThing = get_name(pa...
logging.debug("{} already exists. Asking to overwrite...".format(path)) res = "" while res != "y" and res != "n": prompt = "{0} {1} already exists. Do you want to replace it? " \ "(y/n) ".format(typeOfThing, nameOfThing) res = input(prompt) res = res.lower() if ...
# -*- coding: utf-8 -*- """ Ozone Bricklet Plugin Copyright (C) 2015 Olaf Lüke <olaf@tinkerforge.com> ozone.py: Ozone Bricklet Plugin Implementation 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; e...
top = True def destroy(self):
pass def get_url_part(self): return 'ozone' @staticmethod def has_device_identifier(device_identifier): return device_identifier == BrickletOzone.DEVICE_IDENTIFIER def get_current_value(self): return self.current_value def cb_ozone_concentration(self, ozone_concen...
#!/usr/bin/python import sys import time import datetime import re import ConfigParser import os from operator import attrgetter scriptdir = os.path.abspath(os.path.dirname(sys.argv[0])) conffile = scriptdir + "/ovirt-vm-rolling-snapshot.conf" Config = ConfigParser.ConfigParser() if not os.path.isfile(conffile): ...
time.sleep(5) sys.stdout.write('.') sys.stdout.flush() else:
print break for snapi in vm.get_snapshots().list(): snapi_id = snapi.get_id() if vm.snapshots.get(id=snapi_id).description == snap_description: snap_status = "ok" break ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2022 Pytroll developers # Author(s): # Adam Dybbroe <Firstname.Lastname @ smhi.se> # 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 Foundat...
the (non-static) config during processing.""" def setUp(self): self.config_complete = create_config_from_yaml(TEST_YAML_CONTENT_OK) @patch('aapp_runner.read_aapp_config.load_config_from_file') def test_check_if_scene_is_unique_return_value(self, config): """Test checking if the current sc...
rn_value = self.config_complete myfilename = "/tmp/mytestfile" aapp_run_config = AappRunnerConfig(myfilename, 'norrkoping', 'xl-band') aapp_config = AappL1Config(aapp_run_config.config, 'xl-band') aapp_config['platform_name'] = 'metop03' aapp_config['collection_area_id'] = 'euro...
from tests.test_helper import * from braintree.resource import Resource class TestResource(unittest.TestCase): def test_verify_keys_allows_wildcard_keys(self): signature = [ {"foo": [{"bar": ["__any_key__"]}]} ] params = { "foo[bar][lower]": "lowercase", ...
def test_verify_keys_works_with_arrays(self): signature = [ {"add_ons": [{"update": ["existing_id", "quantity"]}]} ] params = { "add_ons": { "update": [ { "existing_id": "foo", "quantity":...
} ] } } Resource.verify_keys(params, signature) @raises(KeyError) def test_verify_keys_raises_with_invalid_param_in_arrays(self): signature = [ {"add_ons": [{"update": ["existing_id", "quantity"]}]} ] params = ...
# ========================================================================= # Copyright 2012-present Yunify, Inc. # ------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the Licens...
return IaaSActionManager.get_valid_actions() elif service == 'qs': return QSActionManager.get_valid_actions() def get_action(service, action): if service == 'iaas': return Ia
aSActionManager.get_action(action) elif service == 'qs': return QSActionManager.get_action(action) def check_argument(args): if len(args) < 2: exit_due_to_invalid_service() if args[1].lower() in ('--version', '-v'): version = pkg_resources.require("qingcloud-cli")[0].version ...
# coding=utf-8 # # This file is part of SickGear. # # SickGear is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SickGear is distribu...
'href'].lstrip('/')), seeders)) except generic.HaltParseException: pass except Exception: logger.log(u'Failed to parse. Traceback: %s' % traceback.format_exc(), logger.ERROR) self._log_result(mode, len(items[mode]) - cnt, search_ur...
(key=lambda tup: tup[2], reverse=True) results += items[mode] return results def find_propers(self, search_date=datetime.datetime.today()): return self._find_propers(search_date) def _get_episode_search_strings(self, ep_obj, add_string='', **kwargs): return generic.Torr...
### # Copyright (c) 2004, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditi...
uld effect your configuration by manipulating t
he # registry as appropriate. from supybot.questions import expect, anything, something, yn conf.registerPlugin('MyPing', True) MyPing = conf.registerPlugin('MyPing') # This is where your configuration variables (if any) should go. For example: # conf.registerGlobalValue(MyPing, 'someConfigVariableName',...
import pf from Var import var import numpy,string from Glitch import Glitch """A faster version of nextTok(), using memory allocated (once only) using numpy, and using functions written in C. The slow, pure python module is NexusToken.py. This version is about twice as fast. Which one is used is under the control o...
' x1 NexusToken2.nextTok() here. savedCommentLen=%i' % nt.savedCommentLen[0] if nt.savedCommentLen[0]: ret = nt.embeddedComment[:int(nt.savedCommentLen[0])].tostring() nt.savedCommentLen[0] = 0 return ret
pf.nextToken(nt.nexusToken, flob) #print ' x2 tokLen = %i, embeddedCommentLen[0] = %i' % (nt.tokLen[0], nt.embeddedCommentLen[0]) if nt.embeddedCommentLen[0]: ret = nt.embeddedComment[:int(nt.embeddedCommentLen[0])].tostring() nt.embeddedCommentLen[0] = 0 #nt.previousEmbeddedComment =...
import sqlite3 from sklearn import linear_model import numpy as np import pandas as pd import datetime import sys conn = sqlite3.connect(sys.argv[1]) c = conn.cursor(); c.execute("select _id, name from tracks") rows = c.fetchall() track_names = pd.DataFrame([{'track_name': row[1]} for row in rows]) track_ids = [int...
: print "Error constructing date from", row x = -(row_date - day).days y = track_ids.index(int(row[1])) if x < n: ticktrix[x, y] = 1 return ticktrix last_day -= datetime.timedelta(1) print "Fitting for d
ay:", last_day my_window = window(last_day) target_data = my_window[0,:].T training_data = my_window[1:,:].T print "Target:", target_data.shape print target_data print "Training:", training_data.shape print training_data reg = linear_model.LinearRegression() reg.fit(training_data, target_data) print "Coefficents:",...
# -*-
coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('deals', '0002_advertiser_logo'), ] operations = [ migrations.RemoveField( model_name='advertiser', name='...
# -*- coding: utf-8 -*- ############################################################################### # # UpdateSigningCertificate # Changes the status of the specified signing certificate from active to disabled, or vice versa. This action can be used to disable a user's signing certificate as part of a certificate...
alues are "xml" (the default) and "json".) """ super(UpdateSigningCertificateInputSet, self)._set_input('ResponseFormat', value) def set_Status(self, value): """ Set the value of the Status input for this Choreo. ((required, string) The status you want to assign to the certificate. A...
d.) """ super(UpdateSigningCertificateInputSet, self)._set_input('Status', value) def set_UserName(self, value): """ Set the value of the UserName input for this Choreo. ((optional, string) Name of the user the signing certificate belongs to.) """ super(UpdateSigningC...
from __future__ import print_function, unicode_literals import inspect import six from django import forms from django.forms.forms import DeclarativeFieldsMetaclass from rest_framework import serializers from .. import fields from ..utils import ( initialize_class_using_reference_object, reduce_attr_dict_from...
a'] = options = SerializerFormOptions(meta, name=name) new_attrs = cls.get_form_fields_from_serializer(bases, options) # attrs should take priority in case a specific field is overwritten new_attrs.update(attrs) return super(SerializerFormMeta, cls).__new__(cls, name, bases, new_attrs)...
pping = reduce_attr_dict_from_base_classes( bases, lambda i: getattr(getattr(i, '_meta', None), 'field_mapping', {}), SERIALIZER_FORM_FIELD_MAPPING ) mapping.update(options.field_mapping) return mapping @classmethod def get_form_fields_from_serializer...
import pytest from diofant import Integer, SympifyError from diofant.core.operations import AssocOp, LatticeOp __all__ = () class MyMul(AssocOp): identity = Integer(1) def test_flatten(): assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3) class Join(LatticeOp): """Simplest possible Lattice class.""" ...
: pytest.raises(SympifyError, lambda: Join(object)) assert Join(0, object) == 0 def te
st_lattice_print(): assert str(Join(5, 4, 3, 2)) == 'Join(2, 3, 4, 5)' def test_lattice_make_args(): assert Join.make_args(0) == {0} assert Join.make_args(1) == {1} assert Join.make_args(Join(2, 3, 4)) == {Integer(2), Integer(3), Integer(4)}
default_a
pp_con
fig = 'daiquiri.query.apps.QueryConfig'
{ 'resultType': # category name { 'failed': 29, # category value and total number found of that value 'failure-ignored': 948, 'no-comparison': 4502, 'succeeded': 38609, }, 'builder': { 'Test...
r_dict is not None: fullpath = os.path.join(dirpath, matching_filename) gm_json.WriteToFile(per_builder
_dict, fullpath) actual_builders_written.append(builder) # Check: did we write out the set of per-builder dictionaries we # expected to? expected_builders_written = sorted(meta_dict.keys()) actual_builders_written.sort() if expected_builders_written != actual_builders_written: raise...
########################################################################## # # Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redi...
TABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUD
ING, 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 WAY OUT OF THE USE OF THIS # SOFTWA...
xpress or # implied warranties, including, but not limited to, the implied # warranties of merchantability and fitness for a particular purpose # are disclaimed. In no event shall the author be liable for any # direct, indirect, incidental, special, exemplary, or consequential # damages (including, but not limited to,...
_pre` controls how many tokens before an invalid token the parser considers when trying to repair the input. `errcorr_post` controls how far beyond an invalid token the parser reads when evaluating the quality of an attempted repair. """ self.max_err = max_err sel...
eaves(tree): """Iterate over the leaves of a parse tree. This function can be used to reconstruct the input from a parse tree. """ if tree[0] in Parser.terminals: yield tree else: for x in tree[1:]: for t in Parser.leaves(x): ...
"""Trivial Interfaces and Adaptation from PyProtocols. This package is a subset of the files from Phillip J. Eby's PyProtocols package. They are only included here to help
remove dependencies on ex
ternal packages from the Traits package. The code has been reorganized to address circular imports that were discovered when explicit relative imports were added. """
# -*- coding: utf-8 -*- # # Minimum amount of se
ttings to run the googlytics test suite # # googlytics options are often overriden during tests GOOGLE_ANALYTICS_KEY = 'U-TEST-XXX' DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'googlytics_test.sqlite3' } } INSTALLED_APPS = ( 'django.contrib.aut...
lytics.context_processors.googlytics', )
# -*- coding: utf-8 -*- # # 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 ...
s.path.isfile(log_filename)) self.assertTrue(log_filename.endswith("2.log"), log_filename) logger.info("Test") # Return value of read must be a list. logs = file_handler.read(ti) self.assertTrue(isinstance(logs, list)) # Logs for running tasks should show up too. ...
Remove the generated tmp log file. os.remove(log_filename) class TestFilenameRendering(unittest.TestCase): def setUp(self): dag = DAG('dag_for_testing_filename_rendering', start_date=DEFAULT_DATE) task = DummyOperator(task_id='task_for_testing_filename_rendering', dag=dag) self.ti...
#!/usr/bin/env python # Written by Filippo Bonazzi <f.bonazzi@davide.it> 2016 #
# Convert an integer from its decimal representation into its hexadecimal # representation. # TODO: add argparse import sys import math s = "".join(sys.argv[1].split()) for c in s: if c not in "1234567890": print("Bad string \"{}\"".format(s)) sys.exit(1)
a = 0 for i in range(0, len(s)): a += int(s[len(s) - i - 1]) * int(math.pow(10, i)) print("{0:#x}".format(a))
""" Application-class that implements pyFoamChangeGGIBoundary.py Modification of GGI and cyclicGGI interface parameters in constant/polymesh/boundary file. Author: Martin Beaudoin, Hydro-Quebec, 2009. All rights reserved """ from PyFoam.Applications.PyFoamApplication import PyFoamApplication from PyFoam.RunDicti...
t", default=None, help='separation offset for cyclicGgi') self.parser.add_option("--test", action="store_true", default=False, dest="test", ...
def run(self): fName=self.parser.getArgs()[0] bName=self.parser.getArgs()[1] boundary=ParsedParameterFile(path.join(".",fName,"constant","polyMesh","boundary"),debug=False,boundaryDict=True) bnd=boundary.content if type(bnd)!=list: self.error("Problem with bounda...
(-?\d+|-?\d+\.(\d+))\]", re.I ) floatMatch = floatRE.match(self.replacement) self._floatMatch = floatMatch if self._stringMatch is not None: stringMatch = self._stringMatch else: stringRE = re.compile(r"string\((\d+...
% stack ) floatret = round(floatret * rateFactor, significance) floatret = str(floatret) return floatret else: logger.error( ...
end float %s; will not replace" % (startFloat, endFloat) ) return old except ValueError: logger.error( "Could not parse float[%s:%s]" % (floatMatch.group(1), fl...
lf): xpub_hot = self.wallet.master_public_keys["x1/"] xpub_cold = self.wallet.master_public_keys["x2/"] long_id = self.make_long_id(xpub_hot, xpub_cold) short_id = hashlib.sha256(long_id).hexdigest() return long_id, short_id def make_xpub(self, xpub, s): _, _, _, c, ...
elf.auth_code = None return self.auth_code = self.auth_dialog() @hook def before_send(self):
# request billing info before forming the transaction self.billing_info = None self.waiting_dialog = WaitingDialog(self.window, 'please wait...', self.request_billing_info) self.waiting_dialog.start() self.waiting_dialog.wait() if self.billing_info is None: s...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-02 18:22 from __future__ import unicode_literals import django.contrib.auth.models import django.core.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependenc...
roups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific pe
rmissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name_plural': 'users', 'abstract': False, 'verbose_name': 'user', }, ...
from lightbulb.api.api_native import LightBulb import base64 lightbulbapp = LightBulb() path = "/test/env/bin/lightbulb" #Path to binary configuration_A = {'TESTS_FILE_TYPE': 'None', 'ALPHABET': '32-57,58-64,65-126', 'SEED_FILE_TYPE': 'FLEX', 'TESTS_FILE': 'None','DFA1_MINUS_DFA2': 'True', 'SAVE': 'False', 'HANDLER...
OWSERPARSE': 'True', 'DELAY': '50', '
HOST': 'localhost'} handlerconfig_B = {'URL': 'http://127.0.0.1/~fishingspot/securitycheck/index.php', 'BLOCK':'Impact', 'REQUEST_TYPE':'GET','PARAM':'input','BYPASS':'None', 'PROXY_SCHEME': 'None', 'PROXY_HOST': 'None', 'PROXY_PORT': 'None', 'PROXY_USERNAME': 'None', 'PROXY_PASSWORD': 'None','USER_AGENT': "Mozilla/5.0...
# =============================================================================== # Copyright 2014 Jake Ross # # 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...
, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =============================================================================== # ========
===== enthought library imports ======================= from __future__ import absolute_import from PySide import QtGui, QtCore from traits.trait_types import Event from traitsui.api import View, UItem from traitsui.basic_editor_factory import BasicEditorFactory from traitsui.editors.api import TableEditor from traitsu...
#!/usr/bin/python2.7 import sys import csv import yaml import codecs TO_BE_TRANSLATED_MARK = "***TO BE TRANSLATED***" def collect(result, node, prefix=None): for key,value in n
ode.items(): new_prefix = (key if prefix == None else prefix + "." + key) if isinstance(value, dict): collect(result, value, new_prefix) else: result[new_prefix] = value
def collect_old_csv(filename): result = {} reader = csv.reader(open(filename)) for row in reader: if TO_BE_TRANSLATED_MARK not in row[1]: result[row[0]] = row[1].decode("utf-8") return result def flatten(namespace=None,old_csv=None): namespace = "" if namespace == None else na...
es are currently unreachable. After you have received a ConsistencyLostError, you can either wait for a sufficiently up-to-date replica to become reachable in which case the session can be continued or you can reset the session by calling the reset() method. If you have called the reset() method, a ...
contain any data members. ConsistencyLostError: if the session guarantees have been lost. """ return self._invoke_internal(pn_counter_get_codec) def get_and_add(self, delta): """Adds the given value to the current value and returns the previous value. Args: d...
NoDataMemberInClusterError: if the cluster does not contain any data members. ConsistencyLostError: if the session guarantees have been lost. """ return self._invoke_internal(pn_counter_add_codec, delta=delta, get_before_update=True) def add_and_get(self, delta): """Adds ...
import os import unittest import moderngl import pycodestyle class TestCase(unittest.TestCase): def test_style(self): config_file = os.path.join(os.path.dirname(__file__), '..
', 'tox.ini') style = pycodestyle.StyleGuide(config_file=config_file, ignore='E402') check = style.check_files([ os.path.join(os.path.dirname(__file__), '../moderngl/__init__.py'), os.path.join(os.path.dirname(
__file__), '../moderngl/__main__.py'), ]) self.assertEqual(check.total_errors, 0) if __name__ == '__main__': unittest.main()
ord = input(color.BLEU + "password > " + color.DARKROUGE + "new password > " + color.ENDC) error = Sub_Menu.PassHandle(crypt, password) print (color.VERT + "[+]" + color.ENDC + " changing the password to " + color.VERT + "'" + password + "'" + color.E...
print(color.VERT + "[+]" + color.ENDC + " going back to main menu.") time.sleep(0.3) return dhcp else: print(color.ROUGE + "[*]" + color.ENDC + " please enter a valid op
tion!") #show the menu for chosing dns option. The dns object can be change to on or N/A. # I am planing to give the user the choice to put their dns redirect entry directly # in the program and in the config file. def dnsMenu(dns): while Tru...
""" ==================================================== Shuffle channels' data in the time domain and plot. ==================================================== """ # Author: Eberhard Eich # Praveen Sripad # # License: BSD (3-clause) import numpy as np import os.path as op import mne from jumeg.j...
False, eog=False, stim=False) figraw1 = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,0,1), picks=megpick) axisraw1 = figraw1.gca() axisraw1.set_ylim([-300., -250.]) figshfl1 = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,0,1), picks=megpick) axisshfl1 = figshfl1.gca() ...
hgpick) axisraw2 = figraw2.gca() axisraw2.set_ylim([-300., -250.]) figshfl2 = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,1,0), picks=megnochgpick) axisshfl2 = figshfl2.gca() axisshfl2.set_ylim([-300., -250.])
# -*- coding: utf-8 -*- # entry.py, part for evparse : EisF Video Parse, evdh Video Parse. # entry: evparse/lib/hunantv # version 0.1.0.0 test201505151816 # author sceext <sceext@foxmail.com> 2009EisF2015, 2015.05. # copyright 2015 sceext # # This is FREE SOFTWARE, released under GNU GPLv3+ # please see README.md an...
_URL, url_to): raise error.NotSupportURLError('not support this url', url_to) # create evinfo evinfo = {} evinfo['info'] = {} evinfo['video'] = [] # add some base info evinfo['info']['url'] = url_to evinfo['info']['site'] = 'hunantv' # get vid vid_info = get_vid(url_to) #...
\" ') # get base, more info info, more = get_base_info.get_info(vid_info, flag_debug=etc['flag_debug']) # add more info evinfo['info']['title'] = more['title'] evinfo['info']['title_sub'] = more['sub_title'] evinfo['info']['title_short'] = more['short_title'] evinfo['info']['title_no'] ...
. If the range is not known yet, the -1 is returned""" return self.m def get_ratio(self): """Return ratio c between keyset and the size of the memory""" return self.ratio def set_ratio(self,ratio): """sets the ration and therefore size of the data structure of the PHF""" ...
r the given limit self.ratio = (3.0*self.limit)/len(key_set) def is_key_set(self): """This function return info
rmation, if the set of keys is prepared for the generation of the PHF""" return self.known_keys def _found_graph(self): """This is internal function. It generate random hypergraph according to the specification in the bdz class. It returns a queue of the edge and changes internal datastructure of B...
#!/usr/bin/env python2 #
-*- coding: utf-8 -*- """ Created on Tue Jul 11 20:47:53 2017 @author: fernando """ import pandas as pd import matplotlib import matplotlib.pyplot as plt plt.style.use('ggplot') df = pd.read_csv("/home/fernando/CoursePythonDS/DAT210x/Module3/Datasets/wheat.data") print df.describe() df[df.groove>5].asymmetry.plot...
plt.show()
from pypers.core.step import Step from pypers.steps.mothur import Mothur import os import json import re import glob class MothurSummarySeqs(Mothur): """ Summarizes the quality of sequences in an unaligned or aligned fasta-formatted sequence file. """ spec = { 'name' : 'MothurSummarySeqs', ...
'descr': 'output summary filename' }, {
'name' : 'output_log', 'type' : 'file', 'value' : '*.log.txt', 'descr': 'output summary logfile with tile summary table' } ] }, 'requirements' : { 'cpus' : '...
import pytest import datetime import os from helpers import ensure_dir def pytest_configure(config): if not hasattr(config, 'input'): current_day = '{:%Y_%m_%d_%H_%S}'.format(datetime.datetime.now()) ensure_dir(os.path.join(os.path.dirname(__file__), 'input', current_day)) result_dir = os...
self.logcat_dir = logcat_dir @pytest.fixture(scope='function') def device_logger(request): logcat_dir = request.config.logcat_dir screenshot_dir = request.config.screen
_shot_dir return DeviceLogger(logcat_dir, screenshot_dir)
# import asyncio # # async def compute(x, y): # print("Compute %s + %s ..." % (x, y)) # await asyncio.sleep(1.0) # return x + y # # async def print_sum(x, y): # for i in range(10): # result = await compute(x, y) # print("%s + %s = %s" % (x
, y, result)) # # loop = asyncio.get_event_loop() # loop.run_until_complete(print_sum(1,2)) # asyncio.ensure_future(print_sum(1, 2)) # asyncio.ensure_future(print_sum(3, 4)) # asyncio.ensure_future(print_sum(5, 6)) # loop.run_forever() import asyncio async def display_date(who, num): i = 0 while True: ...
await asyncio.sleep(1) i += 1 loop = asyncio.get_event_loop() asyncio.ensure_future(display_date('AAA', 4)) asyncio.ensure_future(display_date('BBB', 6)) loop.run_forever()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.core.validators import django.contrib.auth.models class Migration(migrations.Migration): dependencies = [ ('core', '0011_atmosphere_user_manager_update'), ] operations = [ ...
ects', to='core.Application'
, blank=True), ), migrations.AlterField( model_name='project', name='instances', field=models.ManyToManyField( related_name='projects', to='core.Instance', blank=True), ), migrations.AlterField( model_name='project', name='volumes', field=models.ManyToManyField( r...
from setuptools import setup version = '1.4' testing_extras = ['nose', 'coverage'] docs_extras = ['Sphinx'] setup( name='WebOb', version=version, description="WSGI request and response object", long_description="""\ WebOb provides wrappers around the WSGI request environment, and an object to help c...
, ], keywords='wsgi request web http', au
thor='Ian Bicking', author_email='ianb@colorstudy.com', maintainer='Pylons Project', url='http://webob.org/', license='MIT', packages=['webob'], zip_safe=True, test_suite='nose.collector', tests_require=['nose'], extras_require = { 'testing':testing_extras, 'docs':doc...
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=missing-docstring
import os import codecs from setuptools import setup def read(fname): file_path = os
.path.join(os.path.dirname(__file__), fname) return codecs.open(file_path, encoding='utf-8').read() setup( name='pytest-typehints', version='0.1.0', author='Edward Dunn Ekelund', author_email='edward.ekelund@gmail.com', maintainer='Edward Dunn Ekelund', maintainer_email='edward.ekelund@gma...
""" Copyright (C) 2014 Vahid Rafiei (@vahid_r) 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 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 Genera...
return result def read_timestamp(self): """Read and AMQP timestamp, which is a 64-bit integer representing seconds since the Unix epoch in 1-second resolution. Return as a Python datetime.datetime object, expressed as localtime. """ return datetime.utcfromtimestamp...
v, (list, tuple)): self.write(b'A') self.write_array(v) elif v is None: self.write(b'V') else: err = (ILLEGAL_TABLE_TYPE_WITH_KEY.format(type(v), k, v) if k
else ILLEGAL_TABLE_TYPE.format(type(v), v)) raise FrameSyntaxError(err) def write_array(self, a): array_data = AMQPWriter() for v in a: array_data.write_item(v) array_data = array_data.getvalue() self.write_long(len(array_data)) self.out.write(ar...
elif origin in ["programmer", "developer", "source code"]: devcomments = super().getnotes("developer") autocomments = self.getautomaticcomments() if devcomments == autocomments or autocomments.find(devcomments) >= 0: devcomments = "" elif devcomments.find(...
turn group def hasplural(self): return self.xmlelement.tag == self.namespaced("group") class PoXliffFile(xliff.xlifffile, poheader.poheader): """a file for the po variant of Xliff files""" UnitClass = PoXliffUnit def __init__(self, *args, **kwargs): if "sourcelanguage" not in kwargs...
node(self, filename, sourcelanguage="en-US", datatype="po"): # Let's ignore the sourcelanguage parameter opting for the internal # one. PO files will probably be one language return super().createfilenode( filename, sourcelanguage=self.sourcelanguage, datatype="po" ) def...
# encoding: utf-8 from bs4 import BeautifulSoup from okscraper.base import BaseScraper from okscraper.sources import UrlSource, ScraperSource from okscraper.storages import ListStorage, DictStorage from lobbyists.models import LobbyistHistory, Lobbyist, LobbyistData, LobbyistRepresent, LobbyistRepresentData from perso...
st_data(lobbyist) except ObjectDoesNotExist: last_lobbyist_data = None if last_lobbyist_data is not None: for key in self._get_data_keys(): if data[key] != getattr(last_lobbyis
t_data, key): last_lobbyist_data = None break if last_lobbyist_data is not None: represent_ids = sorted(data['represents'], key=lambda represent: represent.id) last_represent_ids = sorted(last_lobbyist_data.represents.all(), key=lambda represent: r...