prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from sevenbridges.meta.resource import Resource from sevenbridges.meta.fields import StringField, DictField class BatchGroup(Resource): """ Batch group for a b
atch task. Represents the group that is assigned to the child task from the batching criteria that was used when the task was started. """ value = StringField(read_only=True) fields = DictField(re
ad_only=True) def __str__(self): return '<Batch group>'
# from django.shortcuts import render, get_object_or_404 # from .models import Album, Song # def index(request): # all_albums = Album.objects.all() # context = { # 'all_albums':all_
albums, # } # retu
rn render(request, 'music/index.html', context) # def detail(request, album_id): # album = get_object_or_404(Album, pk=album_id) # return render(request, 'music/detail.html', {'album': album}) # def favourite(request, album_id): # album = get_object_or_404(Album, pk=album_id) # try: ...
import sys from logging import warning from glob import iglob import json import os import shutil from ..common import chdir, run from .cache import cache_specs from .dirs import get_specs_dir def load_all_specs(*, basedir=get_specs_dir(), skip_update_check=True): os.makedirs(basedir, exist_ok=True) if not ...
es found - Updating", file=sys.stderr) with chdir(basedir): ru
n(['git', 'pull', 'origin', 'master']) # the repo has a /specs folder basedir = os.path.join(basedir, 'specs') cache_specs(basedir) spec_files = iglob(os.path.join(basedir, '_cache', '*.json')) # load_spec returns a (name, spec) tuple, so we just let the dict() constructor # turn that into t...
from
django.apps import AppConfig class MainConfig(AppConfig): name =
'main'
import unittest from chat.commands.commandlist import CommandList from chat.command import Command from tests.structs.dummychat import DummyChat class TestCommands(unittest.TestCase): def setUp(self): self.chat = DummyChat() def test_
get(self): command = CommandList.get('help', s
elf.chat, 'message') self.assertTrue(command and isinstance(command, Command), 'Command get failed') def test_validate(self): fail_msg = 'Command validate failed' self.assertTrue(CommandList.validate('help'), fail_msg) self.assertTrue(CommandList.validate('!help'), fail_msg) ...
class TestRailTestCase: def _
_init__(self, title, section, suite, steps): self.title = title self.section_name = section self.suite_name = suite self.steps = steps self.type_id = 1 self.priority_id = 4 def to_json_dict(self): return { 'title': self.title, 'type_id...
y_id': self.priority_id, 'custom_steps_separated': self.steps }
""" Tools for sending email. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module # Imported for backwards compatibility, and for the sake # of a cleaner namespace. These symbols used to be in # django/core/mail.py before the int...
ll see the other recipients in the 'To' field. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_passwo
rd is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. """ connection = connection or get_connection(username=auth_user, password=auth_pass...
port': raise ImportError, 'test_support must be imported from the test package' import sys class Error(Exception): """Base class for regression test exceptions.""" class TestFailed(Error): """Test failed.""" class TestSkipped(Error): """Test skipped. This can be raised to indicate that a test w...
'Unicode filename tests may not be effective' \ % TESTFN_UNICODE_UNENCODEABLE # Make sure we can write to TESTFN, try in /tmp if we can't fp = None try: fp = open(TESTFN, 'w+') except IOError: TMP_TESTFN = os.path.join('/tmp', TESTFN) try: fp = open(TMP_TESTFN, 'w+')...
TESTFN = TMP_TESTFN del TMP_TESTFN except IOError: print ('WARNING: tests will fail, unable to write to: %s or %s' % (TESTFN, TMP_TESTFN)) if fp is not None: fp.close() unlink(TESTFN) del os, fp def findfile(file, here=__file__): """Try to find a file on sys.path and...
import mock import lxml.etree as ET from .utils import make_cobertura def test_parse_path(): from pycobertura import Cobertura xml_path = 'foo.xml' with mock.patch('pycobertura.cobertura.os.path.exists', return_value=True): with mock.patch('pycobertura.cobertura.ET.parse') as mock_parse: ...
), (3, '\n', None), (4, 'def foobarbaz():\n', False), (5, ' a = 1 + 3\n', False), (6, ' pass\n', False) ], } for class_name in cobertura.classes(): assert cobertura.class_source(class_name) == \ expected
_sources[class_name]
from optparse import make_option from django.core.management.base import BaseCommand from crits.core.mongo_tools import mongo_connector import pprint class Command(BaseCommand): """ Gets a count of indicator types and object types in CRITs """ help = "Gets a count of indicator types and object type...
_per_collection: for collection in self.all_object_collections: print "OBJECT TYPES FOR COLLECTION: [%s]" % collection.upper() if len(results[collection]['re
sult']) != 0: pp.pprint(results[collection]['result']) else: print "None found." print else: all_obj_types = {} for collection in self.all_object_collections: collection_results = results[collection...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.backend.j...
main=self.get_options().main, jvm_options=jvm_options, args=self.args) except KeyboardInterrupt:
# TODO(John Sirois): Confirm with Steve Gury that finally does not work on mac and an # explicit catch of KeyboardInterrupt is required. pass
e if self.__move_mode != 'vertical': new_time = self.track.xToTime(pos.x()) else: new_time = None if self.__move_mode != 'horizontal': new_value = self.track.yToValue(pos.y()) else: new_value = None ...
nge: music.PropertyValueChange[float]) -> None: self.__pos = QtCore.QPoint( self.__pos.x(), self.__track_editor.valueToY(change.new_value)) self.__track_editor.update() @property def index(self) -> int: return self.__point.index @property def point(self)...
def time(self) -> audioproc.MusicalTime: return self.__point.time def pos(self) -> QtCore.QPoint: return self.__pos def setPos(self, pos: QtCore.QPoint) -> None: if pos is None: self.__pos = QtCore.QPoint( self.__track_editor.timeToX(self.__point.time), ...
# -*- coding: utf-8 -*- # Copyright 2015 AvanzOsc (http://www.avanzosc.es) # Copyright 2015-2017 - Pedro M. Baeza <pedro.baeza@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) { "name": "Procurement Purchas
e No Grouping", "version": "10.0.1.0.0", "author": "AvanzOSC," "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/purchase-workflow",
"category": "Procurements", "depends": [ 'purchase', 'procurement', ], "data": [ 'views/product_category_view.xml', ], 'installable': True, 'license': 'AGPL-3', }
# Copyright 2018 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 a...
## Train and Export Model def train_and_export_model(train_data, train_labels): model_dir = os.path.join(MODELS_LOCATION, MODEL_NAME) hparams = tf.contrib.training.HParams( batch_size=100, hidden_units=[512, 512]
, num_conv_layers=3, init_filters=64, dropout=0.2, max_training_steps=50, eval_throttle_secs=10, learning_rate=1e-3, debug=True ) run_config = tf.estimator.RunConfig( tf_random_seed=19830610, save_checkpoints_steps=1000, keep_checkpoint_max=3, model...
# Copyright 2015 Dell 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 agree...
# Find our server. server = api.find_server(initiator_name) # No? Create it. if server is None: server = api.create_server(initiator_name) # Find the volume on the storage center. scvolume
= api.find_volume(volume_name) # if we have a server and a volume lets bring them together. if server is not None and scvolume is not None: mapping = api.map_volume(scvolume, server) if mapping is not N...
from pytest import fixture from itertools i
mport combinations import msgpack as pymsgpack values = [ 42, 7, 3.14, 2.71, 'lorem', 'ipsum', True, False, None, b'lorem', b'ipsum', [], [ 'lorem', 42, 3.14, True, None, ['ipsum']], dict(), { 'lorem': 'ipsum', 'dolor': 42, 'sit': 3.1
4, 'amet': [ True, None], 'consectetur':{ 'adipisicing': 'elit'}}] pairs = tuple(combinations(values, 2)) @fixture def cxxjson(): from cxx import json return json @fixture def cxxmsgpack(): from cxx import msgpack return msgpack
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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 S...
[ ('posix', os.name != 'posix', "Requires a POSIX os"), ('windows', os.name != 'nt', "Requires Windows"), ('linux', not sys.platform.startswith('linux'), "Requires Linux"), ('mac', sys.platform != 'darwin', "Requires macOS"), ('not_mac', sys.platform == 'darwin', "Skipped on mac...
ttr(sys, 'frozen', False), "Can only run when frozen"), ('ci', 'CI' not in os.environ, "Only runs on CI."), ('issue2478', os.name == 'nt' and config.webengine, "Broken with QtWebEngine on Windows"), ] for searched_marker, condition, default_reason in markers: marker...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
T_2", "dag_id": "TEST_DAG_ID", "task_id": "TEST_TASK_ID", "execution_date": self.default_time, "owner": 'airflow', "when": self.default_time2,
"extra": None, }, ], "total_entries": 2, }, )
lf._autoname) def _register_keybindings(self): """Register accelerators for static labels that must change the focus""" newId_t = wx.NewId() newId_n = wx.NewId() newId_a = wx.NewId() newId_d = wx.NewId() newId_o = wx.NewId() self.Bind(wx.EVT_MENU, self.OnActi...
ray.IsChecked(), arraysize=asize ) else: self._typei = model.cc.typeinst( type=self._types[typename], const=self.m_const.IsChecked(), ptr=self.m_ptr.IsChecked(), ref=self.m_ref...
e.IsChecked(), ptrptr=self.m_pptr.IsChecked(), constptr=self.m_constptr.IsChecked(), array=self.m_array.IsChecked(), arraysize=asize ) self._bitField = self.m_checkBox51.IsChecked() if self._bitField is True: ...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
self._rpc = RPCSession( _rpc_connect(self.session_name, self.transport.write, self.transport.read) ) self.context = self._rpc.cpu
(0) return self def __exit__(self, exc_type, exc_value, exc_traceback): """Tear down this session and associated RPC session resources.""" self.transport.__exit__(exc_type, exc_value, exc_traceback) def create_local_graph_runtime(graph_json_str, mod, ctx): """Create a local graph runt...
one: b_values = numpy.zeros((n_out,), dtype=theano.config.floatX) b = theano.shared(value=b_values, name='b', borrow=True) self.W = W self.b = b lin_output = T.dot(input, self.W) + self.b self.output = ( lin_output if activation is None e...
f.hiddenLayer = HiddenLayer( rng=rng, input=input, n_in=n_in, n_out=n_hidden, activation=T.tanh ) # The logistic regression
layer gets as input the hidden units # of the hidden layer self.logRegressionLayer = LogisticRegression( input=self.hiddenLayer.output, n_in=n_hidden, n_out=n_out ) # end-snippet-2 start-snippet-3 # L1 norm ; one regularization option is to enf...
import pytest import requests import time from threading import Thread from bottle import default_app, WSGIRefServer from tomviz.acquisition import server class Server(Thread): def __init__(self, dev=False, port=9999): super(Server, self).__init__() self.host = 'localhost' self.port = por...
shutdown() # Force the socket to close so we can reuse the same port self._server.srv.socket.close() @pytest.fixture(scope="module") def acquisition_server(): srv = Server() srv.start() yield srv srv.stop() srv.join() @pytest.fixture(scope="module") def acquisition_dev_server(): ...
998) srv.start() yield srv srv.stop() srv.join()
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 ...
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. """Compare a txt file of predictions with gold targets from a TSV file.""" from absl import app from absl import flags fro...
return "{%s}" % ", ".join(items) def assert_instance(obj, class_, label): """Raises ArgumentError when `obj` is not instance of `cls`""" if not isinstance(obj, class_): raise ModelInconsistencyError("%s should be sublcass of %s, " "provided: %s" % (label, ...
name) except ImportError: return MissingPackage(name, feature, source, comment) def expand_dictionary(record, separator = '.'): """Return expanded dictionary: treat keys are paths separated by `separator`, create sub-dictionaries as necessa
ry""" result = {} for key, value in record.items(): current = result path = key.split(separator) for part in path[:-1]: if part not in current: current[part] = {} current = current[part] current[path[-1]] = value return result def loc...
import math class P4(object): def p4(self): '''4-momentum, px, py, pz, E''' return self._tlv def p3(self): '''3-momentum px, py, pz''' return self._tlv.Vect() def e(self): '''energy''' return self._tlv.E() def pt(self): '''transverse momentum ...
theta = pi/2 -> 0 theta = pi -> eta = -inf ''
' return self._tlv.Eta() def phi(self): '''azymuthal angle (from x axis, in the transverse plane)''' return self._tlv.Phi() def m(self): '''mass''' return self._tlv.M() def __str__(self): return 'pt = {e:5.1f}, e = {e:5.1f}, eta = {eta:5.2f}, theta...
from django.conf.urls import url from .viewsets import Bo
okmarkViewSet bookmark_list = BookmarkViewSet.as_view({ 'get': 'list', 'post': 'create' }) bookmark_detail = BookmarkViewSet.as_view({ 'get': 'retrieve', 'patch': 'update', 'delete': 'destroy' }) urlpatterns = [ url(r'^bookmarks/$', bookmark_list, name='bookmarks'), url(r'^bookmarks/(?P<p...
), ]
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2018 Dell EMC Inc. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], ...
tract proper URI response = self.get_request(self.root_uri + bios_uri) if response['ret'] is False: return response result['ret'] = True data = response['data'] set_bios_attr_uri = data["@Redfish.Settings"]["SettingsObject"][
"@odata.id"] payload = {"TargetSettingsURI": set_bios_attr_uri} response = self.post_request( self.root_uri + self.manager_uri + "/" + jobs, payload, HEADERS) if response['ret'] is False: return response response_output = response['resp']....
# -*- coding: utf-8 -*- # Copyright 2015 Eficent - Jordi Ballester Alomar # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AnalyticAccountOpen(models.TransientModel): _name = 'analytic.account.ope
n' _descript
ion = 'Open single analytic account' analytic_account_id = fields.Many2one( 'account.analytic.account', 'Analytic Account', required=True ) include_child = fields.Boolean( 'Include child accounts', default=True ) @api.model def _get_child_analytic_accoun...
# -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2009 Philip Peitsch <philip.peitsch@gmail.com> #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed ...
outHudsonnotifierDialog instance directly. """ #look for the ui file that describes the ui ui_filename = os.path.join(getdatapath(), 'ui', 'AboutHudsonnotifierDialog.ui') if not os.path.exists(ui_filename): ui_filename = None builder = gtk.Builder() builder.add_from_file(ui_filena...
_name__ == "__main__": dialog = NewAboutHudsonnotifierDialog() dialog.show() gtk.main()
self.source is None: mod_type = self.etc[2] if mod_type==imp.PY_SOURCE: self._reopen() try: self.source = self.file.read() finally: self.file.close() elif mod_type==imp.PY_COMPILED: ...
cause a visible difference in behaviour, there must be a module or package name that is accessible via both sys.path and one of the non PEP 302 file system mechanisms. In this case, the emulation will find the form
er version, while the builtin import mechanism will find the latter. Items of the following types can be affected by this discrepancy: imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY """ if fullname.startswith('.'): raise ImportError("Relative module names not support...
out.insert(0, _read_memory_buffer((layer.n, ), layer.mask, dtype='int32')) layer_outshape = (layer.batch, layer.out_c, layer.out_h, layer.out_w) out.insert(0, _read_memory_buffer(layer_outshape, layer.output)) elif i == net.n-1: ...
84] = 1 cffi_arr = ffi.cast('float*', np_arr.ctypes.data) tvm_out = _get_tvm_output(net, np_arr)[0] darknet_output = get_darknet_network_predict(net, cffi_arr) darknet_out = np.zeros(net.outputs, dtype='float32') for i in range(net.outputs): darknet_out[i] = darknet_output[i] last_layer ...
utshape = (last_layer.batch, last_layer.outputs) darknet_out = darknet_out.reshape(darknet_outshape) tvm.testing.assert_allclose(darknet_out, tvm_out, rtol=1e-4, atol=1e-4) def test_forward_extraction(): '''test extraction model''' model_name = 'extraction' cfg_name = model_name + '.cfg' weight...
# -*- coding: utf-8 -*- """ Layer.py - base layer for gabbs maps ====================================================================== AUTHOR: Wei Wan, Purdue University EMAIL: rcac-help@purdue.edu Copyright (c) 2016 Purdue University See the file "license.terms" for information on usage and re...
e else: return False def getScale(self, zoomlevel): dpi = iface.mainWindow.physicalDpiX()
inchesPerMeter = 39.37 maxScalePerPixel = 156543.04 try: zoomlevel = int(zoomlevel) scale = (dpi * inchesPerMeter * maxScalePerPixel) / (math.pow(2, zoomlevel)) scale = int(scale) return scale except TypeError: raise ...
cos
t, zeros = map(int, input().split()) print(int(round(cost, -zeros
)))
# Copyright 2015 Mirantis, 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 a...
ntOpt('quitting_rpc_timeout', default=10, help=_("Set new timeout in seconds for new rpc calls after " "agent receives SIGTERM. If value is set to 0, rpc "
"timeout won't be changed")), cfg.BoolOpt('log_agent_heartbeats', default=False, help=_("Log agent heartbeats")), cfg.IntOpt('report_interval', default=30, help='Seconds between nodes reporting state to server.'), ] vmware_opts = [ cfg.FloatOpt( ...
#!/usr/bin/env python # # Copyright (C) 2012 Jay Sigbrandt <jsigbrandt@slb.com> # Martin Owens <doctormo@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; ei...
R P
URPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. # """ Test crontab usage. """ import os import sys import unittest import crontab from datetime import date, time, datetime, timedelta try: ...
from .. import BaseForm from wtforms import StringField, TextAreaField from wtforms.validators import DataRequired class CategoryForm(BaseForm): name = StringField('name', validators=[ DataRequired() ]) description = TextAreaField('desc...
validators=[
DataRequired() ])
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # 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 L...
# out for now but this needs to be tested a bit more. # TODO: Re-evaluate if we can delete this or still require it. #if bpl.is_corrupt: # logging.warning( # u'[{0:s}] corruption detected in binary plist: {1:
s}'.format( # self.NAME, file_name)) return top_level_object def Parse(self, parser_context, file_entry): """Parse and extract values from a plist file. Args: parser_context: A parser context object (instance of ParserContext). file_entry: A file entry object (instance of dfvfs...
# -*- coding: utf-8 -*- # @author: vuolter from __future__ import absolute_import, unicode_literals import os import re import sys from future import standard_library standard_library.install_aliases() def char(text, chars, repl=''): return re.sub(r'[{0}]+'.format(chars), repl, text) _UNIXBADCHARS = ('\0', ...
xt, repl, sep).strip() if os.name == 'nt' and res.lower() in _WINBADWORDS: res = sep + res return res def pattern(text, rules): for rule in rules: try: pattr, repl, flags = r
ule except ValueError: pattr, repl = rule flags = 0 text = re.sub(pattr, repl, text, flags) return text def truncate(text, offset): maxtrunc = len(text) // 2 if offset > maxtrunc: raise ValueError('String too short to truncate') trunc = (len(text) - offs...
from .killableprocess import Popen, mswindows if mswindows: from .wi
nprocess import STARTUP
INFO, STARTF_USESHOWWINDOW
#!/usr/bin/env python # -*- coding: utf8 -*- import os import argparse import tensorflow as tf from gym import wrappers from yarll.environment.registration import make class ModelRunner(object): """ Run an already learned model. Currently only supports one variation of an environment. """ def __i...
None: super(ModelRunner, self).__init__() self.env = env self.model_directory = model_directory self.save_directory = save_directory self.config = dict( episode_max_length=self.env.spec.tags.get('wrapper_config.TimeLimit.max_episode_steps'), repeat_n_actio...
self.saver = tf.train.import_meta_graph(os.path.join(self.model_directory, "model.meta")) self.saver.restore(self.session, os.path.join(self.model_directory, "model")) self.action = tf.get_collection("action")[0] self.states = tf.get_collection("states")[0] def choose_action(self, state...
ype): rng = jtu.rand_default(self.rng()) args_maker = lambda: [rng(shape, dtype)] self._CheckAgainstNumpy(np.linalg.slogdet, jnp.linalg.slogdet, args_maker, tol=1e-3) self._CompileAndCheck(jnp.linalg.slogdet, args_maker) @parameterized.named_parameters(jtu.cases_from_list...
dtype_string(shape, dtype)), "shape": shape, "dtype": dtype} for shape in [(1, 1), (4, 4), (5, 5), (2, 7, 7)] for dtype in float_types + complex_types)) @jtu.skip_on_devices("tpu") @jtu.skip_on_flag("jax_skip_slow_tests", True) def testSlogdetGrad(self, shape, dtype): rng = jtu.rand_default...
iag(np.ones([5], dtype=np.float32))*(-.01)] * 2) args_maker = lambda: [mat] self._CheckAgainstNumpy(np.linalg.slogdet, jnp.linalg.slogdet, args_maker, tol=1e-3) @parameterized.named_parameters(jtu.cases_from_list( {"testcase_name": "_shape={}_leftvectors={}_rightvector...
""" Kodi resolveurl plugin Copyright (C) 2014 smokdpi 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 version. ...
stream_url = self._redirect_test(stream_url) else: raise ResolverError('File not found') if r: stream_url = urllib.unquote_p
lus(r.group(1)) if 'http' not in stream_url: stream_url = 'http://' + host + '/' + stream_url.replace('/gplus.php', 'gplus.php').replace('/picasa.php', 'picasa.php') stream_url = self._redirect_test(stream_url) if stream_url: if 'google' in stream_url: ...
#!/usr/bin/env python # Standard packages import os import sys import argparse # Third-party packages from toil.job import Job # Package methods from ddb import configuration from ddb_ngsflow import gatk from ddb_ngsflow import annotation from ddb_ngsflow import pipeline from ddb_ngsflow.align import bwa from ddb_ng...
for samples") parser.add_argument('-c', '--configuration', help="Configuration file for various settings") Job.Runner.addToilOptions(parser) args = parser.parse_args() args.l
ogLevel = "INFO" sys.stdout.write("Setting up analysis directory\n") if not os.path.exists("Logs"): os.makedirs("Logs") if not os.path.exists("FinalVCFs"): os.makedirs("FinalVCFs") if not os.path.exists("FinalBAMs"): os.makedirs("FinalBAMs") if not os.path.exists("Intermedi...
import importlib from .base import BaseTransport from ..service import Service class LocalTransport(BaseTransport): def __init__(self): super(LocalTransport, self).__init__() self.__service = None def __repr__(self): return self.__class__.__name__ def configure(self, service_na...
class(obj, service_name, service_version): continue instance = obj() # uber-safe final check to make sure we have the correct service class if not isinstance(instance, Service): continue return instance raise ...
'must subclass servant.Service and define an action_map, ' 'name and version.' ) def _looks_like_service_class(self, obj, service_name, service_version): return ( getattr(obj, 'name', '') == service_name and getattr(obj, 'version', -1) == ser...
import squeakspace.common.util as ut import squeakspace.common.util_http as ht import squeakspace.proxy.server.db_sqlite3 a
s db import squeakspace.common.squeak_ex as ex import config def post_handler(environ): query = ht.parse_post_request(environ) cookies = ht.parse_cookies(environ) user_id = ht.get_required_cookie(cookies, 'user_id')
session_id = ht.get_required_cookie(cookies, 'session_id') node_name = ht.get_required(query, 'node_name') url = ht.get_required(query, 'url') real_node_name = ht.get_required(query, 'real_node_name') fingerprint = ht.get_optional(query, 'fingerprint') conn = db.connect(config.db_path) try: ...
from .pathutils import grep_r from . import project import os import re def is_partial(path): '''Check if file is a Sass partial''' return os.path.basename(path).startswith('_') def partial_import_regex(partial): '''Get name of Sass partial file as would be used for @import''' def from_curdir(cwd)...
) return (files, partials) else: partials.append(file_path) partial_fn = partial_import_regex(os.path.join(start, file_path)) for f in grep_r(p
artial_fn, start, exts=['.sass','.scss']): if f not in files and f not in partials: files, partials = get_rec(f, start, files, partials) return (files, partials) def get(path): '''Get files affected by change in contents of `path`''' rel, root = project.splitpath(path) deps, _ = ...
# # Copyright (C) 2014 National Institute For Space Research (INPE) - Brazil. # # This f
ile is part of Python Client API for Web Time Series Service. # # Web Time Series Service for Python is free software: you can # redistr
ibute it and/or modify it under the terms of the # GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # Web Time Series Service for Python is distributed in the hope that # it will be useful, but WITHOUT ANY ...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Subscription.frequency' db.add_column('billing_subscription', 'frequency', ...
.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.rel
ated.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permissio...
#!/usr/bin/env python # -*- coding: utf-8 -*- import gi gi.require_version('Gtk', '3.0') import sys import pygame from gi.repository import Gtk from sugar3.activity.activity import Activity from sugar3.graphics.toolbarbox import ToolbarBox from sugar3.activity.widgets import ActivityToolbarButton from sugar3.graphic...
lbar.insert(rem_point, -1) # save list button save = ToolButton('filesave') save.connec
t('clicked', self._save) save.set_tooltip(_('Save data')) toolbar_box.toolbar.insert(save, -1) # separator and stop button separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) toolbar_box.toolbar.insert(separator, -1) ...
import unittest import os from PIL import Image from SUASSystem.utils import crop_target class SUASSystemUtilsDataFunctionsTestCase(unittest.TestCase): def test_crop_image(self): """ Test the crop image method. """ input_image_path = "tests/images/image2_test_image_bounder.jpg" ...
bottom_right_coords) saved_crop = Image.open(output_crop_image_path).load() input_image = Image.open(input_image_path).load() self.assertEqual(saved_crop[0, 0], input_image[250, 200])
self.assertEqual(saved_crop[1, 1], input_image[251, 201]) self.assertEqual(saved_crop[50, 50], input_image[300, 250]) self.assertEqual(saved_crop[99, 99], input_image[349, 299]) os.remove("tests/images/test_crop.jpg")
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # 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, eith...
nment['WL_VCS'] = target.vcs environment['WL_REPO'] = target.repo environment['WL_PATH'] = target.get_path() environment['WL_FILEMASK'] = component.filemask environment['WL_FILE_FORMAT'] = component.file_format try: subprocess.check_call( command, ...
v=environment, cwd=component.get_path(), ) return True except (OSError, subprocess.CalledProcessError) as err: component.log_error( 'failed to run hook script %s: %s', script, err ) return...
import sy
s #line = sys.stdin.read() #print line datas = [] for line in sys.stdin: datas.append(line)
print datas
#!/usr/bin/python # -*- coding: utf-8 -*- # def add(x, y): a=1 while a>0: a = x & y b = x ^ y x = b y = a << 1 return b def vowel_count(word): vowels_counter = 0 for letter in word: if letter.isalpha(): if letter.upper() in 'AEIOUY': vowels_co...
is",max
_vowel_number # Assignment N 2 text="Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Donec rutrum congue leo eget malesuada." list=text.split() length=len(list[0]) words=[] words.append(...
# Copyright 22011 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """All the interfaces that are exposed through
the webservice. There is a declaration in ZCML somewhere that looks like: <webservice:register module="lp.patchwebservice" /> which tells `lazr.restful` that it should look for webservice exports here. """ __metaclass__ = type __all__ = [
'ITemporaryBlobStorage', 'ITemporaryStorageManager', ] from lp.services.temporaryblobstorage.interfaces import ( ITemporaryBlobStorage, ITemporaryStorageManager, ) from lp.services.webservice.apihelpers import ( patch_operations_explicit_version, ) # ITemporaryBlobStorage patch_operations...
.qt import * from aqt.utils import ( TR, HelpPage, disable_help_button, openHelp, showInfo, showWarning, tr, ) def video_driver_name_for_platform(driver: VideoDriver) -> str: if driver == VideoDriver.ANGLE: return tr(TR.PREFERENCES_VIDEO_DRIVER_ANGLE) elif driver == VideoDr...
for d in self.video_drivers ] self.form.video_driver.addItems(names) self.form.video_driver.setCurrentIndex( self.video_drivers.index(self.mw.pm.video_driver()) ) def update_video_driver(self) -> None: new_driver = self.video_drivers[self.form.video_driver.cur...
()] if new_driver != self.mw.pm.video_driver(): self.mw.pm.set_video_driver(new_driver) showInfo(tr(TR.PREFERENCES_CHANGES_WILL_TAKE_EFFECT_WHEN_YOU)) def updateCollection(self) -> None: f = self.form d = self.mw.col self.update_video_driver() qc = ...
"""Custom urls.py for django-registration.""" from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from regi
stration.backends.default.views import ( Activatio
nView, RegistrationView, ) from registration_email.forms import EmailRegistrationForm urlpatterns = [ # django-registration views url(r'^activate/complete/$', TemplateView.as_view( template_name='registration/activation_complete.html'), name='registration_activation_complete'),...
#!/usr/bin/env python import json DEBUG = False import sys import tweepy import time #consumer_key =
'HcMP89vDDumRhHeQBYbE3Asnp' #consumer_secret = 'kcXfsNyBl7tan1u2DgV7E10MpsVxhbwTjmbjp3YL9XfDdMJiYt' #access_key = '67882386-IXbLKaQEtTbZF9yotuLTjgitqjwBkouIstmlW4ecG' #access_secret = 'SyVrXlIDkidYr3JlNiTQ8tjZ973gIKy5m
fpEwFpQWN3Gy' consumer_key = 'Mcof8aJtJVDqQwz4OMDn2AyZu' consumer_secret = 'mjsHber2Gj79uc2unbzSRdwGyNyZGjEPBEn4ZHXQZW8FeGeSkv' access_key = '833745600743079936-hK2K3umAtnfYYuLGLDwD7uzj9ssPCDU' access_secret = '2Odz7Cky2gb3dZJsO1E65zNL8i84ZnoxLrM9uihSEDb6M' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) au...
# coding=utf-8 # Licensed Materials - Property of IBM # Copyright IBM Corp. 2016 """ Publish and subscribe to MQTT messages. Additional information at http://mqtt.org and http://ibmstreams.github.io/streamsx.messaging """ from future.builtins import * from streamsx.topology.topology import * from streamsx.topology ...
config['retain'] = True config['password'] = "foobar" config['trustStore'] = "/tmp/no-such-trustStore" config['trustStorePassword'] = "woohoo"
config['keyStore'] = "/tmp/no-such-keyStore" config['keyStorePassword'] = "woohoo" # create the connector's configuration property map config['serverURI'] = "tcp://localhost:1883" config['userID'] = "user1id" config[' password'] = "user1passwrd" # create the co...
def fat(n): result = 1 while n > 0: result = result * n n = n - 1
return result # testes print(
"Fatorial de 3: ", fat(3));
from datetime import datetime def days_diff(date1, date2): """ Find absolute diff in days between dates """ days = datetime(*date1) - datetime(*date2) print abs(days) return abs(days
.days) if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert days_diff((1982, 4, 19), (1982, 4, 22)) == 3 assert days_diff((2014, 1, 1), (2014, 8, 27)) == 238 assert days_d
iff((2014, 8, 27), (2014, 1, 1)) == 238
import sys
import requests try:
from .helper import * except SystemError: from helper import * def compareRequestsAndSelenium(url): html1 = str(requests.get(url).text) try: driver = webdriver.Firefox() driver.maximize_window() driver.get(url) html2 = str(driver.page_source) finally: ...
""" This module contains several handy functions primarily meant for internal use. """ from datetime import date, datetime, timedelta from time import mktime import re import sys from types import MethodType __all__ = ('asint', 'asbool', 'convert_to_datetime', 'timedelta_seconds', 'time_difference', 'datet...
%s' % (obj.__module__, get_callable_name(obj)) try: obj2 = ref_to_obj(ref) if obj != obj2: raise ValueError except Exception: raise ValueError('Cannot determine the reference to %s' % repr(obj)) return ref def ref_to_obj(ref): """ Returns the object pointed...
if not ':' in ref: raise ValueError('Invalid reference') modulename, rest = ref.split(':', 1) try: obj = __import__(modulename) except ImportError: raise LookupError('Error resolving reference %s: ' 'could not import module' % ref) try: fo...
# -*- coding: utf-8
-*- # © <YEA
R(S)> ClearCorp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import account_move_line
#! /usr/bin/env python """Read infofiles. """ import glob import os, os.path import sys import threading import time import skytools import cc.util from cc import json from cc.daemon import CCDaemon from cc.message import is_msg_req_valid from cc.reqs import InfofileMessage class InfoStamp: def __init__(self,...
self.ccpublish (msg, blob) self.stat_inc ('infosender.bytes.read', len(body)) self.stat_inc ('infosender.bytes.sent', len(cfb)) def find_new(self):
fnlist = glob.glob (os.path.join (self.infodir, self.infomask)) newlist = [] for fn in fnlist: try: st = os.stat(fn) except OSError, e: self.log.info('%s: %s', fn, e) continue if fn not in self.infomap: ...
"""empty message Revision ID: ded3fd1d7f9d Revises: b70e85abec53 Cr
eate Date: 2020-12-30 22:46:59.418950 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'ded3fd1d7f9d' dow
n_revision = 'b70e85abec53' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('hashfiles', sa.Column('checksum', sa.String(length=256), nullable=False)) op.drop_column('hashfiles', 'hash_str') # ### end Alembic commands ##...
s: dict of numpy arrays (one per output) """ @abstractmethod def getOutputElementCount(self, name): """Return the number of elements in the given output of the region Called from the scope of the region's PyRegion.getOutputElementCount() method. name: the name of the output """ @abstractme...
xt compute', dataType='UInt32', count=1, constraints='bool', defaultValue=0, accessMode='ReadWrite'), ), commands=dict( setIdentityPolicyInstance=dict(description= "Set identity policy instance BERORE running the network. " + \ ...
\ "RegionIdentityPolicyBase class."), getIdentityPolicyInstance=dict(description= "Returns identity policy instance that was associated with " + \ "the TestRegion instance via the setIdentityPolicyInstance " + \ "command."), ) ) re...
import unittest import os, sys, imp from qgis import utils from qgis.core import QgsVectorLayer, QgsField, QgsProject, QGis from qgis.PyQt.QtCore import QVariant from .qgis_models import set_up_interface from mole3.qgisinteraction import layer_interaction as li from mole3.qgisinteraction import plugin_interaction as p...
(str(plugin_folder)), 'Path to plugin not found. ({})'.format(str(plugin_folder))) sys.modules['pointsamplingtool'] = imp.load_source('pointsamplingtool', plugin_folder) def setUp(self): self.qgis_app, self
.canvas, self.iface = set_up_interface() utils.plugin_paths = [os.path.expanduser('~/.qgis2/python/plugins')] utils.updateAvailablePlugins() utils.loadPlugin('pointsamplingtool') utils.iface = self.iface utils.startPlugin('pointsamplingtool') def tearDown(self): if s...
# the problem described below was fixed in 9758! # keep_htpsit=False fails since 9473, # on some installations (?) with: # case A (see below in the code): # RuntimeError: Could not locate the Fermi level! # or the energies from the 2nd one behave strange, no convergence: # iter: 1 18:21:49 +1.7 -3608....
4,-0.001,-0.865), (-0.282,-0.674,-3.822), ( 0.018,-0.147,-4.624), (-0.113,-0.080,-3.034), ( 2.253, 1.261, 0.151), ( 2.606, 0.638,-0.539), ( 2.455, 0.790, 1.019), ( 3.106,-0.276,-1.795), ( 2.914, 0.459,-2.386), ( 2.447,-1.053,-1.919), ( 6.257,-0.625,-0.626), ( 7.107,-1.002,-0.317), ( 5.526,-1.129...
,-3.337), (-1.083, 2.576,-3.771), (-0.213, 1.885,-2.680), ( 0.132, 6.301,-0.278), ( 1.104, 6.366,-0.068), (-0.148, 5.363,-0.112), (-0.505, 6.680,-3.285), (-0.674, 7.677,-3.447), (-0.965, 6.278,-2.517), ( 4.063, 3.342,-0.474), ( 4.950, 2.912,-0.663), ( 3.484, 2.619,-0.125), ( 2.575, 2.404,-3.170)...
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.
sqlalchemy import SQLAlchemy from config import config from flask.ext.redis import Redis bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() redis1 = Redis() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(ap...
host' app.config['REDIS_PORT'] = 6379 app.config['REDIS_DB'] = 0 bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) redis1.init_app(app) from .main import main as main_blueprint # from .main.common import common app.register_blueprint(main_bluepr...
# -*- coding:
utf-8 -*- from .ba
se import WatershedBEM
""" A tool for converting kv6 models into pmf. GreaseMonkey, 2013 - Public Domain WARNING: I haven't checked to ensure that X,Y are around the right way. If you find your models have been flipped inadvertently, let me know! --GM """ from __future__ import print_function import sys, struct # Backwards compatibilit...
x 15 chars) denoting the part outfp.write(bonename + b"\x00"
*(16-len(bonename))) # then there's a uint32_t denoting how many points there are in this body part outfp.write(struct.pack("<I",blklen)) # then there's a whole bunch of this: # uint16_t radius; # int16_t x,y,z; # uint8_t b,g,r,reserved; bi = 0 oi = 0 for cx in range(xsiz): for cy in range(ysiz): for i in range(x...
from mrjob.job import MRJob from mrjob.step import MRStep def get_id_from_line(line): if line.find('.","Message-ID: <') > 0: start = line.find("Message-ID")+13 i=0 for char in line[start:]: i=i+1 if (not
(char.isdigit() or (char == '.'))): stop = i+start-2 break return line[start:stop] class MRMultilineInput(MRJob): def st
eps(self): return [ MRStep(mapper_init=self.mapper_init_count, mapper=self.mapper_count), MRStep(mapper=self.mapper_child) # STEP 1 def mapper_init_count(self): self.message_id = '' self.in_body = False self.body = [] self.after_key = False self.beginning = False self.key = False def mapper_...
ze output line: {line}' ) name, version = parts url, sha256 = self._get_pypi_info(name, version) dep = HomebrewDependency( name=name, url=url, sha256=sha256, version=version ) yield dep def _remove_dbt_resource(self, lines:...
d_formula() if self.set_default: self.create_default_package() # self.run_tests(formula_path=self.default_formula_path, audit=False) self.commit_default_formula() class WheelInfo: def __init__(self, p
ath): self.path = path @staticmethod def _extract_distinfo_path(wfile: zipfile.ZipFile) -> zipfile.Path: zpath = zipfile.Path(root=wfile) for path in zpath.iterdir(): if path.name.endswith('.dist-info'): return path raise ValueError('Wheel with no dis...
#!/usr/bin/python # Generate .js files defining Blockly core and language messages. # # Copyright 2013 Google Inc. # https://developers.google.com/blockly/ # # 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 t...
= '' del target_defs[key] else: value = source_defs[key] comment = ' // untranslated' value = value.replace('"', '\\"') outfile.write(u'Blockly.Msg["{0}"] = "{1}";{2}\n' .format(key, value, comment)) # Announce any keys defined o...
efs] synonym_keys = [key for key in target_defs if key in synonym_defs] if not args.quiet: if extra_keys: print(u'These extra keys appeared in {0}: {1}'.format( filename, ', '.join(extra_keys))) if synonym_keys: print(u'These syno...
# -*- coding: utf-8 -*- """ pythoner.net Copyright (C) 2013 PYTHONER.ORG 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 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 L...
ore 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 django.contrib import admin from models import * class ProfileAdmin(admin.ModelAdmin): list_display = ('screen_name','city','introduction') ...
# Copyright 2015 Netflix, 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...
DomainName=domain) # Does the cluster have a policy? if domain_config["DomainConfig"]["AccessPolicies"]["Options"] == "": config['policy'] = {} else: config['policy'] = json.loads(domain_config["DomainConfig"]["AccessPolicies"]["Opt
ions"]) config['name'] = domain return ElasticSearchServiceItem(region=kwargs['region'], account=kwargs['account_name'], name=domain, arn=arn, config=config) class ElasticSearchServiceItem(ChangeItem): def __init__(self, region=None, account=None, name=None, arn=None, config={}): super(El...
outdata1 = divmod(20,8) # prefix an argument with a star when calling a function to unpack tuple t = (20,8) outdata2 = divmod(*t) import os # Note that filename = hh.grad _, filename = os.path.split('/nfs/j3/hh.grad') # Using * to grab excess items # Can be used in python3, but not in python2 # a, b, *rest = range...
, b, *rest = range(3) # a, b, *rest = range(2) # a, *body, c, d = range(5) # *head, b, c, d = range(5) # Nested tuple unpacking a = [('good', (334,213)), ('bad', (231,234))] for cond, (x, y) in a: print('x = {0}, y = {1}'.format(x, y)) # Namedtuple from collections import namedtuple place = namedtuple('plac...
ds) LatLong = namedtuple('LatLong', 'lat long') delhi_data = ('Delhi NCR', LatLong(28.61, 77.21)) delhi = place._make(delhi_data) for key, value in delhi._asdict().items(): print(key + ':', value)
import datetime import decimal from time import time from django.utils.hashcompat import md5_constructor from django.utils.log import getLogger logger = getLogger('django.db.backends') class CursorDebugWrapper(object): def __init__(self, cursor, db): self.cursor = cursor self.db = db ...
s): if s is None or s == '': return None return decimal.Decimal(s) ############################################### # Converters from Python to database (string) # ############################################### def rev_typecast_boolean(obj, d): return obj and '1' or '0' def rev_typeca...
eturn str(d) def truncate_name(name, length=None, hash_len=4): """Shortens a string to a repeatable mangled version with the given length. """ if length is None or len(name) <= length: return name hash = md5_constructor(name).hexdigest()[:hash_len] return '%s%s' % (name[:length-...
import xml.etree.cElementTree as et from collections import Ordere
dDict from tabletopscanner.boardgamegeekapi.parsers import Deserializer class SearchParser(Deserializer): def deserialize(self,
xml): tree = et.fromstring(xml) return [SearchParser.__make_search_result(el) for el in tree.findall('item')] @staticmethod def __make_search_result(el): geekid = geekid = el.attrib['id'] name = el.find('name').attrib['value'] yearpublished = el.find('yearpublished').at...
assert_false # pylint: disable=E0611 from auth.authz import get_user_by_email, get_course_groupname_for_role from django.conf import settings from selenium.webdriver.common.keys import Keys import time import os from django.contrib.auth.models import Group from logging import getLogger logger = getLogger(__name__)...
a CSS transition, # Selenium will always report it as being visible. # This makes it very difficult to successfully click # the "Save" button at the UI level. # Instead, we use JavaScript to reliably click # the button. btn_css
= 'div#page-notification a.action-%s' % name.lower() world.trigger_event(btn_css, event='focus') world.browser.execute_script("$('{}').click()".format(btn_css)) world.wait_for_ajax_complete() @step('I change the "(.*)" field to "(.*)"$') def i_change_field_to_value(_step, field, value): field_css = '...
import unittest import os import json import time from os import environ from ConfigParser import ConfigParser from pprint import pprint from biokbase.workspace.client import Workspace as workspaceService from MyContigFilter.MyContigFilterImpl import MyContigFilter class MyContigFilterTest(unittest.TestCase): ...
', 'length': 12, 'md5': 'md5', 'sequence': 'agcttttcatgg'} obj1 = {'contigs': [contig1, contig2, contig3], 'id': 'id', 'md5': 'md5', 'name': 'name', 'source': 'source', 'source_id': 'source_id', 'type': 'type'} self.getWsClient().save_objects({'workspace': self.getWsName(), 'objects': ...
[{'type': 'KBaseGenomes.ContigSet', 'name': obj_name, 'data': obj1}]}) ret = self.getImpl().filter_contigs(self.getContext(), {'workspace': self.getWsName(), 'contigset_id': obj_name, 'min_length': '10', 'output_name': 'my_output'}) obj2 = self.getWsClient().get_objects([{'ref': s...
ere are all the test parameters and values for the each `~astropy.modeling.FittableModel` defined. There is a dictionary for 1D and a dictionary for 2D models. Explanation of keywords of the dictionaries: "parameters" : list or dict Model parameters, the model is tested with. Make sure you keep the right orde...
Linear1D, Lorentz1D, MexicanHat1D, Trapezoid1D, Const1D, Moffat1D, Gaussian2D, Const2D, Box2D, MexicanHat2D, TrapezoidDisk2D, AiryDisk2D
, Moffat2D, Disk2D, Ring2D) from ..polynomial import Polynomial1D, Polynomial2D from ..powerlaws import ( PowerLaw1D, BrokenPowerLaw1D, ExponentialCutoffPowerLaw1D, LogParabola1D) import numpy as np #1D Models models_1D = { Gaussian1D: { 'parameters': [1, 0, 1], 'x_values': [0, np.sqrt(...
DATA_DIR = '/media/
d/ss
d2/dstl/'
t(':')[0] value = [] else: key = line.strip().split('- ')[1].split(': ')[0] value = line.split(key)[1][2:] if key in data: if hasattr(data[key],'__iter__'): value = data[key] + [value] else: v...
: return "%svideo/%s/%s" % format if appsettings.USE_VOXANT: class VoxantVideo(Video):
asset_id = models.CharField(max_length=255,help_text='Voxant video asset ID (the `a` parameter)') layout_id = models.CharField(max_length=255,help_text='Voxant video asset ID (the `m` parameter)') def absolute_url(self, format): return "%svoxantvideo/%s/%s" % format class Audio(Media)...
#!/usr/bin/env python ''' 2D Group Members: > Charlotte Phang > Lau Wenkie > Mok Jun Neng > Martin Tan > Dicson Candra ''' #Import relevant modules import RPi.GPIO as GPIO import os import glob import time from PIDsm import PID_ControllerSM ### PIN NUMBERS ### tempPin = 4 motorPin = 12 fanPin = 1...
rPin, GPIO.OUT) #setup the motor pin GPIO.setup(fanPin, GPIO.OUT) #setup the fan pin #define the fan and pump pins as PWM pins and initialise them at 0% PWM (off) pump = GPIO.PWM(motorPin, pwmFreq) pump.start(0.0) fan = GPIO.PWM(fanPin, pwmFreq) fan.start(0.0) #create controller object from MotorSM class targetTempe...
float(targetTemperature),30,0,10) motorController.start() fanController = PID_ControllerSM(float(targetTemperature),50,0,5) fanController.start() #create sensor object temp = tempSensor() def main(): #main code to loop indefinitely here #check current temperature currentTemp = temp() print 'Current temp: ...
from django.conf import settings as django_settings # noinspection PyPep8Naming class LazySettings: @property def REQUIRE_MAIN_NAME(self): return getattr(django_settings, 'REQUIRE_MAIN_NAME', 'main') @property def DEFAULT_PAGINATE_BY(self): return getattr(django_settings, 'DEFAULT_PAG...
', 10) @property def AUTO_PAGE_SIZE(self): return getattr(django_settings, 'AUTO_PAGE_SIZE', True) @property def AUTO_FORM_HEADLINE(self): return getattr(django_settings, 'AUTO_FORM_HEADLINE', True) @property def CREATE_FORM_HEADLINE_PREFIX(self): return getattr(django...
DLINE_PREFIX(self): return getattr(django_settings, 'UPDATE_FORM_HEADLINE_PREFIX', 'Edit') @property def FORM_RELATED_OBJECT_IDS(self): return getattr(django_settings, 'FORM_RELATED_OBJECT_IDS', True) @property def GENERIC_FORM_BASE_TEMPLATE(self): return getattr(django_setting...
import re import time class BaseCounters: def __init__(self): self.keyre = re.compile('\A[\w.]+\Z') def ping(self, key): self.validate_key(key) self.do_ping(key, int(time.time())) def hit(self, key, n=1): self.validate_key(key) self.do_hit(key, n) def validate_key(self, key): if re.m...
se ValueError("Counters keys must only contain letters, numbers, the underscore (_) and fullstop (.), received \"
%s\"" % key)
# If the first sample didn't turn out large enough, keep trying to take samples; # this shouldn't happen often because we use a big multiplier for their initial size. # See: scala/spark/RDD.scala while len(samples) < num: # TODO: add log warning for when more than one iterat...
, key=lambda k_v: keyfunc(k_v[0]), reverse=(not ascending))) return self.partitionBy(numPartitions, partitionFunc).mapPartitions(sortPartition, True) @overload def sortByKey( self: "RDD[Tuple[S, V]]"
, ascending: bool = ..., numPartitions: Optional[int] = ..., ) -> "RDD[Tuple[K, V]]": ... @overload def sortByKey( self: "RDD[Tuple[K, V]]", ascending: bool, numPartitions: int, keyfunc: Callable[[K], "S"], ) -> "RDD[Tuple[K, V]]": ... ...
from datetime import datetime class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): sup...
e self.source_type = source_type self.source_id = source_id self.database_id = database
_id self.exception_cls = exception_cls self.created_at = datetime.utcnow() class TokenValidationException(PanoplyException): def __init__(self, original_error, args=None, retryable=True): super().__init__(args, retryable) self.original_error = original_error
""" =========================================== Robust linear model estimation using RANSAC =========================================== In this example we see how to robustly fit a linear model to faulty data using the RANSAC algorithm. """ import numpy as np from matplotlib import pyplot as plt from sklearn import ...
, noise=10, coef=True, random_state=0) # Add outlier d
ata np.random.seed(0) X[:n_outliers] = 3 + 0.5 * np.random.normal(size=(n_outliers, 1)) y[:n_outliers] = -3 + 10 * np.random.normal(size=n_outliers) # Fit line using all data model = linear_model.LinearRegression() model.fit(X, y) # Robustly fit linear model with RANSAC algorithm model_ransac = linear_model.RANSACReg...
from Channel import Channel import telepot class AmbrosioBot(telepot.Bot): """AmbrosioBot is my telgram bot""" def __init__(self, token): super(AmbrosioBot, self).__init__(token) self.clist = None self.chat_id = None def set_list(self,clist): self.clist = clist def on...
msg['text'] if self.clist is not None: self.clist.append(command) self.chat_id = chat_id def respond(self, response): if self.chat_id is not None: self.sendMessage(self.chat_id, response) class TelegramChannel(Channel): """channel class receive...
Channel, self).__init__(name) self.bot = AmbrosioBot("189884221:AAHls9d0EkCDfU0wgQ-acs5Z39aibA7BZmc") self.messages = [] self.bot.set_list(self.messages) self.bot.notifyOnMessage() def get_msg(self): if self.msg_avail(): return self.messages.pop(0) def m...
limit_bids=0, limit_asks=0): """ Send a request to get the public order book, return the response. Arguments: symbol -- currency symbol (default 'btcusd') limit_bids -- limit the number of bids returned (default 0) limit_asks -- limit the number of asks returned (default...
'limit_auction_results': limit_auction_results, 'include_indicative': include_indicative } return requests.get(url, params) # authenticated requests def new_order(self, amount, price, side, client_order_id=None, symbol='btcusd', type='exchange limit', options=N...
""" Send a request to place an order, return the response. Arguments: amount -- quoted decimal amount of BTC to purchase price -- quoted decimal amount of USD to spend per BTC side -- 'buy' or 'sell' client_order_id -- an optional client-specified order id (default ...
imp
ort click from complex.cli import pass_context @click.command('status', short_help='Shows file changes.') @pass_context def cli(ctx): """Shows file changes in the current working directory.""" ctx.log('Cha
nged files: none') ctx.vlog('bla bla bla, debug info')
from __future__ import abs
olute_import import six import logging from .. import py3_errmsg logger = logging.getLogger(__name__) try: import enaml except ImportError: if six.PY3: logger.exception(py3_errmsg) else: raise else: from .model import (GetLastModel, DisplayHeaderModel, WatchForHeadersModel, ...
iew, GetLastWindow, WatchForHeadersView, ScanIDSearchView)
import typer from controller import log from controller.app import Application from controller.deploy.docker import Docker @Application.app.command(help="Provide instructions to join new nodes") def join( manager: bool = typer.Option( False, "--manager", show_default=False, help="join new node with manag...
and node.manager_status ): manager_address = node.manager_status.addr if manager: log.info("To add a manager to this swarm, run the following command:") token = docker.swarm.get_token("manager") else: log.info("To add a worker to this swarm, run the foll...
ddress}") print("")
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('viewer', '0006_meter_on_auditlist'), ] operations = [ migrations.CreateModel( name='Group', fields=[...
primary_key=True)), ('name', models.CharField(max_length=64)), ], options={ }, bases=(models.Model,), ), migrations.RenameField( model_name='profiledatapoint', old_name='kwh', new_name='kw', ), ...
='meter', name='groups', field=models.ManyToManyField(to='viewer.Group'), preserve_default=True, ), ]
# Copyright 2017 The TensorFlow Authors. 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 applica...
rt absolute_import from __future__ import division from __future__ import print_func
tion import textwrap import gast from tensorflow.python.util import tf_inspect def parse_object(obj): """Return the AST of given object.""" return parse_str(tf_inspect.getsource(obj)) def parse_str(src): """Return the AST of given piece of code.""" return gast.parse(textwrap.dedent(src))
# -*- coding: utf-8 -*- import os import ConfigParser import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email import encoders from global_functions import app_dir class Mailer(): """ Instance to manage the mailing. ...
f): """ Setup all needed info. """ # Gets all the connection info from the .ini file self.Config = ConfigParser.ConfigParse
r() self.Config.read(os.path.join(app_dir, "institution.ini")) self.server = unicode(self.Config.get("Mail", "server")) self.port = int(self.Config.get("Mail", "port")) self.email = unicode(self.Config.get("Mail", "email")) self.password = unicode(self.Config.get("Mail", "passwor...
') self.thetaIterationValue = self.getWidget('spinBox_thetaIterationValue') self.phiIterationValue = self.getWidget('spinBox_phiIterationValue') self.medialMesh = self.getWidget('checkBox_medialMesh') # Advanced Post Processed Segmentation self.CollapsibleButton_AdvancedPostProcessedSegmentation =...
egreeValue.connect('valueChanged(double)', self.onSPHARMDegreeValueChanged) self.thetaIterationValue.connect('valueChanged(int)', self.onThetaIterationValueChanged) self.phiIterationValue.connect('valueChanged(int)', self.onPhiIterationValueChanged) self.medialMesh.connect('clicked(bool)', self.onMedialMesh...
lambda: self.onSelectedCollapsibleButtonOpen( self.CollapsibleButton_AdvancedPostProcessedSegmentation)) self.GaussianFiltering.connect('clicked(bool)', self.onSelectGaussianVariance) self.VarianceX.connect('valueChanged(double)', self.onVarianceXValue...
r seconds', 'minutesRequired': 'You must enter minutes (after a :)', 'badNumber': 'The %(part)s value you gave is not a number: %(number)r', 'badHour': 'You must enter an hour in the range %(range)s', 'badMinute': 'You must enter a minute in the range 0-59', 'badSecond': 'You mus...
, state): if value: return self.true_values[0] else: return self.false_values[0] # Should deprecate: StringBoolean = StringBool class SignedString(FancyValidator): """ Encodes a string into a signed string, and base64 encodes both the
signature string and a random nonce. It is up to you to provide a secret, and to keep the secret handy and consistent. """ messages = { 'malformed': 'Value does not contain a signature', 'badsig': 'Signature is not correct', } secret = None nonce_length = 4 def _...