prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from nose.tools import * from unittest import TestCase import os from shutil import rmtree from
tempfile import mkdtemp from fnmatch import fnmatch from files.file_matcher_glob import FileMatcherGlob class FileMatcherGlobTests(TestCase): def setUp(self): self.directory = mkdtemp('-caboose-file-matcher-glob-tests') def tearDown(self): rmtree(self.directory) def test_file_matcher_mat...
b("*.java") eq_(True, self.file_matcher.match("hello.java")) eq_(False, self.file_matcher.match("hello.java2")) def test_file_matcher_matches_against_unicode_glob(self): self.file_matcher = FileMatcherGlob(u"*.java") eq_(True, self.file_matcher.match("hello.java")) e...
"""Test kytos.core.buffers module.""" import asyncio from unittest import TestCase from unittest.mock import MagicMock, patch from kytos.core.buffers import KytosBuffers, KytosEventBuffer # pylint: disable=protected-access class TestKytosEventBuffer(TestCase): """KytosEventBuffer tests.""" def setUp(self): ...
ignal(self): """Test send_stop_signal method.""" self.kytos_buffers.send_stop_signal() self.assertTrue(self.kytos_buffers.raw._reject_new_events) self.assertTrue(self.kytos_buffers.msg_in._reject_new_events) self.assertTrue(self.kytos_buffers.msg_out._reject_new_events)
self.assertTrue(self.kytos_buffers.app._reject_new_events)
#! /usr/bin/en
v python3 from .config import
* from .diff import * from .HtmlFormatter import * from .AnsiFormatter import *
import datetime import nrkdownload.utils def test_valid_filename(string=r":blah/bl:ah.ext"): filename = nrkdownload.utils.valid_filename(string) assert filename == "blahblah.ext" def test_parse_duration(string="PT3H12M41.6S"): # PT28M39S : 28m39s # PT3H12M41
.6S : 3h12m41.6s duration = nrkdownload.utils.parse_duration(string) assert duration == datetime.timedelta(hours
=3, minutes=12, seconds=41.6) duration = nrkdownload.utils.parse_duration("") assert duration == datetime.timedelta() # duration = nrkdownload.utils.parse_datetime('not_a_duration') # assert duration == datetime.timedelta() def test_classmethod(): c = nrkdownload.utils.ClassProperty() assert ...
#!/usr/bin/env py
thon import unittest from aminer import AMinerParser class AMinerParserTest(unittest.TestCase): SINGLE_TEST_FILE = "./aminer_single.txt" def setUp(self): self.single_test = open(self.SINGLE_TEST_FILE, "r") def test
_single_parse(self): p = AMinerParser() if __name__ == "__main__": unittest.main()
in_booklet self.parse_pages_booklet() def parse_pages_booklet(self): full_page_parsed = True index = None while full_page_parsed: if index: params = {'First': index[0], 'Start': index[1]} else: params = None soup_cu...
1: if existing_count > 1: logger.warn("found two objects with the url %s. Taking the first" % pdf_url)
link = Link.objects.filter(url=pdf_url).first() filename = None if existing_count > 0: files = [f for f in link.linkedfile_set.order_by('last_updated') if f.link_file.name != ''] if len(files) > 0: link_file = files[0] filename = link_file.li...
#!/usr/bin/env python #-*- coding:utf-8 -*- import logging, os.path import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.websocket import tornado.gen class Application(tornado.web.Application): def __init__(self): base_dir = os.path.dirname(__file__) ...
if self in WebSocketHandler.listenners: WebSocketHandler.listenners.remove(self) @tornado.gen.engine def on_message(self, wsdata): for listenner in WebSocketHandler.listenners: listenner.write_message(wsdata) @tornado.gen.coroutine def main(): tornado.options.parse...
p://localhost:8888") if __name__ == "__main__": tornado.ioloop.IOLoop.current().run_sync(main) tornado.ioloop.IOLoop.current().start()
#!/usr/bin/env python # Calculate a table of pairwise energies and forces between "INT" atoms # in the lipid membrane model described in # Brannigan et al, Phys Rev E, 72, 0119
15 (2005) # The energy of this interaction U(r) = eps*(0.4*(sigma/r)^12 - 3.0*(sigma/r)^2) # I realized later this is not what we want because although energy is conserved # all enrgies are shifted with respect to energies used in the Brannigan paper # (by 0.27 kCal/mole) and the later Watson JCP 2011 paper (by 0.224 k...
sly between 1 and 0 in the range from rc1 to rc2 (rc2>rc1): S(r) = (rc2^2 - r^2)^2 * (rc2^2 + 2*r^2 - 3*rc1^2) / (rc2^2-rc1^2)^3 I'm using the same smoothing/switching cutoff function used by the CHARMM force-fields. (I'm even using the same code to implement it, taken from lammps charmm/coul/c...
# -*- coding: utf-8 -*- import unittest import logging from os.path import isfile from os import popen from os import remove from t2db_objects import objects from t2db_objects.utilities import formatHash from t2db_objects.parameters import generate_config_yaml from clean_text.cleaner import sentenceCleaner from cle...
nd a sample" self.assertEqual(sentenceCleaner(sentence, ["removeUrl", "removeUserMention"]), goldenSentence) def test_tokenize(self): sentence = "Hello didn't very happy 1313" goldenTokens = ["Hello" , "did", "n't", "very", "happy", "1313"] tokens = tokenize(sentence) for i in range(0, len(toke...
tokens = tokenize(sentence) self.assertEqual(sentenize(tokens), goldenSentence) def test_tokenCleaner(self): sentence = "Hello I'm very happy 1313" goldenSentence = "hello" tokens = tokenize(sentence) functions.stopwords = load_stopwords('etc/stopwords_en.txt') newTokens = tokenCleaner(to...
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free ...
warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server license may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial L...
workers executing jobs for the manager """ __version__ = "$Rev: 6125 $"
import graphene from .account.schema import AccountMutations, AccountQueries from .checkout.schema import CheckoutMutations, CheckoutQueries from .core.schema import CoreMutations from .discount.schem
a import DiscountMutations, DiscountQueries from .menu.schema import MenuMutations, MenuQueries from .o
rder.schema import OrderMutations, OrderQueries from .page.schema import PageMutations, PageQueries from .payment.schema import PaymentMutations, PaymentQueries from .product.schema import ProductMutations, ProductQueries from .shipping.schema import ShippingMutations, ShippingQueries from .shop.schema import ShopMutat...
# Copyright (c) 2018 PaddlePaddle 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 app...
st_reader = paddle.batch( paddle.da
taset.mnist.test(), batch_size=BATCH_SIZE) avg_cost, acc = trainer.test( reader=test_reader, feed_order=['img', 'label']) print("avg_cost: %s" % avg_cost) print("acc : %s" % acc) if acc > 0.2: # Smaller value to increase CI speed tra...
#coding=UTF-8 from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext from pyspark.sql.types import * from datetime import date, datetime, timedelta import sys, re, os st = datetime.now() conf = SparkConf().setAppName('PROC_O_IBK_WSYH_ECUSRLOGINTYPE').setMaster(sys.argv[2]) sc = SparkContext(conf = c...
TLOGINADDR --最后一次登录地址:src.LASTLOGINADDR ,DST.CREATEUSERSEQ --创建用户顺序号:src.CREATEUSERSEQ ,DST.CREATEDEPTSEQ --创建机构顺序号:src.CREATEDEPTSEQ ,DST.CREATETIME ...
--更新机构顺序号:src.UPDATEDEPTSEQ ,DST.UPDATETIME --更新时间:src.UPDATETIME ,DST.FR_ID --法人号:src.FR_ID ,DST.ODS_ST_DATE --系统日期:src.ODS_ST_DATE ,DST.ODS_SY...
import concurrent.futures from itertools import islice import xbmc import threading Executor = concurrent.futures.ThreadPoolExecutor def execute(f, iterable, stop_flag=None, workers=10, timeout=30): with Executor(max_workers=workers) as executor: threading.Timer(timeout, stop_flag.set) for future...
unner(executor, workers, f, iterable, timeout): if xbmc.abortRequested: break if stop_flag and stop_flag.isSet(): break yield future.result() def _batched_pool_runner(pool, batch_size, f, iterable, timeout)...
rrent.futures.as_completed(futures, timeout): yield item except: pass
from src.settings import Colors def league_color(league: str) -> Colors: if league in [ ]: return Colors.GREEN if league in [ '1 CFL (Montenegro)', 'A Lyga (Lithuania)', 'Bikar (Iceland)', 'Coupe de la Ligue (France)', 'EURO Qualifiers (Europe)', 'F...
England)', 'J-League (Japan)', 'J-League 2 (Japan)', 'K-League (South Korea)', 'Landspokal (Denmark)', 'League Cup (Scotland)', 'Meistriliiga (Estonia)', 'OFB Cup (Austria)', 'Pohar CMFS (Czech Republic)', 'Premier League
(Wales)', 'Primera Division (Chile)', 'Proximus League (Belgium)', 'Serie A (Italy)', 'S-League (Singapore)', 'Slovensky Pohar (Slovakia)', 'Svenska Cupen (Sweden)', 'Swiss Cup (Switzerland)', 'Virsliga (Latvia)', 'Vyscha Liga (Ukraine)', '...
# Third-party import astropy.units as u import numpy as np # Project from ....dynamics import PhaseSpacePosition, Orbit from ....units import galactic PSP = PhaseSpacePosition ORB = Orbit class _TestBase(object): use_half_ndim = False E_unit = u.erg/u.kg @classmethod def setup_class(cls): np...
urn_shapes += [(ntimes, norbits)]*2 cls.gradient_return_shapes += [(r_ndim, ntimes, norbits)]*2 cls.hessian_return_shapes += [(r_ndim, r_ndim, ntimes, norbits)]*2 _obj_w0s = cls.w0s[:] for w0, eshp, gshp, hshp in zip(_obj_w0s, cls.energy_return_sh...
cls.energy_return_shapes.append(eshp) cls.gradient_return_shapes.append(gshp) cls.hessian_return_shapes.append(hshp) def test_energy(self): for arr, shp in zip(self.w0s, self.energy_return_shapes): if self.E_unit.is_equivalent(u.one) and hasattr(arr, 'pos') and \ ...
import os
def get_html_theme_path(): theme_dir = os.path.abspath(os.path.dirname(os.path
.dirname(__file__))) return theme_dir
SRC}.abin' always_run = True def keyword(self): return "Generating" def __str__(self): return self.outputs[0].path_from(self.generator.bld.bldnode) class build_intel_hex(Task.Task): '''build an intel hex file for upload with DFU''' color='CYAN' run_str='${TOOLS_SCRIPTS}/make_int...
group='dynamic_sources', target=[bld.bldnode.find_or_declare('hwdef.h'), bld.bldn
ode.find_or_declare('ldscript.ld')] ) bld( # create the file modules/ChibiOS/include_dirs rule="touch Makefile && BUILDDIR=${BUILDDIR_REL} CHIBIOS=${CH_ROOT_REL} AP_HAL=${AP_HAL_REL} ${CHIBIOS_BUILD_FLAGS} ${CHIBIOS_BOARD_NAME} ${MAKE} pass -f '${BOARD_MK}'", group='dynamic_sour
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-19 10:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0015_auto_20160408_1355'), ] operations = [ migrations.AlterField( ...
field=models.CharField(max_length=120, null=True),
), migrations.AlterField( model_name='service', name='service_code', field=models.CharField(max_length=120, unique=True), ), ]
__copyright__ = """ Copyright (C) 2006, Catalin Marinas <catalin.marinas@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 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be ...
# backup information was already reset above crt_series.refresh_patch(cache_update = False, backu
p = False, log = 'sync') out.done('updated') else: out.done()
# validation 2000 valid_x = train_x[:,10000:] valid_y = train_y[10000:] train_x = train_x[:,:10000] train_y = train_y[:10000] tmp = sio.loadmat(data_dir+'test.mat') test_x = tmp['x_test'].T test_y = tmp['t_test'].T.astype(np.int32) print train_x.shape print train_y.shape pr...
print test_y.shape train_mean_prior = np.zeros((n_z,train_x.shape[1])) test_mean_prior = np.zeros((n_z,test_x.shape[1])) valid_mean_prior = np.zeros((n_z,valid_x.shape[1])) f_enc, f_dec = pp.Identity() x = {'x': train_x.astype(np.float32), 'mean_prior': train_mean
_prior.astype(np.float32)} x_train = x x_valid = {'x': valid_x.astype(np.float32), 'mean_prior': valid_mean_prior.astype(np.float32)} x_test = {'x': test_x.astype(np.float32), 'mean_prior': test_mean_prior.astype(np.float32)} L_valid = 1 dim_input = (size,size) n_x = size*size n_y = 10 t...
tropic(new_structure = '', start_new_version = None, base_calculation = (None, None, None), database = None, min_mult = 1, max_mult = 1, num_points = 2, geo_folder = '', it_folder = '', override = False): """ This function makes set of structures uniformly scaled from the initial one within the range of deform...
- num_points_a (int) - number of different simultaneous deformations of the vectors 1 and 2 - min_mult_c (float) - minimal deformation of the vector 3 of the structure from "base_calculation" - max_mult_c (float) - maximal deformation of the vector 3 of the structure from "b...
- num_points_c (int) - number of different deformations of the vector 3 from "base_calculation" - geo_folder (str) - path to the folder to save *.geo files of newly built structures - it folder (str) - section folder - override (boolean) - if True then the...
d_processes = True self.pmonitor = ep.ProcessMonitor( config=conf, resource_type='test') def get_monitored_process(self, uuid, service=None): monitored_process = mock.Mock() self.pmonitor.register(uuid=uuid, service_name=service, ...
s(TEST_UUID) self.get_monito
red_process(TEST_UUID, TEST_SERVICE) self.assertEqual(len(self.pmonitor._monitored_processes), 2) def test_unregister(self): self.get_monitored_process(TEST_UUID) self.pmonitor.unregister(TEST_UUID, None) self.assertEqual(len(self.pmonitor._monitored_processes), 0) def test_unr...
from datetime import date import os from django.contrib.auth.models import User from django import forms from django.utils import timezone from fields import Html5CaptchaField from html5input import * from settings import AVAILABLE_TEMPLATES, TEMPLATE_DIRS from accounts.models import UserProfile class SettingsUserFor...
) class RecoverPasswordForm(forms.Form): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'required': None})) captcha = Html5CaptchaField(required=True) def clean_username(self): username = self.cleaned_data['username'] user = User.objects.filter(is_active=True, ...
s name exists.") return username class RecoverUsernameForm(forms.Form): email = forms.EmailField(label='email', widget=Html5EmailInput(attrs={'required': None})) captcha = Html5CaptchaField(required=True) def clean_email(self): email = self.cleaned_data['email'] user = User.object...
""" This page is in the table of contents. Plugin to home the tool at beginning of each layer. The home manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home ==Operation== The default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, not...
self.distanceFeedRate.addLine('M103') self.addHopUp( self.oldLocation ) self.distanceFeedRate.addLinesSetAbsoluteDistanceMode(self.homeLines) self.addHopUp( self.oldLocation ) self.addFloat( self.oldLocation, location ) if self.extruderActive: self.distanceFeedRate.addLine('M101') def addHopUp(self, l...
) self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, locationUp.dropAxis(), locationUp.z ) ) def getCraftedGcode( self, gcodeText, repository ): "Parse gcode text and store the home gcode." self.repository = repository self.homeLines = settings...
'registry'][ 'testsuite.models'] = model_definitions() def tearDown(self): del self.app.extensions['registry']['testsuite.fields'] del self.app.extensions['registry']['testsuite.models'] def test_wrong_indent(self): """JSONAlchemy - wrong indent""" from invenio.modu...
creator: bar, '1', foo() """ self.assertRaises(pyparsing.ParseException, parser.parseString, test) from invenio.modules.jsonalchemy.errors import FieldParserExceptio
n tmp_file = tempfile.NamedTemporaryFile() config = """ foo: creator: bar, '1', foo() """ tmp_file.write(config) tmp_file.flush() self.app.extensions['registry'][ 'testsuite.fields'].register(tmp_file.name) clean_field_mode...
.split(__file__)[0] logger = None """Runner for web-platform-tests The runner has several design goals: * Tests should run with no modification from upstream. * Tests should be regarded as "untrusted" so that errors, timeouts and even crashes in the tests can be handled without failing the entire test run. * Fo...
upported test type %s for product %s" %
(test_type, product)) continue with ManagerGroup("web-platform-tests", kwargs["processes"], test_source_cls, test_source_kwargs, ...
Optional[Callable]): A callback that takes no arguments, to be executed when an exception is being raised. Returns: str: The desired header. Raises: ~google.resumable_media.common.InvalidResponse: If the header is missing. """ headers = get_headers(response) ...
return matches[0] else: raise common.InvalidResponse( response, "X-Goog-Hash header had multiple ``{}`` values.".format(checksum_label), header_value,
matches, ) def _get_checksum_object(checksum_type): """Respond with a checksum object for a supported type, if not None. Raises ValueError if checksum_type is unsupported. """ if checksum_type == "md5": return hashlib.md5() elif checksum_type == "crc32c": return...
import uuid import logging import threading from sleekxmpp import Message, Iq from sleekxmpp.exceptions import XMPPError from sleekxmpp.xmlstream.handler import Callback from sleekxmpp.xmlstream.matcher import StanzaPath from sleekxmpp.xmlstream import register_stanza_plugin from sleekxmpp.plugins import BasePlugin fr...
return True return False def open_stream(self, jid, block_size=4096, sid=None, window=1, ifrom=None, block=True, timeout=None, callback=None): if sid is None: sid = str(uuid.uuid4()) iq = self.xmpp.Iq() iq['type'] = 'set'
iq['to'] = jid iq['from'] = ifrom iq['ibb_open']['block_size'] = block_size iq['ibb_open']['sid'] = sid iq['ibb_open']['stanza'] = 'iq' stream = IBBytestream(self.xmpp, sid, block_size, iq['to'], iq['from'], window) with self._stream_loc...
# -*- coding: utf-8 -*- """ End-to-end tests for the main LMS Dashboard (aka, Student Dashboard). """ import six from common.test.acceptance.fixtures.course import CourseFixture, XBlockFixtureDesc from common.test.acceptance.pages.common.auto_auth import AutoAuthPage from common.test.acceptance.pages.lms.dashboard im...
elf): """ Test the accessibility of the course listings """ self.dashboard_page.a11y_audit.config.set_rules({
"ignore": [ 'aria-valid-attr', # TODO: LEARNER-6611 & LEARNER-6865 'button-name', # TODO: AC-935 'landmark-no-duplicate-banner', # TODO: AC-934 'landmark-complementary-is-top-level', # TODO: AC-939 'region' # TODO: AC-932 ...
oncepts[concept_name].get_spawned_by() def add_spawned_by(self, concept_name, spawned_by): if concept_name in self.concepts: self.concepts[concept_name].add_spawned_by(spawned_by) def get_consumes(self, concept_name): if concept_name in self.concepts: return self.concep...
nfo("creating node: " + concept_name) concept = ConceptNode(concept_name) self.add_concept(concept_name, concept, type) #self.save_concept(name=new_concept_name)
#self.save_concept(name=newconcept_name) #add parent to child self.logger.info("adding parent: " + new_concept_name + " to child: " + concept_name) if type == "info": self.concepts[concept_name].add_parent(new_concept_name, gen=gen) elif type == "us...
from django.db import mo
dels from django.utils import timezone from pytz import common_timezones from .validators import YoutubeValidator class TimezoneField(models.CharField): """ A field for selecting a timezone from the common timezones list. """ def __init__(self,
*args, **kwargs): common_timezone_names = [tz.replace('_', ' ') for tz in common_timezones] the_kwargs = { 'choices': zip(common_timezones, common_timezone_names), 'default': timezone.get_default_timezone_name(), 'max_length': 50, } the_kwargs.update(k...
from functools
import partial from .primitives import EMPTY __all__ = ['identity', 'constantly', 'caller', 'partial', 'rpartial', 'func_partial', 'curry', 'rcurry', 'autocurry', 'iffy'] def identity(x): return x def
constantly(x): return lambda *a, **kw: x # an operator.methodcaller() brother def caller(*a, **kw): return lambda f: f(*a, **kw) # not using functools.partial to get real function def func_partial(func, *args, **kwargs): """ A functools.partial alternative, which returns a real function. Can be us...
gnals import class_prepared from django.utils import six from mezzanine.utils.importing import import_dotted_path # Backward compatibility with Django 1.5's "get_user_model". if VERSION >= (1, 5): from django.contrib.auth import get_user_model else: def get_user_model(): from django.contrib.auth.mode...
*more_models) # If the model is already loaded, pass it to the function immediately. # Otherwise, delay execution until the class is p
repared. try: model_class = get_registered_model(*model_key) except LookupError: self.pending_operations.setdefault(model_key, []).append(function) else:
static/visualization.swf?configFile=/static/visualization.xml query_params = parse_qsl(query_string) updated_query_params = [] for query_name, query_val in query_params: if query_val.startswith("/static/"): new_val = StaticContent.get_canonicalized_asset_path( ...
mimetype string of the asset md5: An md5 hash of the asset content ''' raise NotImplementedError def delete_all_course_assets(self, course_key): """ Delet
e all of the assets which use this course_key as an identifier :param course_key: """ raise NotImplementedError def copy_all_course_assets(self, source_course_key, dest_course_key): """ Copy all the course assets from source_course_key to dest_course_key """ ...
ng library from file: {rf}") raise else: if not self.library: self.library = rflib else: self.library = self.library + rflib def get_nuclei(self): """ get all the nuclei that are part of the network """ ...
= "\n" return ostr def get_screening_map(self): """a screening map is just a list of tuples containing the information about nuclei pairs for screening: (descriptive name of nuclei, nucleus 1, nucleus 2, rate, 1-based index of rate) """ screening_map = [] fo...
= "_".join([str(q) for q in r.ion_screen]) in_map = False for h, _, _, mrates, krates in screening_map: if h == nucs: # if we already have the reactants, then we # will already be doing the screening factors, ...
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Parallel workflow execution via IPython controller """ from __future__ import print_function, division, unicode_literals, absolute_import from future import standard_library stan...
lled"), e) else: raise e return super(IPythonPlugin, self).run(graph, config, updatehash=updatehash) def _get_result(self, taskid): if taskid not in self.taskmap: raise ValueError('Task %d not in pending list' % taskid) if self.taskmap[taskid].ready()...
skid].get() result_out = dict(result=None, traceback=None) result_out['result'] = result result_out['traceback'] = traceback result_out['hostname'] = hostname return result_out else: return None def _submit_job(self, node, updatehash=F...
# Copyright 2013-2020 Akretion France (https://akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGP
L-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Fiscal Position VAT Check", "version": "14.0.1.0.0", "category": "Invoices & Payments", "license": "AGPL-3", "summary": "Check VAT on invoice validation", "author": "Akretion,Odoo Community Association (OCA)", "website": ...
", "base_vat"], "data": [ "views/account_fiscal_position.xml", ], "installable": True, }
# -*- coding: utf-8 -*- # RTCP Datagram Module from struct import unpack, pack debug = 0 # Receiver Reports included in Sender Report class Report: SSRC = 0 FractionLost = 0 CumulativeNumberOfPacketsLostH = 0 CumulativeNumberOfPacketsLostL = 0 ExtendedHighestSequenceNumberReceived = 0 Interarr...
self.Reports[i].FractionLost, self.Reports[i].CumulativeNumberOfPacketsLostH, self.Reports[i].CumulativeNumberOfPacketsLostL, self.Reports[i].ExtendedHighestSequenceNumberReceived, self.Reports[i].InterarrivalJitter, self.Reports[i...
orts[i].DelaySinceLastSR = unpack('!IBBHIIII', self.Datagram[off: off + 24]) off += 24 # Source Description (SDES) elif PacketType == 202: # RC now is SC SSRCCount = Ver_P_RC & 0b00011111 self.SourceDescriptions = [] i = 0 for i...
#!/usr/bin/python # # Copyright 2016 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 b...
governing permissions and # limitations under the License. """Up
dates the specified datafeed on the specified account.""" from __future__ import print_function import argparse import sys from shopping.content import common # Declare command-line flags. argparser = argparse.ArgumentParser(add_help=False) argparser.add_argument('datafeed_id', help='The ID of the datafeed to update...
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.glm import H2OGeneralizedLinearEstimator as glm # Given alpha array and lambda_search=True, build two cross-validation models, one with validation dataset # and one without for multinomial. Since they use the metri...
s"][l])) pyunit_utils.assertEqualCoeffDicts(cv_r['coefficients'][l], cv_r_valid['coefficients'][l], tol=1e-6) pyunit_utils.assertEqualCoeffDicts(cv_r['coefficients_std'][l], cv_r_valid[
'coefficients_std'][l], tol=1e-6) if __name__ == "__main__": pyunit_utils.standalone_test(glm_alpha_array_with_lambda_search_cv) else: glm_alpha_array_with_lambda_search_cv()
lf): return '%d-Return(%s)' % (self.num, self.name) class ThrowBlock(BasicBlock): def __init__(self, name, block_ins): super(ThrowBlock, self).__init__(name, block_ins) self.type.is_throw = True def visit(self, visitor): return visitor.visit_throw_node(self) def __str__(s...
visitor.visit_switch_node(self) def copy_from(self, node): s
uper(SwitchBlock, self).copy_from(node) self.cases = node.cases[:] self.switch = node.switch[:] def update_attribute_with(self, n_map): super(SwitchBlock, self).update_attribute_with(n_map) self.cases = [n_map.get(n, n) for n in self.cases] for node1, node2 in n_map.iteritem...
default_a
pp_config = 'providers.com.da
ilyssrn.apps.AppConfig'
""" ============================================= Effect of varying threshold for self-training ============================================= This example illustrates the effect of a varying threshold on self-training. The `breast_cancer` dataset is loaded, and labels are deleted such that only 50 out of 569 samples h...
his dataset, with varying thresholds. The upper graph shows the amount of labeled samples that the classifier has available by the end of fit, and the accuracy of the classifier. The lower graph shows the last iteration in which a sample was labeled. All values are cross validated with 3 folds. At low thresholds (in ...
es are likely have incorrect predicted labels, and as a result, fitting on these incorrect labels produces a poor accuracy. Note that the classifier labels almost all of the samples, and only takes one iteration. For very high thresholds (in [0.9, 1)) we observe that the classifier does not augment its dataset (the am...
from flask import url_for from flask_sqlalchemy import BaseQuery def test_create_
av_scan(client, monkeypatch, malware_sample): monkeypatch.setattr(BaseQuery, 'first_or_404', lambda x: True) rv = client.post(url_for('api.add_av_scan'), json={'files': [malware_sa
mple._asdict()]}) assert rv.status_code == 202
from math import isnan from nose.tools import eq_ from js_helper import _do_real_test_raw, _do_test_raw, _do_test_scope, _get_var def test_assignment_with_pollution(): """ Access a bunch of identifiers, but do not write to them. Accessing undefined globals should not create scoped objects. """ a...
var y = 2; var z = x + y; var dbz = 1; var dbz1 = 1; dbz = dbz / 0; dbz1 = dbz1 % 0; var dbz2 = 1; var dbz3 = 1; dbz2 /= 0; dbz3 %= 0; var a = 2 + 3; var b = a - 1; var c = b * 2; """) assert err.message_count == 0 assert _get_var(err, 'x') == 1 assert...
nan(_get_var(err, 'dbz1')) # ...and this. assert _get_var(err, 'dbz2') == float('inf') assert isnan(_get_var(err, 'dbz3')) assert _get_var(err, 'a') == 5 assert _get_var(err, 'b') == 4 assert _get_var(err, 'c') == 8 def test_in_operator(): "Tests the 'in' operator." err = _do_test_raw("...
= config_client.list_discovered_resources( resourceType="AWS::S3::AccountPublicAccessBlock", resourceIds=[ACCOUNT_ID, "nope"], ) assert result["resourceIdentifiers"] == [ { "resourceType": "AWS::S3::AccountPublicAccessBlock", "resource...
PublicAccessBlock", resourceId=ACCOUNT_ID ) assert ( json.loads(result["configurationItems"][0]["configuration"]) == proper_config ) assert ( result["configurationItems"][0]["accountId"] == result["configurationItems"][0]["resourceId"] ...
{ "resourceType": "AWS::S3::AccountPublicAccessBlock", "resourceId": ACCOUN
this is the next state def mute_all_test(self): self.collection.remove() for i in range(0, 10): self.collection.insert({"name" : "test", "mute": False ,"account_id": self.account_id}) result = self.model.mute_all(account_id=self.account_id) for r in self.collection.f...
_id, 'trigger': True, 'server': server['_id'], 'time': i }]}, server_id=server_id) trigger_result = self.history_collection.find({'alert_id': rule['_id'] , 'notify': True}) eq_(trigger_result.count(), 3) for r in t...
ve() self.server_collection.remove() def delete_server_alerts_test(self): server_model.collection.remove() self.collection.remove() server_id = server_model.add('testserver') self.collection.insert({"rule_type" : "process",}) self.collection.insert({"rule_type" : ...
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class IntegerUsernameUserManager(BaseUserManager): def create_user(self, username, password): user = self.model(username=username) user.
set_password(password) user.save(using=self._db) return user def get_by_natural_key(self, username): return self.get(username=username) class IntegerUsernameUser(AbstractBaseUser): username = mo
dels.IntegerField() password = models.CharField(max_length=255) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username', 'password'] objects = IntegerUsernameUserManager()
import sys import ray import pytest from ray.test_utils import ( generate_system_config_map, wait_for_condition, wait_for_pid_to_exit, ) @ray.remote class Increase: def method(self, x): return x + 2 @ray.remote def increase(x): return x + 1 @pytest.mark.parametrize( "ray_start_reg...
s_server_restart(ray_start_cluster_head): """Checks that the node failure detector is correct when gcs server restart. We set the cluster to timeout nodes after 2 seconds of heartbeats. We then kill gcs server and remove the worker node and restart gcs server again to check that the removed node will d...
""" cluster = ray_start_cluster_head worker = cluster.add_node() cluster.wait_for_nodes() # Make sure both head and worker node are alive. nodes = ray.nodes() assert len(nodes) == 2 assert nodes[0]["alive"] and nodes[1]["alive"] to_be_removed_node = None for node in nodes: ...
# -*- coding: utf-8 -*- # Copyright (C) Canux CHENG <canuxcheng@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to ...
F OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """Base class for all Sharepoint 2013 plugins.""" import logging import traceback from monitoring.nagios.plugin import NagiosPluginHTTP from powershell i
mport XMLTable, XMLSerializedTable from powershell.xml.exceptions import XMLValidityError logger = logging.getLogger('plugin.base') class PluginBase(NagiosPluginHTTP): """Base class for all Exchange plugins.""" def __init__(self, *args, **kwargs): super(PluginBase, self).__init__(*args, **kwargs) ...
# coding: utf-8 from __future__ import absolute_import from swagger_server.
models.error_model import ErrorModel from swagger_serv
er.models.taxonomy import Taxonomy from . import BaseTestCase from six import BytesIO from flask import json class TestTaxonomyController(BaseTestCase): """ TaxonomyController integration test stubs """ def test_tax(self): """ Test case for tax Taxonomic information, or hierarchy ...
rrentDate or dt[ 'Link' ] not in gDTLinkList[ 'Value' ]: result = self.rmClient.deleteDowntimeCache ( downtimeID = dt[ 'DowntimeID' ] ) resQuery.append(result) return S_OK( resQuery ) def _prepareCommand( self ): '...
ntName, unless it is given a list, in which case it contacts the gocdb client. The server is not very stable, so in case of failure tries a second time. If there are downtimes, are recorded and then returned. ''' if masterParams is not None: element, elementNames = masterParams h...
return params element, elementName, hours, gocdbServiceType = params[ 'Value' ] elementNames = [ elementName ] #WARNING: checking all the DT that are ongoing or starting in given <hours> from now try: results = self.gClient.getStatus( element, name = elementNames, startingInHours = hours )...
from datetime import date, datetime from unittest import TestCase from myob.constants import DEFAULT_PAGE_SIZE from myob.credentials impo
rt PartnerCredentials from myob.manage
rs import Manager class QueryParamTests(TestCase): def setUp(self): cred = PartnerCredentials( consumer_key='KeyToTheKingdom', consumer_secret='TellNoOne', callback_uri='CallOnlyWhenCalledTo', ) self.manager = Manager('', credentials=cred) def asser...
import os import json import numpy as np from sklearn.externals import joblib from scripts.features.post import Post from scripts.features.post_feature import PostFeature import scripts.features.length_extractor as lext import scripts.features.charactor_extractor as cext import scripts.features.structure_extractor as s...
= [] def load(self): self.classifier = joblib.load(self.model_path + "banana.pkl") self.scaler = joblib.load(self.model_path + "banana_scaler.pkl") with open(self.model_path + "banana_list.txt") as f: self.features = f.readline().split() return self def evaluate...
lassifier.predict_proba(f_vector) return prediction[0][1] # probability of good def get_features(self, post_dict): post = Post(post_dict) pf = PostFeature(post) cleaned_rendered_body = cext.RenderedBodyPreprocessor().clean_rendered_body(post.rendered_body) pf.add(l...
# -*- coding: utf-8 -*- ############################################################################## # # Odoo Addon, Open Source Management Solution # Copyright (C) 2014-now Equitania Software GmbH(<http://www.equitania.de>). # # This program is free software: you can redistribute it and/or modify # it un...
Workaround für HTML-Texte: Autom. Inhalt nach Speichern ohne Inhalt: <p><br></p> Entfernen der Zeilenumbrüche und Paragraphen für Test, ob ein Inhalt gesetzt wurde :param value: :return: """ if not value: return False value = value.replace('<br>', '') ...
') value = value.replace('<', '') value = value.replace('>', '') value = value.replace('/', '') value = value.strip() return value != ''
d_urls(test_set['data_files']): data = ulmo.usgs.eddn.get_data(test_set['dcp_address'], start=test_set['start']) assert data['message_timestamp_utc'][-1] == test_set['first_row_message_timestamp_utc'] assert data['message_timestamp_utc'][0] == test_set['last_row_message_timestamp_utc...
0:00', pd.np.nan, 199.96], ['2013-10-30 09:00:00', pd.np.nan, 199.92], ['2013-10-30 10:00:00', pd.np.nan, 199.88], ['2013-10-30 1
1:00:00', pd.np.nan, pd.np.nan], ['2013-10-30 12:00:00', pd.np.nan, pd.np.nan], ['2013-10-30 13:00:00', pd.np.nan, pd.np.nan], ['2013-10-30 14
#!/usr/bin/env python # Fan control mod for Raspberry Pi import RPi.GPIO as GPIO, time, datetime, subprocess, os, logging from daemon import runner DEBUG = 1 GPIO.setmode(GPIO.BCM) # Respective ports on the GPIO header FAST = 18 SLOW = 25 # Default settings for fan control MAX_TEMP = 50 MIN_TEMP = 40 POLL_TIME =...
POLL_TIME = 15 time.sleep(POLL_TIME) except: logger.error('Exiting now!') finally: GPIO.cleanup() app = App() logger = logging.getLogger("DaemonLog") logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelna
me)s - %(message)s") handler = logging.FileHandler("/var/log/fandaemon/fandaemon.log") handler.setFormatter(formatter) logger.addHandler(handler) daemon_runner = runner.DaemonRunner(app) #This ensures that the logger file handle does not get closed during daemonization daemon_runner.daemon_context.files_preserve=[hand...
# Copyright 2015 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...
of data) as judged by cifar10_eval.py. Speed: With batch_size 128. System | Step Time (sec/batch) | Accuracy ------------------------------------------------------------------ 1 Tesla K20m | 0.35-0.60 | ~86% at 60K steps (5 hours) 1 Tesla K40m | 0.25-0.
35 | ~86% at 100K steps (4 hours) Usage: Please see the tutorial and website for how to download the CIFAR-10 data set, compile the program and train the model. http://tensorflow.org/tutorials/deep_cnn/ """ from __future__ import absolute_import from __future__ import division from __future__ import prin...
from tests.compiler import compile_snippet, A_ID, LST_ID, SELF_ID, VAL1_ID, internal_call, A_INST, INNER_ID, \ CONTAINER_INNER_ID, STATIC_START from thinglang.compiler.opcodes import OpcodePushLocal, OpcodePushMember, OpcodePushStatic, OpcodePop, \ OpcodeDereference, OpcodeCallVirtual def test_direct_member_a...
] def test_member_access_via_method_call(): assert compile_snippet('a_inst.me().a1') == [ OpcodePushLocal(A_INST), OpcodeCallVirtual(1), OpcodeDereference(0) ] assert compile_snippet('a_inst.me().me().a1'
) == [ OpcodePushLocal(A_INST), OpcodeCallVirtual(1), OpcodeCallVirtual(1), OpcodeDereference(0) ] def test_local_list_immediate_index(): assert compile_snippet('lst[123]') == [ OpcodePushStatic(STATIC_START), OpcodePushLocal(LST_ID), internal_call('list...
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.0.1' class Extension(ext.Extension)
: dist_name = 'Mopidy-USBPlaylist' ext_name = 'usbplaylist' version = __version__ def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(Extension, self).get_config_schema() schema['path'] = config.String() return schema def setup(self, registry): from .actor impo...
import pytest import logging @pytest.mark.asyncio async def test_confirmation(rpc_context): # setup rpc async de
f test_method(request): a = await request.confirm('just say yes!', timeout=1) logging.debug('a = %s', a) return a rpc_context.rpc.add_methods(('', test_method)) # setup client async def confirm(request): return True client = await rpc_context.make_client() client...
test_method')
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('productos', '0003_auto_20141118_2241'), ] operations
= [ migrations.AlterField( model_name='imagenes', name='url', field=models.ImageField(upload_to=b'img', null=True, verbose_name
=b'Im\xc3\xa1gen', blank=True), preserve_default=True, ), ]
# -*- coding: utf-8 -*- # Define your item pipelines he
re # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class CabukcgcrawlerPipeline(object): def process_item(self, item, spider):
return item
""" This file holds utility functions that have no dependencies on other console code. Avoids import loops """ import webcolors def wc(clr, factor=0.0, layercolor=(255, 255, 255)): lc = webcolors.name_to_rgb(layercolor.lower()) if isinstance(layercolor, str) else layercolor if isinstance(clr, str): try: v = we...
def get_field(self, field_name, ar
gs, kwargs): # Handle a key not found try: val = super().get_field(field_name, args, kwargs) except (KeyError, AttributeError): val = None, field_name return val def format_field(self, value, spec): # handle an invalid format if value is None: return self.missing try: return super().format_fiel...
# -*- coding: utf-8 -*- """ /*************************************************************************** IOGeopaparazzi A QGIS plugin A plugin to import/export geodata from/to geopaparazzi Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ ------------------- begin :...
QgsProcessingProvider from .import_gpap_algorithm import ImportGpapAlgorithm from .export_spatialite_al
gorithm import ExportSpatialiteAlgorithm from .export_tiles_algorithm import ExportTilesAlgorithm class IOGeopaparazziProvider(QgsProcessingProvider): def __init__(self): QgsProcessingProvider.__init__(self) # Load algorithms #self.alglist = [ImportGpapAlgorithm(),ExportSpatialiteAlgorithm(),ExportTilesAlgo...
import csv import sys from models import * from datetime import datetime import codecs import json # from models import Attorney, Organization from flask_mail import Message def load_attorneys_from_csv(filename): with codecs.open(filename, mode='rb', encoding='utf-8') as csvfile: attorneys = [row for row ...
if len(a.records) <= 1: a.records.append({ 'year': attorney[5], 'honor_choice': attorney[6], 'rule_49_choice': attorney[7], 'date_modified': datetime.now
(), 'method_added': u'bulk' }) a.save() print(attorney[3] + " is loaded.") except: print( "Unexpected error:", sys.exc_info()[0]) raise return True def check_new_email(email_address): try: Attor...
import pycurl import cStringIO import random import HTMLParser def generate_TAXII_header(xml, ssl=True): headers = { "Content-Type": "application/xml", "Content-Length": str(len(xml)), "User-Agent": "TAXII Client Application", "Accept": "application/xml", "X-TAXII-Accept": "urn:taxii...
art = """<?xml version="1.0" encoding="UTF-8" ?>""" boilerplate = """xm
lns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:taxii_11="http://taxii.mitre.org/messages/taxii_xml_binding-1.1" xsi:schemaLocation="http://taxii.mitre.org/messages/taxii_xml_binding-1.1 http://taxii.mitre.org/messages/taxii_xml_binding-1.1" """ message_id = str(random.randint(345271,9999999999)) xm...
# coding=utf-8 """ Write the collected stats to a locally stored log file. Rotate the log file every night and remove after 7 days. """ from Handler import Handler import logging import logging.handlers class ArchiveHandler(Handler): """ Implements the Handler abstract class, archiving data to a log file ...
Create a new instance of the ArchiveHandler class """ # Initialize Handler Handler.__init__(se
lf, config) # Create Archive Logger self.archive = logging.getLogger('archive') self.archive.setLevel(logging.DEBUG) self.archive.propagate = self.config['propagate'] # Create Archive Log Formatter formatter = logging.Formatter('%(message)s') # Create Archive Log...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 绘制简单的
折线图 import matplotlib.pyplot as plt input_values = list(range(1, 6)) squares = [x * x for x in input_values] # 根据传递的参数来绘制出有意义的图形 plt.plot(input_values, squares, linewidth=3) # 设置图表的标题及标题的字体大小 plt.title("Square Numbe
rs", fontsize=14) # 给坐标轴加上标签 plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) # 设置刻度标记的大小 plt.tick_params(axis='both', labelsize=14) # 打开查看器,并显示绘制的图形 plt.show()
from pytest_bdd import scenario from .contact_steps import * @scenario("con
tacts.feature", "Add new contact") def test_add_new_contact(): pass @scenario("contacts.feature", "Delete a contact") def test_delete_contact(): pass @scenario("contacts.featur
e", "Modify a contact") def test_modify_contact(): pass
from webfs import WebFSStat import stat def Test_Basic(): fields = ('st_mode', 'st_ino', 'st_dev', 'st_nlink', 'st_uid', 'st_gid', 'st_size', 'st_atime', 'st_mtime', 'st_ctime') st = WebFSStat() print st.__dict__.keys() for field in fields: assert field in st.__dict__.keys(), 'fi...
st = WebFSStat() assert st.st_mode == stat.S_IFDIR | 0555 st = WebFSStat(False) assert st.st_mode == stat.S_IFREG | 0444 def Test_IsDir(): st = WebFSStat() assert st.isDir() st = Web
FSStat(False) assert not st.isDir()
ter from chaco.api import Plot, LabelAxis from chaco.tools.api import ZoomTool, PanTool from chaco.ticks import ShowAllTickGenerator from enable.component_editor import ComponentEditor from pikos.live.ui.base_view import BaseView from pikos.live.ui.barplot import SelectableBarPlot, BarSelectTool class TableItem(HasT...
t.index_axis = label_axis self.plot.underlays.append(label_axis) def _sort_values_button_fired(self): self.model.sort_by_curren
t_value() self.plot.invalidate_and_redraw() def _metadata_changed(self, new): self.plot.invalidate_and_redraw() # data_indices = self.scatter.index.metadata.get('selections', []) # if len(data_indices) == 0: # self.model.selected_index = None # return ...
from django.conf.urls import patterns, include, url from django.shortcuts import redirect, render_to_response from django.template.context import RequestContext # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # Just redirect / to /blog for now until I can # co...
#url(r'^$', include('StackSmash.apps.blog.urls')), url(r'^license/', sslicense, name='license'), #url(r'^docs/', include('StackSmash.apps.docs.urls'), name='docs', app_name='docs'), url(r'^blog/', include('StackSmash.apps.blog.urls', namespace='blog')), url(r'^projects/', include('StackSmash.apps.pro...
s.urls', namespace='projects')), url(r'^upload/', include('StackSmash.apps.uploader.urls', namespace='upload')), url(r'^$', to_blog, name='index'), #url(r'^projects/', include('StackSmash.apps.projects.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)...
# -*- coding: utf-8 -*- """ *************************************************************************** BarPlot.py --------------------- Date : January 2013 Copyright : (C) 2013 by Victor Olaya Email : volayaf at gmail dot com ******************************...
ctFromUri( self.getParameterValue(self.INPUT)) namefieldname = self.getParameterValue(self.NAME_FIELD) valuefieldname = self.getParameterValue(self.VALUE_FIELD) output = self.getOutputValue(self.OUTPUT) values = vector.values(layer, namefieldname, valuefieldname) pl...
.8 plt.bar(ind, values[valuefieldname], width, color='r') plt.xticks(ind, values[namefieldname], rotation=45) plotFilename = output + '.png' lab.savefig(plotFilename) with open(output, 'w') as f: f.write('<html><img src="' + plotFilename + '"/></html>')
# -*- coding:utf-8 -*- from Crypto.Cipher import AES from Crypto.Hash import MD5 import binascii import urllib2 import string, random # algorithm MODE = AES.MODE_CBC def __getKeyObject(key): obj = AES.new(md5Encoding(key), MODE) return obj def md5Encoding(msg): ''' get md5 encrypted text @param ...
onList=['number', 'lower', 'upper', 'punc']): charPool = {'number' : string.digits, 'lower' : string.lowercase, 'upper' : string.uppercase, 'punc' : string.punctuation } pool = '' for key in optionList: if charPool.has_key(key): pool = ...
password @param key: the master password @param msg: the plain text to be encrypted ''' obj = __getKeyObject(key) # encrypt xx = msg*16 cipher = obj.encrypt(xx) # convert bin to string s = binascii.b2a_hex(cipher) return s def decrypt(key, msg): ''' Encryp...
#!/usr/bin/env pytho
n quit() for iii in range(0,6): try: print(iii,iii/(4-iii)) except ZeroDivisionError as e: #print("wrong: i={} {}".format(iii,e.message)) print("wrong: i={} {}".format(iii,"nooooooo")) #else: # print("OK") finally: print("continue...") def pickkey(mylist): ...
stjg) quit() x=3 #def myfL(a,b): # return [] def myf (a,b,*other): print(type(other)) print(sum(other)) c=sum(other) #return (a+b+other) #res=myf(5,2,1) ;print(res) #res=myf(a=5,b=2,c=1) ;print(res) #res=myf(b=2,a=5,c=1) ;print(res) #res=myf(a=5) ;print(res) #no res=myf(a=5,b=2,c=1) ;print(res) #...
# Copyright 2012 OpenStack Foundation # # 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...
j.get('volumes', [])) if volumes: self._add_image_metadata(context, volumes) @wsgi.action
("os-set_image_metadata") def create(self, req, id, body): context = req.environ['cinder.context'] if authorize(context): try: metadata = body['os-set_image_metadata']['metadata'] except (KeyError, TypeError): msg = _("Malformed request body.")...
''' Provide Jinja2 templates used by Bokeh to embed Bokeh models (e.g. plots, widgets, layouts) in various ways. .. bokeh-jinja:: bokeh.core.templates.AUTOLOAD_JS .. bokeh-jinja:: bokeh.core.templates.AUTOLOAD_NB_JS .. bokeh-jinja:: bokeh.core.templates.AUTOLOAD_TAG .. bokeh-jinja:: bokeh.core.templates.CSS_RESOURCES ...
te("autoload_nb_js.js") AUT
OLOAD_TAG = _env.get_template("autoload_tag.html")
ge from scipy.misc import doccer from scipy._lib._version import NumpyVersion __all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace', 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude', 'gaussian_gradient_magnitude...
ilter'] _input_doc = \ """input : array_like Input array to filter.""" _axis_doc = \ """axis : int, optional The axis of `input` along which to calculate. Default is -1.""" _output_doc = \ """output : array, optional The `output` parameter passes an array in whi
ch to store the filter output. Output array should have different name as compared to input array to avoid aliasing errors.""" _size_foot_doc = \ """size : scalar or tuple, optional See footprint, below footprint : array, optional Either `size` or `footprint` must be defined. `size` gives the shape...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pandas as pd import numpy as np from erlport.erlterms import Atom, List from erlport.erlang import set_encoder, set_decoder def setup_dtype(): set_encoder(dtype_encoder) set_decoder(dtype_decoder) return Atom(b'ok') def dtype_encoder(value): if isi...
return value def dtype_decoder(value): try: if isinstance(value, List): return [dtype_decoder(v) for v in value] elif isinstance(value, tuple): nvalue = () for v in value:
nvalue = nvalue + (dtype_decoder(v),) return nvalue elif isinstance(value, str): return value else: return value.decode("utf-8") except: return value
# Module to run tests on surveys # Most of these are *not* done with Travis yet # TEST_UNICODE_LI
TERALS import pytest import os import shutil import numpy as np from astropy.table import Table from frb.galaxies.frbgalaxy import FRBHost from frb.galaxies import eazy as frbeazy from frb.frb import FRB from distutils.spawn import find_executable eazy_exec = pytest.mark.skipif(find_executable('eazy') is None, ...
'files') return os.path.join(data_dir, filename) @pytest.fixture def host_obj(): # VLT photom = Table() photom['Name'] = ['G_TEST'] photom['ra'] = 123.422 photom['dec'] = 23.222 # These are observed photom['LRISb_V'] = 25.86 photom['LRISb_V_err'] = 0.25 photom['GMOS_S_r'] = 23....
#
-*- coding: utf-8 -*- __all__ = ["cc"]
# #Programa Lista 4, questão 1; #Felipe Henrique Bastos Costa - 1615310032; # # # # lista = []#lista vazia; cont1 = 0#contador do indice; cont2 = 1#contador da posição do numero, se é o primeiro, segundo etc; v = 5#representaria o len da lista; while(cont1 < v): x = int(input("Informe o %dº numero inteiro para c...
nt2))#x e a variavel que recebe
#o numero do usuario lista.append(x)#o numero informado para x e colocado dentro da lista; cont1+=1#Os contadores estao cont2+=1#sendo incrementados; print("A lista de informada foi:\n%s"%lista)
odically. A value of 0 turns the callback off. If the `value has to change`-parameter is set to true, the callback is only triggered after the value has changed. If the value didn't change within the period, the callback is triggered immediately on change. If it is set to false, the ca...
write_firmware_pointer(self, pointer): """ Sets the firmware pointer for :func:`Write Firmware`. The pointer has to be increased by
chunks of size 64. The data is written to flash every 4 chunks (which equals to one page of size 256). This function is used by Brick Viewer during flashing. It should not be necessary to call it in a normal user program. """ self.check_validity() pointer = int(pointer)...
from django import forms from .models import Post from django.contrib.auth import ( authenticate, get_user_model, login, logout, ) class PostForm(forms.ModelForm): # Post Thread View class Meta: model = Post fields = ['title','image', 'user','country','guide'] widgets = { 'guide' : forms.Textarea(attrs = ...
r.objects.filter(username=username) if use
rname_qs.exists(): raise forms.ValidationError("This username has already been registered!") return username
# -*- coding: utf-8 -*- import sys from warnings import warn from django.conf import settings from django.core.exceptions import ImproperlyConfigured if hasattr(settings, 'MODELTRANSLATION_TRANSLATION_REGISTRY'): TRANSLATION_REGISTRY =\ getattr(settings, 'MODELTRANSLATION_TRANSLATION_REGISTRY', None) elif ha...
TION_TRANSLATION_REGISTRY " "setting yet.") AVAILABLE_LANGUAGES = [l[0] for l in settings.LANGUAGES] DEFAULT_LANGUAGE = getattr(settings, 'MODELTRANSLATION_DEFAULT_LANGUAGE', None) if DEFAULT_LANGUAGE and DEFAULT_LANGUAGE not in AVAILABLE_LANGUAGES: raise ImproperlyConfigured('MODELT...
BLE_LANGUAGES[0] # FIXME: We can't seem to override this particular setting in tests.py CUSTOM_FIELDS =\ getattr(settings, 'MODELTRANSLATION_CUSTOM_FIELDS', ()) try: if sys.argv[1] == 'test': CUSTOM_FIELDS =\ getattr(settings, 'MODELTRANSLATION_CUSTOM_FIELDS', ('BooleanField',)) exc...
#!/usr/bin/python # -*- coding: utf-8 -*- # 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 progra...
m.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Inst
ruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W0 25 /r ib # vpternlogd zmm1{k1}{z}, zmm2, zmm3/m512/m32bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(...
var1 = bool(input()) var2 = bool(input()) if var1: print(var2) elif v<care
t>
# -*- coding: latin-1 -*- impo
rt re import json from .common import InfoExtractor from ..utils import determine_ext
class HarkIE(InfoExtractor): _VALID_URL = r'https?://www\.hark\.com/clips/(.+?)-.+' _TEST = { u'url': u'http://www.hark.com/clips/mmbzyhkgny-obama-beyond-the-afghan-theater-we-only-target-al-qaeda-on-may-23-2013', u'file': u'mmbzyhkgny.mp3', u'md5': u'6783a58491b47b92c7c1af5a77d4cbee', ...
#!/usr/bin/python # Copyright 2003 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE.txt or https://www.bfgroup.xyz/b2/LICENSE.txt) # Regression test: it was possible that due to evaluation of conditional # requirements, two different values of non-free featur...
if <the_featur
e>false in $(properties) && <the_feature>true in $(properties) { EXIT "Oops, two different values of non-free feature" ; } CMD on $(targets) = [ common.file-creation-command ] ; } actions maker { $(CMD) $(<) ; } make a : a.cpp : maker : <variant>debug:<the_feature>true ; """) t.run_bu...
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
f setup_class(cls): cls.app = web.app.test_client() model.rebuild_db() Fixtures.create() @classmethod def teardown_class(cls): mode
l.rebuild_db() def test_api_authenticate(self): """Test AUTHENTICATION works""" res = self.app.get('/?api_key=%s' % Fixtures.api_key) assert 'checkpoint::logged-in::tester' in res.data, res.data
the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language ...
uest( API_ROOT + '/cloud/server/reboot', data=json.dumps(params), method='POST').object return bool(result) def destroy_node(self, node): params = { 'mbpkgid': node.id, #'reason': 'Submitted through Libcloud API' } result...
nection.request( API_ROOT + '/cloud/cancel', data=json.dumps(params), method='POST').object return bool(result) def ex_get_node(self, node_id): """ Get a single node. :param node_id: id of the node that we need the node object for :type n...
#!/usr/bin/env python # imp general import IMP import IMP.core # our project from IMP.isd import Weight from IMP.isd import WeightMover # unit testing framework import IMP.test class TestWeightMover(IMP.test.TestCase): """tests weight setup""" def setUp(self): IMP.test.TestCase.setUp(self) ...
urn_best(False) self.mc.set_kt(1.0) self.mc.add_mover(self.wm) def test_run(self): "Test weight mover mc run" self.setUp() for n in range(5): for j in range(10):
self.mc.optimize(10) ws = self.w.get_weights() sum = 0 for k in range(self.w.get_number_of_states()): sum += self.w.get_weight(k) self.assertAlmostEqual(sum, 1.0, delta=0.0000001) self.w.add_weight() if __name__ == '__...
from django.contr
ib import admin # import your models # Register your m
odels here. # admin.site.register(YourModel)
# 2016-7-1 # build by qianqians # tools def gentypetocsharp(typestr): if typestr == 'int': return 'Int64' elif typestr == 'string': return 'String' elif typestr == 'array': return 'ArrayList' elif typestr == 'float': return 'Double' elif typestr == 'bool': re...
Boolean' elif typestr == 'table':
return 'Hashtable'
nd_dt if entries else None def find_next_start_dt(duration, obj, day=None, force=False): """Find the next most convenient start date fitting a duration within an object. :param duration: Duration to fit into the event/session-block. :param obj: The :class:`Event` or :class:`SessionBlock` the duration nee...
joinedload(Contribution.person_links)) .join(TimetableEntry)) if grouped: for c in query: start_da
te = c.timetable_entry.start_dt.astimezone(tz).date() result[c.event_id]['contribs'][start_date].append((c.timetable_entry, c)) else: for c in query: result[c.event_id]['contributions'].append(c) query = (Break.query .filter(TimetableEntry.ev...
#------------------------------------------------------------------------------ # Naam: libLog.py # Omschrijving: Generieke functies voor logging binnen BAG Extract+ # Auteur: Matthijs van der Deijl # Auteur: Just van den Broecke - porting naar NLExtract (2015) # # Versie: 1.3 # ...
Scherm: def __init__(self, text_ctrl): self.text_ctrl = text_ctrl def __call__(self, tekst): self.schrijf(tekst) def start(self): i = self.text_ctrl.GetNumberOfLines() self.text_ctrl.Clear() while i > 0:
self.text_ctrl.AppendText(" \n") i -= 1 self.text_ctrl.Clear() def schrijf(self, tekst): self.text_ctrl.AppendText("\n" + tekst) self.text_ctrl.Refresh() self.text_ctrl.Update() # See http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/ # (use eve...
#!/usr/bin/python # # Project Kimchi # # Copyright IBM, Corp. 2013 # # 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; either # version 2.1 of the License, or (at your option) any later ver...
ll be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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; if n
ot, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import errno import os import subprocess from kimchi.config import config, paths WS_TOKENS_DIR = '/var/lib/kimchi/vnc-tokens' def new_ws_proxy(): try: os.makedirs(WS_TOKENS_DIR, mode=0755) ...
import logging from datetime import date as _date, timedelta from typing import Dict, List from fahrplan.exception import FahrplanError from fahrplan.xml import XmlWriter, XmlSerializable from .conference import Conference from .day import Day from .event import Event from .room import Room log = logging.getLogger(...
.context("schedule"): xml.tag("version", self.version) xml.append_object(self.conference, extended) for day in self.days.values():
xml.append_object(day, extended)