prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
################################################################# # This file is part of glyr # + a command-line tool and library to download various sort of music related metadata. # + Copyright (C) [2011-2012] [Christopher Pahl] # + Hosted at: https://github.com/sahib/glyr # # glyr is free software: you can redistri...
} TESTCASES = [{ # {{{ 'name': 'bbcmusic', 'data': [{ 'options': { 'get_type': 'artistphoto', 'artist': 'The Rolling Stones' }, 'expect': len_greater_0 }, { 'options': not_foun
d_options, 'expect': len_equal_0 }], }, { # }}} # {{{ 'name': 'discogs', 'data': [{ 'options': { 'get_type': 'artistphoto', 'artist': 'Nirvana' }, 'expect': len_greater_0 }, { 'options': not_found_options, 'e...
a binary-serializable object to hex (eg for submission via RPC) def ToHex(obj): return bytes_to_hex_str(obj.serialize()) # Objects that map to bitcoind objects, which can be serialized/deserialized class CAddress(): def __init__(self): self.nServices = 1 self.pchReserved = b"\x00" * 10 + b"\xf...
n = tx.nVersion self.vin = copy.deepcopy(tx.vin) self.vout = copy.deepcopy(tx.vout) self.nLockTime = tx.nLockTime self.sha256 = tx.sha256 self.hash = tx.hash self.wit = copy.deepcopy(tx.wit) def deserialize
(self, f): self.nVersion = struct.unpack("<i", f.read(4))[0] self.vin = deser_vector(f, CTxIn) flags = 0 if len(self.vin) == 0: flags = struct.unpack("<B", f.read(1))[0] # Not sure why flags can't be zero, but this # matches the implementation in bitco...
import os import sys def main(): if len(sys.argv) <= 2: print("This script generates the .expected file from your PS3's debug logs.") print("") print("Usage: convert-ps3-output.py <input> <output>") print("Example: convert-ps3-output.py hello_world.log hello_world.expected") ...
):]
data = data[data.find(b"\x0D\x0A")+2:] data = data[:data.rindex(b"END LOG")-12] data = data.replace(b"\x0D\x0A", b"\x0A") w.write(data) w.close() if __name__ == "__main__": main()
merged_tally.add_score(score) # Add triggers from second tally to merged tally for trigger in tally.triggers: merged_tally.add_trigger(trigger) return merged_tally def get_tally_xml(self): """Return XML representation of the tally Returns ------- ...
eak # If the Summary has not been linked, then values are ZAIDs else:
if test_nuclide == nuclide: nuclide_index = i break if nuclide_index == -1: msg = 'Unable to get the nuclide index for Tally since "{0}" ' \ 'is not one of the nuclides'.format(nuclide) raise KeyError(msg) e...
import unittest import os import sys import time import sqlite3 import os.path as op from shutil import rmtree from functools import partial from kivy.clock import Clock main_path = op.dirname(op.dirname(op.abspath(__file__))) sys.path.append(main_path) from main import KrySA, ErrorPop from tasks.basic import Basic ...
[0].ids.vals.children for i in range_vals: cols[0].ids.valadd.dispatch('on_release') num = str(i + 1) val
s[0].ids.value.text = num + '.' + num new_data = app.root.wiz_newdata.run() # open Task's popup and get task k = '3' address = ['A1:D13', 'A1:B2', 'C1:D2', 'A12:B13', 'C12:D13', 'B3:C10'] for addr in address: taskcls = Basic() taskcls.b...
None: info.type = value else: edge = TransitionGenerator.Edge(incoming=False, role=role, value=value) info.edges.append(edge) if value == frame: edge.inverse = edge continue if value.islocal(): nb_info = frame_info.get(value, None) i...
. attention.insert(0, simple.info.handle) elif t in [Action.REFER, Action.ASSIGN, Action.CONNECT]: # Promote an existing frame to the
center of attention. attention.remove(simple.info.handle) attention.insert(0, simple.info.handle) # Builds and returns a simple action of type 'type'. def _simple_action(self, type=None): return TransitionGenerator.SimpleAction(type) # Stores mentions starting or ending or both at a given toke...
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
should have received a copy of the GN
U Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class BppSuite(CMakePackage): """BppSuite is a ...
main_id': DEFAULT_DOMAIN_ID} new_user = self.identity_api.create_user(new_user) self.assertRaises(exception.NotFound, self.identity_api.check_user_in_group, new_user['id'], new_group['id']) def test_check_user_in_group_4...
ist_groups_for_user( test_users[x]['id']) self.assertEqual(0, len(group_refs)) for x in range(0, GROUP_COUNT): before_count = x after_count = x + 1 new_group = {'domain_id': domain['id'], 'name': uuid.uuid4().hex} ...
est_groups.append(new_group) # add the user to the group and ensure that the # group count increases by one for each group_refs = self.identity_api.list_groups_for_user( positive_user['id']) self.assertEqual(before_count, len(group_refs)) self...
#!/usr/bin/python2.4 # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # # $Id$ # # Copyright (C) 1999-2006 Keith Dart <keith@kdart.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...
or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even t
he implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. """ Module for managing Linux firewall feature from Python, using sudo to run ipfw program. NOTE: this only works on Linux with firewall option enabled in the kernel. """...
#requirements: selenium wget python2.7 Geckodriver import time import sys import wget from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys ...
.argv[2] url = "https://www.google.com/search?num=100&start=0&hl=em&meta=&q=site:" url += domain url += "+filetype:" url += ftype url += "&filter=0" googlescrape(url) elif len(sys.argv) == 2: for i in range (0,3): if i==0: print "Checking for pdfs..." ftype ...
== 1: print "Checking for docs..." ftype = "doc" elif i == 2: print "Checking for xls..." ftype = "xls" domain = sys.argv[1] url = "https://www.google.com/search?num=100&start=0&hl=em&meta=&q=site:" url += domain url += "+filetyp...
est.TestCase): def test_parser(self): """Test parser selection. Test to see whether we are selecting the correct parser. """ tx = BytesIO(open( os.path.join(BASENAME, 'resources', 'tx-9c0f7b2.dmp'), 'r' ).read()) connection = network.Connectio...
.register_handler( network.ConnectionEstablishedEvent.type, connection_handler ) nc.socket.accept = mock.Mock(side_effect=[ (mock.Mock(), ('10.0.0.1', 8333)), StopIteration() ]) self.assertRaises(StopIteration, nc.accept) self.asser...
tch('bitcoin.network.gevent.spawn') def test_accept_idle_timeout(self, mspawn, mspawn_later): nc = network.GeventNetworkClient() nc.socket = mock.Mock() connection_handler = mock.Mock() nc.register_handler( network.ConnectionLostEvent.type, connection_handler...
# -*- coding: utf-8 -*- ''' Created on Nov 30, 2014 @author: Michael Große <mic.grosse@posteo.de> ''' from collections import defaultdict from receipteval.item_cat_dict import ItemCategoryDict class ReceiptCollection(object): ''' Collection of purchases with evaluation and output options. ''' def __...
lf): self.initialize_super_categories() for category in self.categories.keys(): catsum = 0 length = len(category) for cat in self.c
ategories.keys(): if (cat[0:length] == category): catsum += self.categories[cat][0] self.categories[category][2] = catsum def initialize_super_categories(self): missing_super_categories = [] for category in self.categories.keys(): if (cate...
S8oYyypOWc9zADFcJOExm1sRDBpIEz67oDLXAre6fwBluRTwRE9J9FK2ivtJJaJ oymobILSiGE2pI+a4uzonRD1Z/yzblZF8/k7HoT3WEihXi8LFa5xClNcU8Q8+T2JlMCgkuGPsIgm r+ooelPj4QhS0IxAa256tLk9wknDlKhvZlAEmiOYBoqh8ZKzl16rz98Z9VJGRTSRF4XRw+cxNA40 pEE0gOHBoCmORC1fyJZg1lZFfnbM2qBkP/KJcRCY8h3gwKS6HL2TXfNHeUI/AP2K5IFwN1i6DtNN 5CmEA2sB0g0sdkEUCcgBsKYZD...
2CY+hSfFvyYiBR9u86xBhSbN1LY04LOp5bZMN3ZrGry39FM+MhbrXsMN4S4XWzN7YPnwNCyyqkA GyXA5DhDDXs8tA4mPaQqCe+6JCu/x7fFu33Zlmxk4sQbdk4biVJVZMXfPc5DxrSVpOEQcuYOrkHt GvW8WBcN7NmCDYSrosuxrzWsahElVwCjBNsgRaIFNILJRl4jGKbluEZ3Sj+Ai5ImA+JZacE/3PH1 5AGLFvxtRoLNDvxELFkm6Iwir1ytGwyycwKRZkPmwEJppWqU4qbzKMCzzFTHFsh38xC34WEHtt2q vnZVXK0fMsPQ4...
DUoo9YTViCQIQztjro6oPT4gC/tcZIFEMs+SHM0EVKyajCl86uQIcC9W+NdhHzSl2d0jg1UEDU IUCWF8vdNoVy5aM6Em5yWtdVka+P9Dvb6xqORkOxLqywOv4BFT9jJU71uKFPKbsOt098CVJuuZrp QtIWbbWg24J9TGinuFN8XnnLTsc8Qm20KsYUHYcYkwDrMgruOx+FxPOoy7t3w5BNqx5gnUHK6iVN 8907bDsGUO3c8IFzrKHgtN+9+3jyVbRrCCNEeKYDll5UIPs0LJ40Es1hElbaW3GT49WFrB6vnTDK SQ46a7fFmjypdF...
rror( "No starting revision argument is available." ) def get_revision_argument(self) -> _RevNumber: """Get the 'destination' revision argument. This is typically the argument passed to the ``upgrade`` or ``downgrade`` command. If it was specified as ``...
olclass=pool.NullPool) This then takes effect by running the ``alembic`` script as:: alembic -x dbname=postgresql://user:pass@host/dbname upgrade head This function does n
ot require that the :class:`.MigrationContext` has been configured. .. seealso:: :meth:`.EnvironmentContext.get_tag_argument` :attr:`.Config.cmd_opts` """ if self.config.cmd_opts is not None: value = self.config.cmd_opts.x or [] else: ...
"""<name>Performance Curves</name> <description>Model performance at different thresholds</description> <icon>icons/PerformanceCurves.png</icon> <priority>30</priority> <contact>Janez Demsar (janez.demsar@fri.uni-lj.si)</contact>""" from OWWidget import * from OWGUI import * from PyQt4.QtGui import * from PyQt4.QtCore...
= prob: self.allScores.append(((TP+TN)/all, TP/(P or 1), TN/(N or 1), TP/(all-Nc), TN/Nc, 2*TP/(P+all-Nc), TP, TN, FP, FN, Nc)) self.probs.append(prevprob)
prevprob = prob self.allScores.append(((TP+TN)/all, TP/(P or 1), TN/(N or 1), TP/(all-Nc), TN/Nc, 2*TP/(P+all-Nc), TP, TN, FP, FN, Nc)) self.probs.append(prevprob) self.allScores = zip(*self.allScores) self.selectionChanged() def selectionChanged(self): self.graph.cl...
# http://code.activestate.com/recipes/577263-numerical-integration-using-monte-carlo-method/ # Numerical Integration using Monte Carlo method # FB - 201006137 #pythran export montecarlo_integration(float, float, int, float list, int) #runas montecarlo_integration(1.,10.,100,[x/100. for x in range(100)],100) #bench mont...
= f(x) if y < ymin: ymin = y if y > ymax: ymax = y # Monte Carlo rectArea = (xmax - xmin) * (yma
x - ymin) numPoints = numSteps # bigger the better but slower! ctr = 0 for j in range(numPoints): x = xmin + (xmax - xmin) * rand[j%randsize] y = ymin + (ymax - ymin) * rand[j%randsize] if math.fabs(y) <= math.fabs(f(x)): if f(x) > 0 and y > 0 and y <= f(x): ...
# coding: utf-8 """ Qc API Qc API # noqa: E501 The version of the OpenAPI document: 3.0.0 Contact: cloudsupport@telestream.net Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from telestream_cloud_qc.configuration import Configuration class...
"""Sets the checked of this ActiveFormatTest. :param checked: The ch
ecked of this ActiveFormatTest. # noqa: E501 :type: bool """ self._checked = checked def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) i...
""" Module that provides a connection to the ModuleStore specified in the django settings. Passes settings.MODULESTORE as kwargs to MongoModuleStore """ from __future__ import absolute_import from importlib import import_module import re from django.conf import settings from django.core.cache import get_cache, Inval...
runtime i18n service. """ def __getattr__(self, name): return getattr(django.utils.translation, name) def strftime(self, *args, **kwargs): """ A locale-aware implementation of strftime. """ # This is the wrong place to import this function. I'm putting it here...
. This function isn't called in # that suite, so this hides the import so the test won't fail. # # As I said, this is wrong. But Cale says this code will soon be # refactored to a place that will be right, and the code can be made # right there. If you are reading this comment...
a,b,c = input().split(" ") numbers = [int(a),int(b),int(c)] cnumbers = list(numbers) for j in range(0,len(numbers)): for i in ran
ge(0,len(numbers)-1): if n
umbers[i] > numbers[i+1]: aux = numbers[i+1] numbers[i+1] = numbers[i] numbers[i] = aux for a in range(len(numbers)): print(numbers[a]) print("") for b in range(len(cnumbers)): print(cnumbers[b])
from __future__ import unicode_literals from zope.interface impo
rt implements, classProvides from scheme.macro import Macro from scheme.symbol import Symbol from scheme.environment import Environme
nt, SyntaxEnvironment from scheme.syntax import SyntaxSymbol from scheme.PatternMatcher import PatternMatcher # from scheme.utils import syntax_copy_with_replacement from scheme.utils import transformCode import scheme.debug class syntax_rules(object): implements(Macro) classProvides(Macro) de...
from __future__ import unicode_literals from blanc_basic_assets.fields import AssetForeignKey from django.core.exceptions import ValidationError from django.core.urlresolvers import get_script_prefix from django.core.validators import RegexValidator from django.db import models from django.utils.encoding import iri_to...
ngth=100, unique=True, help_text="Example: '/about/contact/'. Make sure to have leading and trailing slashes.", validators=[url_validator, slash_validator]) title = models.CharField(max_length=200) parent = TreeForeignKey('self', null=True, blank=True, related_name='children') show_in_naviga...
null=True, on_delete=models.SET_NULL) content = models.TextField(blank=True) template_name = models.CharField(max_length=100, blank=True) published = models.BooleanField(default=True, db_index=True) login_required = models.BooleanField(default=False, db_index=True) objects = TreeManager() def ...
from __future__ import absolute_import, unicode_literals import warnings
from django.core
.exceptions import ImproperlyConfigured from django.template.loader import render_to_string from django.utils.safestring import mark_safe from wagtail.utils.deprecation import RemovedInWagtail16Warning from wagtail.wagtailadmin.edit_handlers import BaseChooserPanel from wagtail.wagtailcore.utils import resolve_model_s...
m) if last: last.quantifier = t.between return t elif psm.char == "?" and quantified == ContentOfGroup.Quantified: self.quantified = ContentOfGroup.UngreedyQuantified last = self._last_or_fail(psm) if last: last.quantif...
class class WrappedCharClass: def __init__(self): # ast is CharClass or may be changed to PatternClass in one case
self.ast = ast.CharClass() def add(self, other): assert isinstance(self.ast, ast.CharClass) self.ast.elems = self.ast.elems + (other,) def pop(self): assert isinstance(self.ast, ast.CharClass) last = self.ast.elems[-1] self.ast.elems = self.ast.elems[:-1] retur...
ing', threadHydroWithinB
lock='Within Block Threading', tmax='Maximum Simulation Time [s]', updateHydroFluxes='Update Hydro Fluxes', useDiffuse='Use Diffusive Effects'
, useEnergyDeposition='Use Energy Deposition', useFlame='Use Flame', useGravity='Use Gravity', useHydro='Use Hydro Calculation', useRadTrans='Use Radiative Transfer', use_cma_advection='Use CMA Advection', use_cma_flattening='Use CMA Flattening', ye_burned...
# ================================================================================================== # Copyright 2013 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
p_impl_validator, MockActiveKazooGroup): mock_zk = mock.Mock(spec=KazooClient) mock_group = mock.MagicMock(spec=GroupInterface) MockActiveKazooGroup.mock_add_spec(ActiveKazooGroup) MockActiveKazooGr
oup.return_value = mock_group # by default it tries to assert that the group impl is a subclass of GroupInterface # since the group impl will be a mock, it doesn't pass that check, so we mock the validator # as well. mock_group_impl_validator.return_value = True def devnull(*args, **kwargs): pass servers...
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from tf2_msgs/FrameGraphRequest.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class FrameGraphRequest(genpy.Message): _md5sum = "d41d8cd98f00b204e9800998ecf8427e" _...
nstance :param str: byte array of serialized message, ``str`` """ try: end = 0 return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into b...
ngIO`` :param numpy: numpy python module """ try: pass except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), st...
#!/usr/bin/env python import os from runtest import TestBase class TestCase(TestBase): def __init__(self): TestBase.__init__(self, 'openclose', serial=True, result=""" # DURATION TID FUNCTION [ 9875] | main() { [ 9875] | fopen() { 14.416 us [ 9875] | sys_open(); 1...
4.17 (x86_64) changed syscall routines major, minor, release = uname[2].split('.') if uname[0] == 'Lin
ux' and uname[4] == 'x86_64' and \ int(major) >= 5 or (int(major) == 4 and int(minor) >= 17): return result.replace(' sys_open', ' __x64_sys_openat') else: return result.replace(' sys_open', ' sys_openat')
the dictionary, return its value. If not, insert *k* with a value of *default* and return *default*. *default* defaults to ``None``. See :meth:`dict.setdefault` for more information. """ if not super(OrderedMultiDict, self).__contains__(k): self[k] = [] if default is...
if k is _MISSING: if self: k = self.root[PREV][KEY] else: raise KeyError('empty %r' % type(self)) try: self._remove(k) except KeyError: if default is _MISSING: raise KeyError(k)
return default values = super(OrderedMultiDict, self).__getitem__(k) v = values.pop() if not values: super(OrderedMultiDict, self).__delitem__(k) return v def _remove(self, k): values = self._map[k] cell = values.pop() cell[PREV][NEXT], ce...
# 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 ...
--------------- from msrest.serialization import Model class SecurityGroupViewResult(Model): """The information about security rules applied to the specified VM.
:param network_interfaces: List of network interfaces on the specified VM. :type network_interfaces: list[~azure.mgmt.network.v2017_09_01.models.SecurityGroupNetworkInterface] """ _attribute_map = { 'network_interfaces': {'key': 'networkInterfaces', 'type': '[SecurityGroupNetworkInterface...
import unittest from test import test_support # Skip this test if the _testcapi module isn't available. test_support.import_module('_testcapi') from _testcapi import _test_structmembersType, \ CHAR_MAX, CHAR_MIN, UCHAR_MAX, \ SHRT_MAX, SHRT_MIN, USHRT_MAX, \ INT_MAX, INT_MIN, UINT_MAX, \ LONG_...
ts.T_BYTE = CHAR_MIN-1 def test_ubyte_max(self): with test_support.
check_warnings(('', RuntimeWarning)): ts.T_UBYTE = UCHAR_MAX+1 def test_short_max(self): with test_support.check_warnings(('', RuntimeWarning)): ts.T_SHORT = SHRT_MAX+1 def test_short_min(self): with test_support.check_warnings(('', RuntimeWarning)): ...
# singleton tuple <- singleton tuple x, = 0, print(x) # singleton tuple <- singleton list x, = [-1] print(x) # binary tuple <- binary tuple x,y = 1,2 print(x,y) # binary tuple swap x,y = y,x print(x,y) # ternary tuple <- ternary tuple x,
y,z = 3,4,5 print(x,y,z) # singleton list <- singleton list [x] = [42] print(x) # singleton list <- singleton tuple [x] = 43, print(x) # binary list <- binary list [x,y] = [6,7] # binary list <- binary tuple [x,y] = [44,45] print(x,y) # binary tuple (parens) <- binary list (x,y) = [7,8] print
(x,y) # binary tuple <- result of function call (x,y) = (lambda: (9,10))() print(x,y) # nested binary tuple (parens) <- nested binary tuple (parens) ((x,y),z) = ((11,12),13) print(x,y,z) # nested binary tuple <- nested binary tuple (x,y),z = (14,15),16 print(x,y,z)
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
dict([line.split('=', 1) for line in data.split('\n') if '=' in line and not line.star
tswith('#')])
# (c) 2013, Ovais Tariq <me@ovaistariq.net> # # This file is part of mha_helper # # 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. S...
ng with this program. If not, see <http://www.gnu.org/licenses/>. # -*- coding: utf-8 -*- __name__ = 'mha_helper' __author__ = 'Ovais Tariq' __email__ = 'me@ovaistariq.net' __version__ = '0.4.2' __url__ = 'https://github.com/ovaistariq/mha-helper'
# -*- coding: utf-8 -*- from __future__ import print_function # Form implementation generated from reading ui file './acq4/analysis/old/StdpCtrlTemplate.ui' # # Created: Tue Dec 24 01:49:15 2013 # by: PyQt4 UI code generator 4.10 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, ...
lf.gridLayout.addWidget(self.durationSpin, 1, 1, 1, 2) self.label_4 = QtGui.QLabel(StdpCtrlWidget) self.label_4.setObjectName(_fromUtf8("label_4")) self.gridLayout.addWidget(self.label_4, 2, 0, 1, 1) self.slopeWidthSpin = SpinBox(StdpCtrlWidget) self.slopeWidthSpin.setObjectName(...
ck = QtGui.QCheckBox(StdpCtrlWidget) self.apExclusionCheck.setObjectName(_fromUtf8("apExclusionCheck")) self.gridLayout.addWidget(self.apExclusionCheck, 3, 0, 1, 1) self.label_3 = QtGui.QLabel(StdpCtrlWidget) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout.addWid...
# c
oding: utf-8 class ActMail(object): subject = '宝宝云帐号注册激活邮件' content = '感谢您申请注册宝宝云账号! 请点击链接完成注册: ' source = 'enfancemill@gmail.com' secret = 'kwhr8xkq4eoq6bvvh6nv
r6267lrdcqb2'
"""Update vulnerability sources.""" from selinon import StoragePool from f8a_worker.base import BaseTask from f8a_worker.enums import EcosystemBackend from f8a_worker.models import Ecosystem from f8a_worker.solver import get_ecosystem_solver, OSSIndexDependencyParser from f8a_worker.workers import CVEcheckerTask clas...
ersion': version }) msg = "Components to be {prefix}scanned for vulnerabilities: {components}".\ format(prefix="re-" if only_already_s
canned else "", components=to_scan) self.log.info(msg) return to_scan def execute(self, arguments): """Start the task. :param arguments: optional argument 'only_already_scanned' to run only on already analysed packages :return: EPV dict describing...
to read from and write to the SQLite backend. """ import sqlite3 import codecs import os import re def setup_db(): dbpath = os.path.dirname(os.path.realpath(__file__)) + os.sep +".."+os.sep+"gitdox.db" conn = sqlite3.connect(dbpath) cur = conn.cursor() # Drop tables if they exist cur.execute("DROP TABLE IF EXIS...
ic_query("DELETE FROM metadata WHERE metaid=?", (metaid,)) if not corpus: invalidate_doc_by_id(doc_id) def get_doc_info(doc_id): res = generic_query("SELECT name,corpus,filename,status,assignee_username,mode,schema FROM docs WHERE id=?", (int(doc_id),)) if len(res) > 0: return res[0] else: return res def ge...
x: x[0], generic_query("SELECT id FROM docs WHERE corpus=?", (corpus,))) def get_all_docs(corpus=None, status=None): if corpus is None: if status is None: return generic_query("SELECT id, name, corpus, mode, content FROM docs", None) else: return generic_query("SELECT id, name, corpus, mode, ...
impor
t pcf8591read """ This is a barebones script for controlling the work flow of recording EMG words and associating the data with a specific word, captured in the filename. """ reader = pcf8591read.adc_reader() f
ilename = input('Current word:') reader.record = True reader.run(filename)
im
port _plotly_utils.basevalidators class ReversescaleValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__(self, plotly_name="reversescale", parent_name="volume", **kwargs): super(ReversescaleValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_nam...
)
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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 ...
s deprecated and will ' 'be removed in a subsequent release')) if CONF.action.name in ['add', 'del']: LOG.debug("Called '%(action)s' for mac '%(mac)s' with IP '%(ip)s'", {"action": CONF.action.name, "mac": CONF.action.mac, "ip"...
y: network_id = int(os.environ.get('NETWORK_ID')) except TypeError: LOG.error(_LE("Environment variable 'NETWORK_ID' must be set.")) return(1) print(init_leases(network_id)) rpc.cleanup()
# 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 # d...
sonutils.loads(db_extra['vcpu_model'])) @base.NovaObjectRegistry.register class VirtCPUFeature(base.NovaObject): VERSION = '1.0' fields = { 'policy': fields.CPUFeaturePolicyField(nullable=True),
'name': fields.StringField(nullable=False), } def obj_load_attr(self, attrname): setattr(self, attrname, None)
# -*- coding: utf-8 -*- ''' accpy.simulate.const Felix Kramer (felix.kramer@physik.hu-berlin.de) ''' # ratio of circumference to diameter of circle pi = 3.141592653589793115997963468544185161590576171875 # speed of light----------------------------------------/ (m/s) cl = 299792458. # elementary charge----------------...
----------------------------------/ (J)=(Nm)=(Ws) Eu = mu*cl**2 # classical radius of electron--------------------------/ (m) re = qe**2/(me*1e7) # classical radius of proton----------------------------/ (m) rp = qe**2/(mp*1e7) # classical radius of muon------------------------------/ (m) ru = qe**2/(mu*1e7) # vacuum p...
)=(Henry/m) u0 = 4*pi*1E-7 # vacuum permittivity / elektrical field const----------/ (As/Vm) e0 = 1/(u0*cl**2) # Planck constant---------------------------------------/ (Js) hp = 6.62606957e-34 # reduced Planck constant-------------------------------/ (Js) hb = hp/2/pi # Boltzmann constant------------------------------...
import visualizer as v import os as os import json from shutil import rmtree from os.path import expanduser from os.path import join as OSpathJoin global appLoc appLoc = "C:\Users\john\Desktop\jDesigner"#C:\\Program Files\\aggendo\\jCode\\" configFold = "C:\Users\john\Desktop\jDesigner\config" recent = "" canvas = "" s...
= "" prefs = "" #jDe = json.JSONDecoder recF = file prefF = file tempFold = "C:\\Users\\john\\Desktop\\jDesigner\\temp" def genPaths(): partialPath = v.__file__ #get the path to visualizer.pyc partialPath = partialPath[:-15] #strip away the /visualizer.pyc appLoc = partialPath configFold = OSpathJoin(p...
: instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class MyClass: appLoc = "" def __init__(): if not os.path.exists(appLoc): os.makedirs(appLoc) def getRecent(): ...
from django.db import migrations class Migration(migrations.Migration): """ We're changing the stream deactivation process to make it mark all messages in the stream as read. For things to be consistent with streams that have been deactivated before this change, we need a migration to fix those old st...
sql=""" UPDATE zerver_usermessage SET flags = flags | 1 FROM zerver_message
INNER JOIN zerver_stream ON zerver_stream.recipient_id = zerver_message.recipient_id WHERE zerver_message.id = zerver_usermessage.message_id AND zerver_stream.deactivated; """, reverse_sql="", ), ]
from utils import url_xpath, State from .people import DEPersonScraper from .bills import DEBillScraper # from .events import DEEventScraper # from .committees import DECommitteeScraper class Delaware(State): scrapers = { "people": DEPersonScraper, "bills": DEBillScraper, # 'events': DEEv...
{ "_scraped_name": "2018 - 2020 (GA 150)", "identifier": "150", "name": "150th General Assembly (2019-2020)", "start_date": "2019-01-08", "end_date": "2020-05-06", }, # { # "_scraped_name": "2020 - 2022 (GA 151)", # "ide...
# "end_date": "2022-05-06", # }, ] ignored_scraped_sessions = [ "2020 - 2022 (GA 151)" ] def get_session_list(self): url = "https://legis.delaware.gov/" sessions = url_xpath(url, '//select[@id="billSearchGARefiner"]/option/text()') sessions = [session.str...
from django import forms from django.contrib.gis.geos import Point from widgets import AddAnotherWidgetWrapper from django.core.exceptions import ValidationError from .models import (Site, CycleResultSet, Monitor, ProgrammeResources, ProgrammeImage) class SiteForm(forms.ModelForm): latitude ...
ts' and link: raise ValidationError( 'A resource of type Reports cannot have a link, expecting a document' ) if resource.name == 'Survey Instrument' and link: raise ValidationError( 'A resource of type Survey Instrument cannot have a link, expe...
eaned_data class ProgrammeImageForm(forms.ModelForm): class Meta: model = ProgrammeImage fields = '__all__' def clean(self): featured = self.cleaned_data.get('featured') programme = self.cleaned_data.get('programme') if featured: if ProgrammeImage\ ...
t os import subprocess import shutil import sys import signal from io import StringIO from ast import literal_eval from enum import Enum import tempfile from pathlib import Path, PurePath from mesonbuild import build from mesonbuild import environment from mesonbuild import mesonlib from mesonbuild import mlog from mes...
file {0} missing.\n'.format(fname) # Check if there are any unexpected files found = get_r
elative_files_list_from_dir(installdir) for fname in found: # Windows-specific tests check for the existence of installed PDB # files, but common tests do not, for obvious reasons. Ignore any # extra PDB files found. if fname not in expected and not fname.endswith('.pdb') and compile...
piry, message_id) def get_sequence_number_message_id(self, sequence_number): return self.redis.get(sequence_number_key(sequence_number)) def cache_message(self, message): key = message_key(message['message_id']) expire = self.config.submit_sm_expiry return self.redis.setex(key,...
message: %s" % (message_id,)) else: yield self.message_stash.delete_cached_message(message_id) yield self.publish_nack(message_id, command_status) yield self.failure_publisher.publish_mess
age( FailureMessage(message=err_msg.payload, failure_code=None, reason=command_status)) @inlineCallbacks def handle_submit_sm_success(self, message_id, smpp_message_id, command_status): ...
# Copyright (c) 2015 SUSE Linux GmbH. All rights reserved. # # This file is part of kiwi. # # kiwi 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 la...
es(): warn_me = False if '-X' in rsync_options: rsync_options.remove('-X') warn_me = True if '-A' in rsync_options: rsync_options.remove('-A') warn_me = True if warn_me: log.warning( ...
d attributes not supported for target: %s', self.target_dir ) if exclude: for item in exclude: exclude_options.append('--exclude') exclude_options.append( '/' + item ) if os.path.exists(se...
# -*- coding: utf-8 -*- # vim: ft=python:sw=4:ts=4:sts=4:et: import requests import decimal from datetime import timedelta from xml.etree import ElementTree from django_bnr.models import Rate def get_bnr_rate(date, currency='USD'): try: rate = Rate.objects.get(date=date, currency=currency) retur...
= 7: raise RuntimeError('Cannot get exchange rate for ' '%(currency)s from %(date)s' % { 'currency': currency, 'date': date }) ...
e=rate) except: pass return rate
//github.com/NVIDIA/DIGITS """ Classify an image using individual model files imported from DIGITS This tool is for testing your deployed model with images from the test folder. All the configuration params are removed or commented out as compared to the original example.py - Copy your digits trained model to the...
print if __name__ == '__main__': script_start_time = time.time() parser = argparse.ArgumentParser(description='Classification example - DIGITS') ### Positional arguments parser.add_argument
('caffemodel', help='Path to a .caffemodel') parser.add_argument('deploy_file', help='Path to the deploy file') parser.add_argument('image_file', nargs='+', help='Path[s] to an image') ### Optional arguments parser.add_argument('-m', '--mean', ...
index) del Node.allnodes[index] def _write_data(writer, data): "Writes datachars to writer." data = string.replace(data, "&", "&amp;") data = string.replace(data, "<", "&lt;") data = string.replace(data, "\"", "&quot;") data = string.replace(data, ">", "&gt;") writer.write(data) de...
def _getElementsByTagNameNSHelper(parent, nsURI, localName, rc): for node in parent.chil
dNodes: if node.nodeType == Node.ELEMENT_NODE: if ((localName == "*" or node.tagName == localName) and (nsURI == "*" or node.namespaceURI == nsURI)): rc.append(node) _getElementsByTagNameNSHelper(node, name, rc) class Attr(Node): nodeType = Node.ATTRI...
from pandac.PandaModules import * from direct.distributed.ClockDelta import * from direct.interval.IntervalGlobal import * from ElevatorConstants import * from ElevatorUtils import * import DistributedElevator import DistributedElevatorExt from toontown.toonbase import ToontownGlobals from direct.directnotify import Di...
ifyGlobal from direct.fsm import ClassicFSM from direct.fsm import State from toontown.hood import ZoneUtil from toontown.toonbase import TTLocalizer from toontown.toontowngui import TTDialog class DistributedBossElevator(DistributedElevatorExt.DistributedElevatorExt): def __init__(self, cr): DistributedE...
__init__(self, cr) self.elevatorPoints = BigElevatorPoints self.openSfx = base.loadSfx('phase_9/audio/sfx/CHQ_FACT_door_open_sliding.ogg') self.finalOpenSfx = base.loadSfx('phase_9/audio/sfx/CHQ_FACT_door_open_final.ogg') self.closeSfx = base.loadSfx('phase_9/audio/sfx/CHQ_FACT_door_open...
# -*- coding:
utf-8 -*- """ website.api ~~~~~~~~~~~ website api blueprint. """
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this fil
e except in compliance with the License. You may obtain # a copy of the License at # # http://www.apac
he.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 governing permissions and limitat...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_liter
als try: from builtins import * from future import standard_library standard_library.
install_aliases() except: # we might be on py3.2, which the future library doesn't support pass import os import sys if sys.version_info < (2, 7, 0): # pragma: no cover import unittest2 as unittest else: import unittest from layeredconfig import LayeredConfig, Defaults, Environment, INIFile @unit...
eto': imp_neto, 'impto_liq': impto_liq, 'impto_liq_rni': impto_liq_rni, 'imp_op_ex': imp_op_ex, 'imp_tot_conc': imp_tot_conc, 'imp_perc': imp_perc, 'imp_perc_mun': imp_perc_mun, 'imp_iibb': imp_iibb, 'imp_internos': imp_internos, 'i...
ient.BF
EAuthorize( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit}, Cmp={ 'Id': id, 'Zona': f['zona'], 'Fecha_cbte': f['fecha_cbte'], 'Tipo_cbte': f['tipo_cbte'], 'Punto_vta': f['punto_vta'], ...
update[x], Bullet): self.to_update[x].update() elif isinstance(self.to_update[x], EnemyDrop): self.to_update[x].update() elif isinstance(self.to_update[x], HealthPack): self.to_update[x].update() elif isinstance(self.to_update[x], NoteC...
HealthPack(-random.randint(1
, 2), pos) self.package_list.append(h) def input(self, event_list): # player input key = pygame.key.get_pressed() if key[pygame.K_UP]: self.player.move(-1) if key[pygame.K_DOWN]: self.player.move(1) if key[pygame.K_SPACE]: self...
"""A torture test to ferret out problems with multi-threading.""" import sys import threading from ndb import tasklets from ndb import eventloop def main(): ##sys.stdout.write('_State.__bases__ = %r\n' % (eventloop._State.__bases__,)) num = 10 try: num = int(sys.argv[1]) except Exception: pass thr...
get_event_loop())) x = yield fibonacci(num) sys.stdout.write('%d: %d --> %d\n' % (i, num, x)) @tasklets.tasklet def fibonacci(n): """A recursive Fibonacci to exercise task switching.""" if n <= 1: raise tasklets.Return(n) a = yield fibonacci
(n - 1) b = yield fibonacci(n - 2) raise tasklets.Return(a + b) if __name__ == '__main__': main()
from struct import pack from sqlite3 import Binary def pts(c): return ["dd",[c.X,c.Y]] def pt4mp(c): return ["Bidd",[1,1,c.X,c.Y]] def mp(coordinates): partCount=coordinates.partCount i=0 out = ["I",[0]] while i<partCount: pt = coordinates.getPart(i) [ptrn,c]=pt4mp(pt...
es)) def makeMultiPolygon(c): if c.partCount==1: values = ["<BI",1,3] [ptrn,coords]=linearRing(c.getPart(0)) elif c.partCount>1: values = ["<BI",1,6] [ptrn,coords]=multiRing(c) else: return False values[0]+=ptrn values.extend(coords) return Bin...
ltipoint": return lambda row: makeMultiPoint(row.getValue(field)) elif type == "polyline": return lambda row: makeMultiLineString(row.getValue(field)) elif type == "polygon": return lambda row: makeMultiPolygon(row.getValue(field))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
dependencies = [ ('index', '0004_repository_public'), ] operations = [
migrations.AddField( model_name='project', name='related_project', field=models.ForeignKey(blank=True, to='index.Project', null=True), preserve_default=True, ), ]
if hasattr(sys, "frozen"): plugin_path = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "PyQt5", "plugins") Logger.log("i", "Adding QT5 plugin path: %s" % (plugin_path)) QCoreApplication.addLibraryPath(plugin_path) else: import...
sage catalog that can be used # by Qt's translation system, like qsTr() in QML files. # # \param file The file name to load, without extension. It will be searched for in # the i18nLocation Resources directory. If it can not be found a warning # will be logged but no ...
nguage is looked up based on system locale. # If the specified language can not be found, this method will fall back to # loading the english translations file. # # \note When `language` is `default`, the language to load can be changed with the # enviro...
# -*- coding:utf-8 -*- """ 一些能够帮你提升效率的辅助函数 """ from __future__ import unicode_literals, division from copy import deepcopy from datetime import timedelta from threading import Thread import requests import requests.exceptions from six.moves import urllib from .log import logger from .value import ENV __all__ = ['ge...
de(term_str): """ 将学期字符串转换为对应的学期代码串 :param term_str: 形如 "2012-2013学年第二学期" 的学期字符串 :return: 形如 "022" 的学期代码 """ result = ENV['TERM_PATTERN'].match(term_str).groups() year = int(result[0]) return cal_term_code(year, result[1] == '一') def sort_hosts(hosts,
method='GET', path='/', timeout=(5, 10), **kwargs): """ 测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000 :param method: 请求方法 :param path: 默认的访问路径 :param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']` :param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖 :param kwargs: 其他传递到 ``requests.re...
Appearance"]["Add layers list"]: controls.append('new ol.control.LayerSwitcher({tipLabel: "Layers"})') mapbounds = bounds(iface, settings["Scale/Zoom"]["Extent"] == "Canvas extent", layers) mapextent = "extent: %s," % mapbounds if settings["Scale/Zoom"]["Restrict to extent"] else "" ...
) });''' % {"n": layerName, "extent": sExtent, "col": provider.xSize(),
"name": layer.name(), "row": provider.ySize()} def exportStyles(layers, folder): stylesFolder = os.path.join(folder, "styles") QDir().mkpath(stylesFolder) for layer in layers: if layer.type() != layer.VectorLayer: continue labelsEnabled = unicode(layer.customProperty("lab...
import unittest import modular_core.libfundamental as lfu from modular_core.libsimcomponents import ensemble_manager as mng import os, sys, pdb #log = open(os.path.join(os.getcwd(), 'test_ensembl
e.log'), 'w') #sys.stdout = log import lattice as mod class dummyTestCase(unittest.TestCase): """Tests for `dummy module`.""" simple_mcfg = os.path.join(os.getcwd(), 'lattice_dep_mcfgs', 'lattice_example.mcfg') mn = mng() en = mn.add_ensemble(module = mod.main.module_name) def pause(self, *args, **kwa...
.stdout = log def test_can_make_ensemble(self): """module successfully imported?""" self.assertFalse(mod.main == None) mod_name = mod.main.module_name ensem = self.mn.add_ensemble(module = mod_name) self.assertFalse(ensem is None) def test_can_run_mcfg(self): ran = self.en.run_mcfg(self.simple_mcfg) o...
'0': 'Off', '1': 'On', '2': 'Data Extracted' }, 'state': { '0': 'Stopped - Not at Zero Position', '1': 'Tracking (PEC disabled)', '2': 'Slewing', '3': 'Guiding', '4': 'Merid...
g('Mount has not been initialized')
assert self.location is not None, self.logger.warning( 'Please set a location before attempting setup')
selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.common.exceptions import UnexpectedAlertPresentException, ElementNotVisibleException from TmallSingleCrawler.utils.TMallUtils import ge...
meta={"item": goods_item}) except: continue # 进入下一页 next_page = "https://list.tmall.com/search_product.htm" + response.css( ".ui-page-next::attr(href)").extract_first("") yield scrapy.Request(url=next_page, callback=self.parse) ...
上面同理 if response.status == 302: # if response.headers.has_key("location"): # location = str(response.headers['Location'], encoding="utf-8") # redirect_url = "" # # if location.find("sec.taobao") > 0: # self.parse_code(u...
import numpy as np from ._layout import Layout from ._multivector import MultiVector class ConformalLayout(Layout): r""" A layout for a conformal algebra, which adds extra constants and helpers. Typically these should be constructed via :func:`clifford.conformalize`. .. versionadded:: 1.2.0 At...
or The null basis vector at the origin, :math:`e_o = 0.5(e_{-} - e_{+})` einf : MultiVector The null vector at infinity, :math:`e_\infty = e_{-} + e_{+}`
E0 : MultiVector The minkowski subspace bivector, :math:`e_\infty \wedge e_o` I_base : MultiVector The pseudoscalar of the base ga, in cga layout """ def __init__(self, *args, layout=None, **kwargs): super().__init__(*args, **kwargs) self._base_layout = layout ep, e...
"""deCONZ climate platform tests.""" from unittest.mock import Mock, patch import asynctest from homeassistant import config_entries from homeassistant.components import deconz from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.setup import async_setup_component import homeassistan...
ONN_CLASS_LOCAL_PUSH) gateway = deconz.DeconzGateway(hass, config_entry) gateway.api = DeconzSession(hass.loop, session, **config_entry.data) gateway.api.config = Mock() hass.data[deconz.DOMAIN] = gateway with patch('pydeconz.DeconzSession.async_get_state', return_value=mock_coro(dat...
# To flush out the service call to update the group await hass.async_block_till_done() async def test_platform_manually_configured(hass): """Test that we do not discover anything or try to set up a gateway.""" assert await async_setup_component(hass, climate.DOMAIN, { 'climate': { ...
:,2] = -0.5*k*sumxy K[:,:,3] = theta[2]*np.eye(d1,d2) return K else: return k + measnoise*theta[2]*np.eye(d1,d2) def kernel(data1,data2,theta,wantderiv=True,measnoise=1.): theta = np.squeeze(theta) # Squared exponential and periodic if np.shape(data1)[0] == len(data1): d1 = np.shape(data1)[0] n = 1 els...
n-2*np.sqrt(var)),np.squeeze(mean+2*np.sqrt(var)),color='0.75') pl.plot(x,t,'ko') pl.axis('tight') pl.xlabel('x') pl.ylabel('f(x)') print np.shape(mean), np.shape(var) def showlength(theta,scale)
: x = scale*np.array([[-3.5, -2.5, -.5, .4, 2.25]]).transpose() t = 0.55*np.array([[-2., 0, 1., 2., -1.]]).transpose() xstar = np.reshape(np.linspace(-5,5,100),(100,1)) k = kernel2(x,x,theta,wantderiv=False) print k #print k kstar = [kernel2(x,xs*np.ones((1,1)),theta,wantderiv=False,measnoise=False) for xs in ...
#!/usr/bin/env python from setuptools import setup, find_packages import chagallpy setup( name='chagallpy', version=chagallpy.__version__, packages=find_packages(), license='MIT', description='CHArming GALLery in PYthon', long_description_content_type="text/markdown"
, long_description=open('README.md').read(), author='Jan Pipek', author_email='jan.pipek@gmail.com', url='https://github.com/janpipek/chagallpy', install_requires=['wow
p', 'pillow', "jinja2", "pyyaml", "click"], python_requires="~=3.6", entry_points={ 'console_scripts': [ 'chagall = chagallpy:generate' ] }, include_package_data=True, package_data={ 'resources': ['*.*'], 'templates': ['*.html'] }, )
#!/usr/bin/python # -*- coding: utf-8 -*- ############################################################################## # # DTE Chile OpenERP 7 # Copyright (C) 2016 Cesar Lopez Aguillon Mall Connection # <http://www.mallconnection.org>. # This program is free software: you can redistribute it and/or modify # ...
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 <http://www.gnu.org/licenses/>. # ############################################################################## import model import report import controllers # vim:expand...
"""Read and write configuration settings """ from milc import cli def print_config(section, key): """Print a single config setting to stdout. """ cli.echo('%s.%s{fg_cyan}={fg_reset}%s', section, key, cli.config[section][key]) def show_config(): """Print the current configuration to stdout. """ ...
n cli.args.configs: # Split on space in case they quoted multiple config tokens for config_token in argument.split(' '): section, option, value = parse_config_token(config_token) # Validation if option and '.' in option: cli.log.error('Config keys may...
# Do what the user wants if section and option and value: # Write a configuration option set_config(section, option, value) if not cli.args.read_only: save_config = True elif section and option: # Display a si...
from django.contrib import admin from . import models class OrderItemInline(admin.TabularInline): fields = ('product', 'quantity') raw_id_fields = ('product',) model = models.OrderItem extra = 1 class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'description', 'stock', 'discont...
, 'body', 'rating', 'pub_date') search_fields = ('title', 'body') list_filter = ('pub_date', 'rating') date_hierarchy = 'pub_date' fields = ('user', 'product', 'title', 'body', 'rating') raw_id_fields = ('user', 'product') class OrderAdmin(admin.ModelAdmin): list_display = ('user', 'street', 'c...
date_hierarchy = 'purchase_date' fields = ('street', 'city', 'state', 'zip_code') inlines = (OrderItemInline,) admin.site.register(models.Product, ProductAdmin) admin.site.register(models.Review, ReviewAdmin) admin.site.register(models.Order, OrderAdmin)
# -*- coding: utf-8 -*- VERSION = (0, 1, 6, 'final') if VERSION[-1] != "final": # pragma: no cover __version__ = '.'.join(map(str, VERSION)) else: # pragma: no cover __version__ = '.'.join(ma
p(str, VERSIO
N[:-1]))
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
'12/12/12 12:12:00') r_client.hset(self.token, 'gran
t_type', 'client') r_client.expire(self.token, 20) super(OauthTestingBase, self).setUp()
#!/usr/bin/env python ''' fit best estimate of magnetometer offsets, trying to take into account motor interference ''' import sys, time, os, math from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("--no-timestamps",dest="notimestamps", action='store_true', help="Log...
# discard outliers, keep the middle 3/4 data = data[len(data)/8:-len(data)/8] # fit again (offsets, motor_ofs, field_strength) = fit_data(data) print("Final : %s %s field_strength=%6.1f to %6.1f" % ( offsets, motor_ofs, radi
us(data[0], offsets, motor_ofs), radius(data[-1], offsets, motor_ofs))) print "mavgraph.py '%s' 'mag_field(RAW_IMU)' 'mag_field_motors(RAW_IMU,SENSOR_OFFSETS,(%f,%f,%f),SERVO_OUTPUT_RAW,(%f,%f,%f))'" % ( filename, offsets.x,offsets.y,offsets.z, motor_ofs.x, motor_ofs.y, motor_ofs.z) total =...
import libtcodpy as libtcod from menu import Menu from menu_manager import MenuStatus from menu_game import MenuGame from ui.frame_main_menu import FrameMainMenu class MenuMain(Menu): def __init__(self, width, height): Menu.__init__(self, width, height) self.menu_frame = FrameMainMenu(width, height) def update...
f dra
w(self): #print("drawing MenuMain") self.menu_frame.draw()
from django.contrib import admin from django.co
ntrib.admin import ModelAdmin from paywall.models import PaymentEntry @admin.register(P
aymentEntry) class PaymentEntryAdmin(ModelAdmin): pass
nd averageFlag == True: count = 0 for curr_Key in right_data: if count > 14: break try: average_right_data[curr_Key] /= initial_Gap_Interval except: pass ...
ht["shortcu
ts"][curr_id] = shortcuts for i in list(range(15)): # Max Acceleration # val = get_data_from_Data_Repository(str(i), curr_id) # if val < right_data[i]: data_repository_right[str(i)][curr_id] = right_data[i] ...
import logging # noinspection PyUnresolvedReferences import feature #noqa logging.basicConf
ig(level=logging.DEBUG) class Rollout(object): __version__ = '0.3.5' def __init__(self, feature_storage=None, user_storage=None, undefined_feature_access=False): """ Manage feature flags for groups, users, or on a percentage basis. Use your own user models and persistence with replace...
am user_storage: Object to manage storage of users :type user_storage: pyrollout.storage.UserStorageManager :param undefined_feature_access: Should undefined features be allowed (default:True) or denied (False) access? :type undefined_feature_access: bool """ if feature_storage i...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('widgetbox', '0010_html'), ] operations = [ migrations.AddField(
model_name=
'button', name='extra_css_classes', field=models.CharField(max_length=200, blank=True), preserve_default=True, ), ]
#!/usr/bin/env python impor
t os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wellspring.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
import sys sys.path.append("../../") from
unittes
t.mock import patch, MagicMock MockRPi = MagicMock() MockSpidev = MagicMock() modules = { "RPi": MockRPi, "RPi.GPIO": MockRPi.GPIO, "spidev": MockSpidev } patcher = patch.dict("sys.modules", modules) patcher.start() from gfxlcd.driver.ssd1306.spi import SPI from gfxlcd.driver.ssd1306.ssd1306 import SSD13...
#! /usr/bin/env python # This file is part of khmer, https://github.com/dib-lab/khmer/, and is # Copyright (C) 2010-2015, Michigan State University. # Copyright (C) 2015, The Regents of the University of California. # # Redistribution and use in source and binary forms, with or without # modification, are permitted pro...
help='Overwrite existing output_histogram_filename') parser.a
dd_argument('-b', '--no-bigcount', dest='bigcount', default=True, action='store_false', help='Do not count k-mers past 255') parser.add_argument('--version', action=_VersionStdErrAction, version='khmer {v}'.format(v=__version__)) parser.add...
# Generated by Django 3.0.7 on 2020-08-03 08:42 from django.db import migrations, models import weblate.utils.validators class Migration(migrations.Migration): dependencies = [ ("trans", "0093_auto_20200730_1432"), ]
operations = [ migrations.AddField( model_name="project", name="language_aliases", field=models.CharField( default="", blank=True, help_text="Comma-separated list of language code mappings, for example: en_GB:en,en_US:en", ...
validators=[weblate.utils.validators.validate_language_aliases], verbose_name="Language aliases", ), ), ]
from django.conf import settings from django.test import TestCase, TransactionTestCase from django.test.simple import DjangoTestSuiteRunner from django.test.runner import reorder_suite from django.utils.importlib import import_module from django.utils.unittest.loader import defaultTestLoader class DiscoveryDjangoTe...
0]).__path__[0] if suite is None: suite = defaultTestLoader.discover( discovery_root, top_level_dir=settings.BASE_
PATH, ) if extra_tests: for test in extra_tests: suite.addTest(test) return reorder_suite(suite, ( TestCase, TransactionTestCase, ))
# ---------------------------------------------------------------------- # author : Martin Ruchti # contact : martin.ruchti@tum.de # ---------------------------------------------------------------------- from __future__ import print_function, absolute_import, division from numpy import * from .variables import * '''...
(not is_converged and iteration_number < self.max_iteration_number): # do build and solve self.A, self.dx, self.b = self.builder_and_solver.BuildAndSolve(self.A, self.x, self.
b) # call scheme to do update self.scheme.Update(self.builder_and_solver.dofset, self.dx) #check for convergence error_L2_norm = 0.0 for i in range(0,len(self.dx)): error_L2_norm += (self.dx[i])**2 ...
jango.forms.models import inlineformset_factory from django.db import transaction from django.db.models import F from django.forms.util import ErrorList from geonode.tasks.deletion import delete_layer from geonode.services.models import Service from geonode.layers.forms import LayerForm, LayerUploadForm, NewLayerUploa...
os.path.splitext( form.cleaned_data["ba
se_file"].name) name = slugify(name_base.replace(".", "_")) try: # Moved this inside the try/except block because it can raise # exceptions when unicode characters are present. # This should be followed up in upstream Django. tempdi...
elf.taps)).flatten()) self.mtimecurve_i_stems.setData([],[]) self.mtimecurve_i.setData([],[]) # Configure plots. if self.mtoverlay: self.mplots['mTIME'].setMouseEnabled(x=True, y=True) else: self.mplots['mTIME'].setMouseEnabled(x=False,...
self.imprescurve_i.setData(np.arange(ntaps), impres.imag) else:
self.imprescurve_stems.setData(np.repeat(np.arange(ntaps), 2), np.dstack((np.zeros(impres.shape[0], dtype=int), impres)).flatten()) if self.mtimpulse: if(type(impres[0]) == np.complex128): ...
from django.conf.urls.defaults import * from corehq import AccountingAdminInterfaceDispatcher from cor
ehq.apps.accounting.views import * urlpatterns = patterns('corehq.apps.accounting.views', url(r'^$', 'accounting_default', name='accounting_default'), url(r'^accounts/(\d+)/$', ManageBillingAccountView.as_view(),
name=ManageBillingAccountView.urlname), url(r'^accounts/new/$', NewBillingAccountView.as_view(), name=NewBillingAccountView.urlname), url(r'^subscriptions/(\d+)/$', EditSubscriptionView.as_view(), name=EditSubscriptionView.urlname), url(r'^accounts/new_subscription/$', NewSubscriptionViewNoDefaultDomain.as_...
(name): out = '' word_start = True for c in name: if c == '_': out += '-' word_start = True elif word_start: out += c.upper() word_start = False else: out += c.lower() return out def _req_to_item(req): item = dict() item['method'] = req.method item['path'] = req.path query = req.META.get('...
tpResponse('Refreshed\n') else: return HttpResponseNotAllowed(['POST']) def respond(req, inbox_id, item_id): if req.method =
= 'POST': try: content = json.loads(req.body) except: return HttpResponseBadRequest('Bad Request: Body must be valid JSON\n') try: code = content.get('code') if code is not None: code = int(code) else: code = 200 reason = content.get('reason') headers = content.get('headers') if...
put_shapes[0] # Explicitly unroll the recurrence instead of using scan cell_out, hid_out = unroll_scan( fn=step_fun, sequences=sequences, outputs_info=[cell_init, hid_init], go_backwards=self.backwards, ...
elf.hid_init_incoming_index > 0: hid_init = inputs[self.hid_init_incoming_index] # Treat all dimensions after the second as flattened feature dimensions if input.ndim > 3: input = T.flatten(input, 3) # Because scan iterates over the first dimension w...
s) input = input.dimshuffle(1, 0, 2) seq_len, num_batch, _ = input.shape # Stack input weight matrices into a (num_inputs, 3*num_units) # matrix, which speeds up computation W_in_stacked = T.concatenate( [self.W_in_to_resetgate, self.W_in_to_u...
__author__ = 'davedash'
class WheeljackException(Exception): pass class RepoNotFoundException(WheeljackException): """Exception thrown when we interact with an undefined Repo.""" pas
s class RepoAlreadyInstalledException(WheeljackException): """Exception thrown when we try to re-install a repo.""" pass class ReposConfigException(WheeljackException): """Exception raised when there is a configuration error.""" pass class WheeljackCodeDirectoryMissing(WheeljackException): """...
#!/usr/bin/env python3 # Copyright (c) 2017-2020 The Fujicoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test wallet load on startup. Verify that a fujicoind node can maintain list of wallets loading on sta...
filename='w4', load_on_startup=True) assert_equal(set(self.nodes[0].listwallets()), set(('', 'w1', 'w2', 'w3', 'w4'))) self.restart_node(0) assert_equal(set(self.nodes[0].listwallets()), set(('', 'w2', 'w4'))) self.nodes[0].unloadwallet(wallet_name='', load_on_startup=False) self...
self.restart_node(0) assert_equal(set(self.nodes[0].listwallets()), set(('w2', 'w3'))) if __name__ == '__main__': WalletStartupTest().main()
from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Table from sqlalchemy.orm import relationship, backref from models import DecBase from models.document import Document from models.keyword import Keyword from jsonschema import * from json_schemas import * from models.collection_version import ...
or joining defined tables together collection_keywords = Table('collection_keywords', DecBase.metadata, Column('keyword_id', Integer, ForeignKey('keyword.id')), Column('collection_address', String, ForeignKey('collection.address')) ...
on_docs = Table('collection_docs', DecBase.metadata, Column('document_address', String, ForeignKey('document.hash')), Column('collection_address_docs', String, ForeignKey('collection.address')) ) hash_association = Table('collection_ha...
import hashlib import requests import threading import json import sys import traceback import base64 import electrum_vtc as electrum from electrum_vtc.plugins import BasePlugin, hook from electrum_vtc.i18n import _ class LabelsPlugin(BasePlugin): def __init__(self, parent, config, name): BasePlugin....
.on_pulled(wallet) except Exception as e: traceback.print_exc(file=sys.stderr)
self.print_error("could not retrieve labels") def start_wallet(self, wallet): nonce = self.get_nonce(wallet) self.print_error("wallet", wallet.basename(), "nonce is", nonce) mpk = wallet.get_fingerprint() if not mpk: return password = hashlib.sha1(mpk).digest(...
""" Integration tests for mac_timezone If using parallels, make sure Time sync is turned off. Otherwise, parallels will keep changing your date/time settings while the tests are ru
nning. To turn off Time sync do the following: - Go to actions -> configure - Select options at the top and 'More Options' on the left - Set time to 'Do not sync' """ import datetime import pytest from tests.support.case import ModuleCas
e from tests.support.unit import skipIf @pytest.mark.flaky(max_runs=4) @pytest.mark.skip_unless_on_darwin @pytest.mark.skip_if_binaries_missing("systemsetup") @pytest.mark.skip_if_not_root class MacTimezoneModuleTest(ModuleCase): """ Validate the mac_timezone module """ USE_NETWORK_TIME = False T...
# -*- coding: utf-8 -*- # Scrapy settings for appstore project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'appstore' SPIDER_MODULES = ['appstore.spiders'] N...
S = { 'appstore.pipelines.AppstorePipeline': 300, } DOWNLOAD_DELAY=5 # Crawl responsibly by identifying yourse
lf (and your website) on the user-agent #USER_AGENT = 'appstore (+http://www.yourdomain.com)'
max_features=2, random_state=1) gbrt.fit(X_train, y_train) deviance = gbrt.loss_(y_test, gbrt.decision_function(X_test)) assert_true(deviance < 0.5, "GB failed with deviance %.4f" % deviance) def test_max_feature_auto(): # Test if max features is set properly for floats and...
t(X, y) for func in ['predict', 'decision_function', 'predict_proba']: staged_func = getattr(estimator, "staged_" + func, None) if staged_func is None: # regressor has no staged_predict_proba continue with warnings.catch_warnings(record=True): ...
staged_result[1][:] = 0 assert_true(np.all(staged_result[0] != 0)) def test_serialization(): # Check model serialization. clf = GradientBoostingClassifier(n_estimators=100, random_state=1) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result) assert_equal(100, len(clf.esti...