prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from django.conf.urls import url from . import views app_name = 'repo' ur
lpatterns = [ url(r
'^$', views.home, name='home'), url(r'^home/$', views.home, name='home'), url(r'^library/$', views.library, name='library'), url(r'^login/$', views.login, name='login'), url(r'^register/$', views.register, name='register'), url(r'^results/?P<form>[A-Za-z]+/$', views.results, name='results'), url(r'^(?P<sn>[-\/\d\...
self.description = "Backup file relocation" lp1 = pmpkg("bash") lp1.files = ["etc/profile*"] lp1.backup = ["etc/profile"] self.addpkg2db("local", lp1) p1 = pmpkg("bash", "1.0-2") self.addpkg(p1) lp2 = pmpkg("filesystem
") self.addpkg2db("local", lp2) p2 = pmpkg("filesystem", "1.0-2") p2.files = ["etc/profile**"] p2.backup = ["etc/profile"] p
2.depends = [ "bash" ] self.addpkg(p2) self.args = "-U %s" % " ".join([p.filename() for p in (p1, p2)]) self.filesystem = ["etc/profile"] self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_VERSION=bash|1.0-2") self.addrule("PKG_VERSION=filesystem|1.0-2") self.addrule("!FILE_PACSAVE=etc/profile") self.addrule("FILE_P...
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import api, SUPERUSER_ID _logger = logging.getLogger(__name__) def post_init_hook(cr, registry): """ Create a payment group for every existint payment """ env = api.Environment(cr, SUPERUSER_ID, {}) # payments...
ayment'].search( [('partner_id', '!=', False)]) for payment in payments: _logger.info('creating payment group for payment %s' % payment.id) _state = payment.state in ['sent', 'reconciled'] and 'posted' or payment.state _state = _state if _state != 'cancelled' else 'cancel' ...
nt.partner_id.id, 'payment_date': payment.date, 'communication': payment.ref, 'payment_ids': [(4, payment.id, False)], 'state': _state, })
ty=stat.property).first() if fill_state is None: currently_filled = installation_epoch() fill_state = FillState.objects.create(property=stat.property, end_time=currently_filled, state=FillState.DONE) ...
Stat.HOUR: end
_time = ceiling_to_hour(event_time) row, created = table.objects.get_or_create( property=stat.property, subgroup=subgroup, end_time=end_time, defaults={'value': increment}, **id_args) if not created: row.value = F('value') + increment row.save(update_fields=['value']) def do_dr...
s super_user = "bigboss" super_pw = hashlib.sha256("ultimatepw").hexdigest() admin_user = "antti.admin" admin_pw = hashlib.sha256("qwerty1234").hexdigest() basic_user = "testuser" basic_pw = hashlib.sha256("testuser").hexdigest() wrong_pw = "wrong-pw" test_course_template_1 = {...
pp.get(self.course_resource_url) self.assertEquals(rv.status_code,401) self.assertEquals(PROBLEMJSON,rv.mimetype) # Test Course/PUT rv = self.app.put(self.course_resource_url) self.assertEquals(rv.status_code,401) self.assertEquals(PROBLEMJSON,rv.mimetype) ...
SON,rv.mimetype) # Try to Course/POST when not admin or super user rv = self.app.post(self.courselist_resource_url, headers={'Authorization': 'Basic ' + \ base64.b64encode(self.basic_user + ":" + self.basic_pw)}) self.assertEq...
import time seen = set() import_order = [] elapsed_times = {} level = 0 parent = None children = {} def new_import(name, globals={}, locals={}, fromlist=[]): global level, parent if name in seen: return old_import(name, globals, locals, fromlist) seen.add(name) import_order.append((name, ...
_.__import__ __builtins__.__import__ = new_import from sympy import * parents = {} is_parent = {} for name, level, parent in import_order: parents[name] = parent is_parent[parent] = True print "== Tree ==" for name, level, parent in import_order: print "%s%s: %.3f (%s)" % (" "*level, name, elapsed_ti...
ren) ==" slowest = sorted((t, name) for (name, t) in elapsed_times.items())[-50:] for elapsed_time, name in slowest[::-1]: print "%.3f %s (%s)" % (elapsed_time, name, parents[name])
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
DummyOperator(BaseOpera
tor): """ Operator that does literally nothing. It can be used to group tasks in a DAG. """ ui_color = '#e8f7e4' @apply_defaults def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) def execute(self, context): pass
#!/usr/bin/pytho
n ''' Example of zmq client. Can be used to record test data on remote PC Nacho Mas January-2017 ''' import sys import zmq import time import json from config import * # Socket to talk to server context = zmq.Context() socket = context.socket(zmq.SUB) #socket.setsockopt(zmq.CONFLATE, 1) socket.connect ("tcp://...
topicfilter) # Process while True: topic, msg = demogrify(socket.recv()) print "%f" % msg['unixUTC'] #time.sleep(5)
port stat import sys from functools import partial from pathlib import Path from platform import system from shutil import rmtree, which from subprocess import CalledProcessError from sys import version_info from tempfile import TemporaryDirectory from typing import ( Any, Callable, Dict, List, Name...
= False, ) -> None: """Run Black and record failures""" if not repo_path: results.stats["failed"] += 1 results.failed_projects[project_name] = CalledProcessError( 69, [], f"{project_name} has no repo_path: {repo_path}".encode(), b"" ) return stdin_test = project_...
i_args(project_config["cli_arguments"])) cmd.append("--check") if not no_diff: cmd.append("--diff") # Workout if we should read in a python file or search from cwd stdin = None if stdin_test: cmd.append("-") stdin = repo_path.read_bytes() elif "base_path" in project_conf...
# Copyright 2016 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...
(2, 3,)]: for k in [1, 4]: operator, mat = self._build_operator_and_mat(batch_shape, k) # Work with 5 simultaneous sys
tems. 5 is arbitrary. x = self._rng.randn(*(batch_shape + (k, 5))) self._compare_results( expected=tf.matrix_solve(mat, x).eval(), actual=operator.solve(x)) def testSqrtSolve(self): # Square roots are not unique, but we should still have # S^{-T} S^{-1} x = A^{-1} x. #...
#!/F3/core/tweet_model.py # A class for representating a tweet. # Author : Ismail Sunni/@ismailsunni # Created : 2012-03-30 from db_control import db_conn from datetime import datetime, timedelta import preprocess as pp class tweet_model: '''A class for representating a tweet.''' def __init__(self, id...
r_time + delta_duration < end_time): retval.append(get_test_data(keyword, cur_time, cur_time + delta_duration)) dur_times.append(cur_time) cur_time += delta_duration if (cur_time < end_time): dur_times.append(cur_time) retval.append(get_test_data(keyword, cur_time, end_time)) return retval, du...
_name__ == '__main__': keyword = "foke" start_time = datetime.strptime("10-4-2012 18:00:00", '%d-%m-%Y %H:%M:%S') end_time = datetime.strptime("18-4-2012 12:00:00", '%d-%m-%Y %H:%M:%S') duration_hour = 6 retval, dur_times = get_test_data_by_duration(keyword, start_time, end_time, duration_hour) num_tw...
# -*- coding: utf-8 -*- from orator.orm import Factory, Model, belongs_to, has_many from orator.connections import SQLiteConnection from orator.connectors import SQLiteConnector from .. import OratorTestCase, mock class FactoryTestCase(OratorTestCase): @classmethod def setUpClass(cls): Model.set_con...
r.admin) users = self.factory(User, 3).create() self.assertEqual(3, len(users)) self.assertFalse(users[0].admin) admin = self.factory(User, "admin").create() self.assertTrue(admin.admin) admins = self.factory(User, "admin", 3).create() self.assertEqual(3, len(...
class User(Model): __guarded__ = ["id"] @has_many("user_id") def posts(self): return Post class Post(Model): __guarded__ = [] @belongs_to("user_id") def user(self): return User class DatabaseConnectionResolver(object): _connection = None def connection(self, ...
# 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 # distrib...
r express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import mock from oscdebug.tests import base from oscdebug.v1 import auth class TestAuthTypeShow(base.TestCommand): def setUp(self): super(TestAuthTypeShow, self).setUp() ...
verifylist = [ ('auth_type', 'password'), ] parsed_args = self.check_parser(self.cmd, arglist, verifylist) # DisplayCommandBase.take_action() returns two tuples columns, data = self.cmd.take_action(parsed_args) collist = ('name', 'options') self.assertEq...
from UM.Scene.SceneNodeDecorator import SceneNodeDecorator class GCo
deListDecorator(Scene
NodeDecorator): def __init__(self): super().__init__() self._gcode_list = [] def getGCodeList(self): return self._gcode_list def setGCodeList(self, list): self._gcode_list = list
from .ica
import * #
from .ica_gpu import ica_gpu
# Add project owner self.subproject.project.owners.add(self.second_user()) notify_merge_failure( self.subproject, 'Failed merge', 'Error\nstatus' ) # Check mail (second one is for admin) self.assertEqual(len(mail.outbox), 5) def test_noti...
rtEqual( mail.outbox[0].subject, '[Weblate] New translation in Test/Test - Czech' ) def test_notify_new_language(self): second_user = self.second_user() notify_new_language( self.subproject, Language.objects.filter(code='de'), seco...
self.assertEqual(len(mail.outbox), 2) self.assertEqual( mail.outbox[0].subject, '[Weblate] New language request in Test/Test' ) # Add project owner self.subproject.project.owners.add(second_user) notify_new_language( self.subproject, ...
5 s.axes_manager[0].scale = 0.01 poly = hs.model.components1D.Polynomial(order=2, legacy=True) poly.coefficients.value = [1, 2, 3] poly.coefficients.value = [1, 2, 3] poly.coefficients._bounds = ((None, None), (10, 0.0), (None, None)) poly_dict = poly.as_dictionary(True) ...
: self.m.signal.metadata.Signal.binned = binned s = self.m.as_signal(parallel=False) s.metadata.Signal.binned = binned p = hs.model.components1D.Polynomial(order=2, legacy=False) p.estimate_parameters(s, None, None, only_current=only_current) assert_allclose(p.a2.value, 0...
m = self.m_offset with pytest.raises(ValueError): m.append(hs.model.components1D.Polynomial(order=0, legacy=False)) def test_2d_signal(self): # This code should run smoothly, any exceptions should trigger failure s = self.m_2d.as_signal(parallel=False) model = Mode...
""" Models a GC-MS experiment represented by a list of signal peaks """ ############################################################################# # # # PyMS software for processing of metabolomic mass-spectrometry data # # Copy...
# # 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 hop...
from django.apps import AppConfig class Player
sConfig(AppConfig
): name = 'players'
#!/usr/bin/python # # Copyright Friday Film Club. All Rights Reserved. """League unit tests.""" __author__ = 'adamjmcgrath@gmail.com (Adam McGrath)' import unittest import base import helpers import models class LeagueTestCase(base.TestCase): def testPostPutHook(self): league_owner = helpers.user() le...
elpers.user() league = models.League(name='Foo', owner=league_owner.put(), users=[league_member_1.put(), league_member_2.put()]) league_key = league.put() self.asser
tListEqual(league_owner.leagues, [league_key]) self.assertListEqual(league_member_1.leagues, [league_key]) self.assertListEqual(league_member_2.leagues, [league_key]) league.users = [league_member_2.key] league.put() self.assertListEqual(league_member_1.leagues, []) self.assertListEqual(league_...
import ctypes import os import types from platform_utils import paths def load_library(libname): if path
s.is_frozen(): libfile = os.path.join(paths.embedded_data_path(), 'accessible_output2', 'lib', libname) else: libfile = os.path.join(paths.module_path(), 'lib', libname) return ctypes.windll[libfile] def get_output_classes(): import outputs module_type = types.ModuleType classes = [m.output_class for m in out...
afiles(): import os import platform from glob import glob import accessible_output2 if platform.system() != 'Windows': return [] path = os.path.join(accessible_output2.__path__[0], 'lib', '*.dll') results = glob(path) dest_dir = os.path.join('accessible_output2', 'lib') return [(dest_dir, results)]
""", (self.study_id, self.feature_id, self.uid) ) except Exception, e: context.logger.error('Location: %s (%s)', self.uid, e) class Study (canary.context.Cacheable, DTable): TABLE_NAME = 'studies' # FIXME: does th...
re (self, id): """ Return the matching exposure, if added. Note that get_exposure is for use in matching or deleting exposures, i.e., only after an exposure has been added to the Study, so uid matching is required. """ f
or exp in self.exposures: if exp.uid == id: return exp return None def get_exposure_from_exposure (self, exposure): for exp in self.exposures: if exp.concept_id == exposure.concept_id: return exp return None def has_risk_facto...
#!/usr/bin/env python #! -*- coding: utf-8 -*- ### # Copyright (c) Rice University 2012-13 # This software is subject to # the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. ### """ THis exists solely to provide less typing for a "leaf node" in a simple real...
inheriting from Base. Thus we have those objects perform multiple inheritence... """ import json import sqlalchemy.types import datetime class CNXBase(): def from_dict(self, userprofile_dict): """ SHould test for schema validity etc. """ d = userprofile_dict for k in d:...
"""Return self as a dict, suitable for jsonifying """ d = {} for col in self.__table__.columns: d[col.name] = self.safe_type_out(col) return d def jsonify(self): """Helper function that returns simple json repr """ selfd = self.to_dict() jsonstr = jso...
from d
jango.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='homepage.html')), url(r'^remote.html$', TemplateView.as_view(template_
name='remote.html'), name="remote.html"), ]
eed(1) tf.reset_default_graph() def testMetricsCollection(self): my_collection_name = '__metrics__' mean, _ = metrics.streaming_auc( predictions=tf.ones((10, 1)), labels=tf.ones((10, 1)), metrics_collections=[my_collection_name]) self.assertListEqual(tf.get_collection(my_colle...
predictions = tf.constant([1, 0, 1, 0], shape=(1, 4), dtype=tf.float32) labels = tf.constant([0, 1, 1, 0], shape=(1, 4))
weights = tf.constant([2], shape=(1, 1)) auc, update_op = metrics.streaming_auc(predictions, labels, weights=weights) sess.run(tf.local_variables_initializer()) self.assertAlmostEqual(0.5, sess.run(update_op), 5) self.assertAlmostEqual(0.5, auc.eval...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from openerp import api, fields, models class CrmActivity(models.Model): ''' CrmActivity is a model introduced in Odoo v9 that models activities performed in CRM, like phonecalls, sending emails, making demonst...
sequence = fields.Integer('Sequence', default=0) team_id = fields.Many2one('crm.team', string='Sales Team') subtype_id = fields.Many2one('mail.message.subtype', string='Message Subtype', required=True, ondelete='cascade') activity_1_id = fields.Many2one('crm.activity', string="Next Activity 1") activi
ty_2_id = fields.Many2one('crm.activity', string="Next Activity 2") activity_3_id = fields.Many2one('crm.activity', string="Next Activity 3") @api.model def create(self, values): ''' Override to set the res_model of inherited subtype to crm.lead. This cannot be achieved using a default on r...
# coding: utf-8 ''' Created on 2012-8-30 @author: shanfeng ''' import smtplib from email.mime.text import MIMEText import urllib import web class XWJemail: ''' classdocs ''' def __init__(self, params): ''' Constructor ''' pass @staticmethod def sendfindpass(user,hash): link = "%s/account/newpass?%s"...
tplib.SMTP() smtp.connect('smtp.163.com') smtp.login('wukong10086@163.com','831112') smtp.sendmail(mail_from,mail_to,msg.as_string()) smtp.quit() def sendMail(mailto,subject,body,format='plain'): if isinstance(body,unicode): body = str(body) me= ("%s<"+fromMail+">") % (Header(_mailFr...
msg['Subject'] = subject msg['From'] = me msg['To'] = mailto msg["Accept-Language"]="zh-CN" msg["Accept-Charset"]="ISO-8859-1,utf-8" try: s = smtplib.SMTP() s.connect(host) s.login(user,password) s.sendmail(me, mailto, msg.as_string()) s.close() ...
#!/usr/bin/python # This script reads through a enotype likelihood file and the respective mean genotype likelihood file. It writes a nexus file for all individuals and the given genotypesi, with '0' for ref homozygote, '1' for heterozygote, and '2' for alt homozygote. # Usage: ~/vcf2nex012.py pubRetStriUG_unlnkd.gl ...
# read genotype likelihood fil
e to get scaffold:bp (which is not in the same order as the vcf file, resulting from vcf2gl.py) with open(argv[1], 'rb') as gl_file: scafPos_gl = list() for line in gl_file: if line.split(' ')[0] == '65': continue elif line.split(' ')[0] == 'CR1043': ind_id = line.split('...
""" ListCompToMap transforms list comprehension into intrinsics. """ from pythran.analyses import OptimizableComprehension from pythran.passmanager import Transformation from pythran.transformations import NormalizeTuples import ast class ListCompToMap(Transformation): ''' Transforms list comprehension int...
None, None, []) mapName = ast.Attribute( value=ast.Name(id='__builtin__', ctx=ast.Load()), attr='map', ctx=ast.Load()) ldBodymap = node.elt ldmap = ast.Lambda(varAST, ldBodymap) return ast.Call(mapNa...
eturn self.generic_visit(node)
from recursive function calls.""" def __init__(self): Object.__init__(self) # XXX: Do cycles need an id? self.functions = set() def add_function(self, function): assert function not in self.functions self.functions.add(function) # XXX: Aggregate events? ...
using Tarjan's strongly connected components algorithm.""" # Apply the Tarjan's algorithm successively until all functions are visited visited
= set() for function in self.functions.itervalues(): if function not in visited: self._tarjan(function, 0, [], {}, {}, visited) cycles = [] for function in self.functions.itervalues(): if function.cycle is not None and function.cycle not in cycles: ...
from HSM_Reactions import * ########## RIGHT MEMBERS OF ODEs, rewritten with only 10 equations to isolate those that are independent ############## def f10eqs(t, y, ksetDict, TparamSet, REACparamSet, DirectControlnuPp, IC_PplusPp, IC_SplusSs): #P = y[0] Ph = y[0] #S = y[2] Ss = y[1] F = y[2] ...
# RF Added const to Alex model piRHP(FsG, kpiRH) + piRHPAddConst(piRHPconst) - etaRHP(RHP, ketaRHP), # RHP Aded const to Alex model piHP(RHP, kpiHP) - etaHP(HP, ketaHP)] # HP # Notice presence of nuFG() in line of F, presence of nuFsG() in th...
absence of pi in that of FsG. return system ########## RIGHT MEMBERS OF ODEs, rewritten with only 9 equations to isolate those that are independent ############## def f9eqs(t, y, ksetDict, TparamSet, REACparamSet, DirectControlnuPp, IC_PplusPp, IC_SplusSs, IC_GplusFsGplusFG): #P = y[0] Ph = y[0] #...
#!/usr/bin/env python3 ######################################################################### # File Name: mthreading.py # Author: ly # Created Time: Wed 05 Jul 2017 08:46:57 PM CST # Description: ###########
############################################################## # -*- coding: utf-8 -*- import time import threading def play(name,count): for i in range(1,count): print('%s %d in %d' %(name, i, count)) time.sleep(1) return if __name__=='__main__': t1=t
hreading.Thread(target=play, args=('t1',10)) # 设置为守护线程 t1.setDaemon(True) t1.start() print("main") # 等待子线程结束 t1.join() exit(1)
# coding=utf-8 """TV base class.""" from __future__ import unicode_literals import threading from builtins import object from medusa.indexers.config import INDEXER_TVDBV2 class Identifier(object): """Base identifier class.""" def __bool__(self): """Magic method.""" raise NotImplementedError...
r, indexerid, ignored_properties): """Initialize class. :param indexer: :type indexer: int :param indexerid: :type indexerid: int :param ignored_properties: :type ignored_properties: set(str) """ self.__dirty = True self.__ignored_properti...
{'lock'} self.indexer = int(indexer) self.indexerid = int(indexerid) self.lock = threading.Lock() @property def series_id(self): """To make a clear distinction between an indexer and the id for the series. You can now also use series_id.""" return self.indexerid def...
sky, swidth=source.apcor.swidth, apcor=source.apcor.apcor, zmag=source.zmag, maxcount=30000,...
rue), MaskedColumn(name="measure_mag1", length=0, mask=True), MaskedColumn(name="measure_merr1", length=0, mask=True), MaskedColumn(name="measure_mag2", length=0, mask=True), MaskedColumn(name="measure_merr2", length=0, mask=True), ...
olumns(new_columns) # We do some 'checks' on the Object.planted match to diagnose pipeline issues. Those checks are made using just # those planted sources we should have detected. bright = planted_objects_table['mag'] < bright_limit n_bright_planted = numpy.count_nonzero(planted_objects_table['mag'][...
= self.IOBinding(self) io.set_filename_change_hook(self.filename_change_hook) # Create the recent files submenu self.recent_files_menu = Menu(self.menubar) self.menudict['file'].insert_cascade(3, label='Recent Files', underline=0, ...
s.path.exists(filename) and not os.path.isdir(filename):
io.loadfile(filename) else: io.set_filename(filename) self.ResetColorizer() self.saved_change_hook() self.set_indentation_params(self.ispythonsource(filename)) self.load_extensions() menu = self.menudict.get('windows') if menu: ...
"""Implements a HD44780 character LCD connected via PCF8574 on I2C. This was tested with: https://www.wemos.cc/product/d1-mini.html""" from time import sleep_ms, ticks_ms from machine import I2C, Pin from esp8266_i2c_lcd import I2cLcd # The PCF8574 has a jumper selectable address: 0x20 - 0x27 DEFAULT_I2C_ADDR = 0x...
main(): """Test function for verifying basic functionality.""" print("Running test_main") i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000) lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16) lcd.putstr("It Works!\nSecond Line") sleep_m
s(3000) lcd.clear() count = 0 while True: lcd.move_to(0, 0) lcd.putstr("%7d" % (ticks_ms() // 1000)) sleep_ms(1000) count += 1 if count % 10 == 3: print("Turning backlight off") lcd.backlight_off() if count % 10 == 4: print(...
from jinja2 import Markup class momentjs(object): def __init__(self, timestamp): self.timestamp = timestamp def render(self, format): return Markup("<script>\ndocument.write(moment(\"%s\").%s);\n</s
cript>" % (self.timestamp.strftime("%Y-%m-%dT%H:%M:%S Z"), format)) def format(self, fmt): return self.render("format(\"%s\")" % fmt) def calendar(self): return self.render("calendar()") def fro
mNow(self): return self.render("fromNow()")
port sessions from plaso.engine import knowledge_base from plaso.formatters import manager as formatters_manager from plaso.formatters import mediator as formatters_mediator from plaso.parsers import interface from plaso.parsers import mediator from plaso.storage import fake_storage from tests import test_lib as share...
in iter(knowledge_base_values.items()): knowledge_base_object.SetValue(identifier, value) knowledge_base_object.SetTimezon
e(timezone) parser_mediator = mediator.ParserMediator( storage_writer, knowledge_base_object) if file_entry: parser_mediator.SetFileEntry(file_entry) if parser_chain: parser_mediator.parser_chain = parser_chain return parser_mediator def _CreateStorageWriter(self): """Crea...
from setuptools import setup, find_packages setup(name='MO
DEL1201230000', version=20140916, description='MODEL1201230000 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/MODEL1201230000', maintainer='Stanley Gu', maintainer_url='stanleygu@gmail.com', packages=find_packages(), package_data={
'': ['*.xml', 'README.md']}, )
bTopMarginF', 'lgAutoManage', 'lgBottomMarginF', 'lgBoxBackground', 'lgBoxLineColor', 'lgBoxLineDashPattern', 'lgBoxLineDashSegLenF', 'lgBoxLineThicknessF', 'lgBoxLinesOn', 'lgBoxMajorExtentF', 'lgBoxMinorExtentF', 'lgDashIndex', 'lgDashIndexes', 'lgItemCo...
'sfMissingValueV', 'sfXArray', 'sfXCActualEndF', 'sfXCActualStartF', 'sfXCEndIndex', 'sfXCEndSubsetV', 'sfXCEndV', 'sfXCStartIndex', 'sfXCStartSubsetV', 'sfXCStartV', 'sfXCStride', 'sfXCellBounds', 'sfYArray', 'sfYCActualEndF', 'sfYCActualStartF', 'sfYCEndIndex', ...
'sfYCStartV', 'sfYCStride', 'sfYCellBounds', 'stArrowLengthF', 'stArrowStride', 'stCrossoverCheckCount', 'stExplicitLabelBarLabelsOn', 'stLabelBarEndLabelsOn', 'stLabelFormat', 'stLengthCheckCount', 'stLevelColors', 'stLevelCount', 'stLevelPalette', 'st...
same name this help avoid confusion by being flexible). """ # pep-8 naming exception -- this is a decorator class def __init__(self, exc): self._exc = exc self._ctx = None def __call__(self, func): @functools.wraps(func) def run_raises_test(*args, **kwargs): ...
values). """ global _deprecations_as_exceptions _deprecations_as_exceptions = True global _include_astropy_deprecations _include_astropy_deprecations = include_astropy_deprecations global _modules_to_ignore_on_import _modules_to_ignore_on_import.update(modules_to_ignore_on_import)
global _warnings_to_ignore_entire_module _warnings_to_ignore_entire_module.update(warnings_to_ignore_entire_module) global _warnings_to_ignore_by_pyver for key, val in six.iteritems(warnings_to_ignore_by_pyver): if key in _warnings_to_ignore_by_pyver: _warnings_to_ignore_by_pyver[key]...
import sqlalchemy metadata = sqlalchemy.MetaData() log_table = sqlalchemy.Table('log', metadata,
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True), sqlalchemy.Column('filename', sqlalchemy.Unicode), sqlalchemy.Column('digest', sqlalchemy.Unicode), sqlalchemy.Column('comment', sqlalchemy.Unicode), ...
code)) def init(engine): metadata.create_all(bind=engine)
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-30 12:53 from __futu
re__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='user', name='added', ), migrations.RemoveField( ...
', ), ]
input = """ g(1). g(2). g(3). f(a,b). f(A,B):- g(A), g(B). f(a,a). """ o
utput = """ {f(1,1), f(1,2), f(1,3), f(2,1), f(2,2), f(2,3), f(3,1), f(3,2), f(3,3), f(a,a), f(a,b), g(1), g(2)
, g(3)} """
from velox_d
eploy import *
# (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ lookup: redis author: - Jan-P...
one: conn = redis.Redis(host=host, port=port) else: conn = redis.Redis(unix_socket_path=socket) ret = [] for term in
terms: try: res = conn.get(term) if res is None: res = "" ret.append(res) except Exception: ret.append("") # connection failed or key not found return ret
from __future__ import absolute_import ########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) #
# # # This file i
s part of AmCAT - The Amsterdam Content Analysis Toolkit # # # # AmCAT 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, e...
e.__name__, ] ) def test_urlconf_overridden_with_null(self): """ Overriding request.urlconf with None will fall back to the default URLconf. """ response = self.client.get('/test/me/') self.assertEqual(response.status_code, 200) self.assertEqual(re...
def setUp(self): urlconf = 'urlpatterns_reverse.urls_error_handlers' urlconf_callables = 'urlpatterns_reverse.urls_error_handlers_callables' self.resolver = RegexURLResolver(r'^$', urlconf) self.callable_resolver = RegexURLResolver(r'^$', urlconf_callables) def test_named_handlers(s...
f.resolver.resolve_error_handler(404), handler) self.assertEqual(self.resolver.resolve_error_handler(500), handler) def test_callable_handlers(self): handler = (empty_view, {}) self.assertEqual(self.callable_resolver.resolve_error_handler(400), handler) self.assertEqual(self.callabl...
from worldengine.simulations.basic import * import random from worldengine.views.basic import color_prop from PyQt4 import QtGui class WatermapView(object): def is_applicable(self, world): return world.has_watermap() def draw(self, world, canvas): width = world.width height = world.h...
: w = world.watermap['data'][y][x] if w > th: r = g = 0 b = 255 else
: r = g = b = 0 col = QtGui.QColor(r, g, b) canvas.setPixel(x, y, col.rgb())
"""NuGridPy p
ackage version""" __version__ = '0.7.6
'
#!/usr/bin/env python # -*- encoding: utf-8 -*- # -*- mode: python -*- # vi: set ft=python : import os from setuptools import setup, find_package
s README_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README') DESCRIPTION = 'Easy image thumbnails in Django.' if os.path.exists(README_PATH): LONG_DESCRIPTION = open(README_PATH).read() else
: LONG_DESCRIPTION = DESCRIPTION setup( name='django-thumbs', version='1.0.4', install_requires=['django'], description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Matt Pegler', author_email='matt@pegler.co', url='https://github.com/pegler/django-thumbs/', packages=['th...
# -*- coding: utf-8 -*- """ lets.transparentlet ~~~~~~~~~~~~~~~~~~~ Deprecated. gevent-1.1
keeps a traceback exactly. If you want to just prevent to print an exception by the hub, use :mod:`lets.quietlet` instead. :copyright: (c) 2013-2018 by Heungsub Lee :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from gevent.pool import Group as TransparentGroup ...
__ = ['Transparentlet', 'TransparentGroup', 'no_error_handling']
template = "Exception {0} in uve stream proc. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.error("%s : traceback %s" % \ (messag, traceback.format_exc())) lredis = None if pb is no...
%s" % self._topic) self._kfk = KafkaClient(self._brokers , "kc-" + self._topic) try: consumer = SimpleConsumer(self._kfk, self._group, self._topic, buffer_size = 4096*4, max_buffer_size=4096*32) #except: except Exception as ex: ...
template = "Consumer Failure {0} occured. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.info("%s" % messag) raise RuntimeError(messag) self._logger.error("Starting %s" % self._topic) ...
icense, or # (at your option) any later version. # # This woob module is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should ha...
ceptions import ActionNeeded from .constants import TYPES, RET import codecs import decimal class ErrorPage(HTMLPage): def on_load(self): raise ActionNeeded("Please resolve the captcha") class CitiesPage(JsonPage): @method class iter_cities(DictElement): ignore_duplicate = True ...
temElement): klass = City obj_id = Dict('Params/ci') obj_name = Dict('Display') class SearchResultsPage(HTMLPage): def __init__(self, *args, **kwargs): HTMLPage.__init__(self, *args, **kwargs) json_content = Regexp(CleanText('//script'), ...
# perf trace event handlers, generated by perf trace -g python # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # This script tests basic functionality such as flag and symbol # strings, common_xxx() calls back into perf, begin, end, unhandled # events, etc. Ba...
_comm) print_uncommon(context) print "call_site=%u, ptr=%u, bytes_req=%u, " \ "bytes_alloc=%u, gfp_flags=%s\n" % \ (call_site, ptr, bytes_req, bytes_alloc, flag_str("kmem__kmalloc", "gfp_flags", gfp_flags)), def trace_unhandled(event_name, context, event_fields_dict): try: unhand...
unhandled[event_name] = 1 def print_header(event_name, cpu, secs, nsecs, pid, comm): print "%-20s %5u %05u.%09u %8u %-20s " % \ (event_name, cpu, secs, nsecs, pid, comm), # print trace fields not included in handler args def print_uncommon(context): print "common_preempt_count=%d, common_flags=%s, common_...
# flake8: noqa import sys import toml import log from .uploader import DropboxUploader from .file_manager import DirectoryPoller, VolumePoller SECT = 'flysight-manager' class ConfigError(Exception): pass class FlysightConfig(object): pass class DropboxConfig(object): pass class VimeoConfig(object...
n") _cfg.from_addr = get("from") _cfg.to_addr = get("to") _cfg.subject = get("subject") return _cfg def load_pushover_opts(self, cfg): get = lambda x: cfg["pushover"][x] _cfg = PushoverConfig() _cfg.token = get("token") _cfg.user = get("
user") return _cfg def load_youtube_opts(self, cfg): get = lambda x: cfg["youtube"][x] _cfg = YoutubeConfig() _cfg.access_token = get("access_token") _cfg.client_id = get("client_id") _cfg.client_secret = get("client_secret") _cfg.refresh_token = get("refresh...
# -*- coding: utf-8 -*- # Copyright (C) 2014-2022 Daniele Simonetti # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # ...
Widget(self.bt_new_school) vbox.setSpacing(12) is_path = api.data.schools.is_path( api.character.schools.get_current() ) former_school_adv = api.character.rankadv.get_former_school() former_school = api.data.schools.get(former_school_adv.school) if former_school_ad...
else None # check if the PC is following an alternate path if is_path: # offer to going back if former_school: self.bt_go_on.setText(self.tr("Continue ") + former_school.name) else: self.bt_go_on.setText(self.tr("Go back to your old s...
fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('expression', models.CharField(max_length=255)), ], options={ }, bases=(models.Model,), ), migrations.Cr...
ection', models.CharField(default=b'init=epsg:4326', help_text=b'PROJ4 definition of the map projection', max_length=255)), ('units', models.SmallIntegerField(blank=True, choices=[(5, b'Decimal degrees')])), ('size', models.CommaSeparatedIntegerField(help_text=b'Map size in pixel units',...
e_type', models.CharField(max_length=10, choices=[(b'png', b'png')])), ('ows_sld_enabled', models.BooleanField(default=True)), ('ows_abstract', models.TextField(blank=True)), ('ows_enable_request', models.CharField(default=b'*', max_length=255)), ('ows_enc...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_
dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 30, transform = "
None", sigma = 0.0, exog_count = 20, ar_order = 12);
# -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Erkan Ozgur Yilmaz # # This module is part of oyProjectManager and is released under the BSD 2 # License: http://www.opensource.org/licenses/BSD-2-Clause """ Database Module =============== This is where all the magic happens. .. versionadded:: 0.2.0 SQLite3 Datab...
e data. :returns: sqlalchemy.orm.session """
global engine global session global query global metadata global database_url # create engine # TODO: create tests for this if database_url_in is None: logger.debug("using the default database_url from the config file") # use the default database ...
By: # # Andrea Gavana, @ 16 Aug 2007 # Latest Revision: 14 Apr 2010, 12.00 GMT # # # TODO List # # 1. Find A Way To Reduce Flickering On The 2 ColourPanels; # # 2. See Why wx.GCDC Doesn't Work As I Thought (!). It Looks Slow As A Turtle, # But Probably I Am Doing Something Wrong While Painting The Alpha Textures. # ...
mal format; - When available, a corresponding "Web Safe" colour is generated using a 500 web colours "database" (a dictionary inside the widget source code). Web Safe colours are re
cognized by all the browsers; - When available, a corresponding "HTML name" for the selected colour is displayed, by using the same 500 web colours "database"; - When available, a corresponding "Microsoft Access Code" for the selected colour is displayed, by using the same 500 web colours "database". And much ...
amedtuple import gimp from . import pgpath from . import objectfilter #=============================================================================== pdb = gimp.pdb #========================================
======================================= class ItemData(object): """ This class i
s an interface to store all items (and item groups) of a certain type (e.g. layers, channels or paths) of a GIMP image in an ordered dictionary, allowing to access the items via their names and get various custom attributes derived from the existing item attributes. Use one of the subclasses for items of a c...
#!/usr/bin/env python # coding: utf-8 from module import Module import numpy as np try: from im2col_cyt import im2col_cython, col2im_cython except ImportError: print('Installation broken, please reinstall PyFunt') from numpy.lib.stride_tricks import as_strided def tile_array(a, b1, b2): r, c = a.shape ...
ngNearest, self).__init__() self.scale_factor = scale if self.scale_factor < 1: raise Exception('scale_factor must be greater than 1') if np.floor(self.scale_factor) != self.scale_factor: raise Exception('scale_factor must be integer') def update_output(self, x): ...
e = x.shape out_size[x.ndim - 1] *= self.scale_factor out_size[x.ndim - 2] *= self.scale_factor N, C, H, W = out_size stride = self.scale_factor pool_height = pool_width = stride x_reshaped = x.transpose(2, 3, 0, 1).flatten() out_cols = np.zeros(out_size) ...
Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
ken, but not composed solely of ')' if len(tok) >= 2 and ((tok[0], tok[-1]) in [('"', '"'), ("'", "'")]): # It's a quoted string yield 'string', tok[1:-1] else: yield 'check', _parse_check(clean) # Yield t...
)', ')' def parse_rule(rule): """Parses policy to the tree. Translates a policy written in the policy language into a tree of Check objects. """ # Empty rule means always accept if not rule: return _checks.TrueCheck() # Parse the token stream state = ParseState() fo
#!/usr/bin/env python import telnetlib import time import socket import sys import getpass TELNET_PORT = 23 TELNET_TIMEOUT = 6 def send_command(remot
e_conn, cmd): ''' Initiate the Telnet Session ''' cmd = cmd.rstrip() remote_conn.write(cmd + '\n') time.sleep(1) return remote_conn.read_very_eager() def login(remote_conn, username, password): ''' Login to pynet-rtr1 ''' output = remote_conn.read_until("sername:", TELNET_TI...
'\n') output += remote_conn.read_until("ssword:", TELNET_TIMEOUT) remote_conn.write(password + '\n') return output def no_more(remote_conn, paging_cmd='terminal length 0'): ''' No paging of Output ''' return send_command(remote_conn, paging_cmd) def telnet_connect(ip_addr): ''' Es...
from django.shortcuts import render, render_to_response from django.shortcuts import redirect from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.conf import settings from manage.forms import * from manage.models import * from...
ws.view_images')) else: form = ImageForm() # A empty, unbound form return render(request, 'manage/new-image.html', {'form': form}) def view_images(request): image_list = Image_Data.objects.all() context_dict = {'images': image_list} return render(request, 'manage/view-images.html', context_...
.is_valid(): post = form.save(commit=False) post.save() return HttpResponseRedirect(reverse('manage.views.view_data_models')) else: form = DataModelForm() return render(request, 'manage/new-data-model.html', {'form': form}) def view_data_models(request): model_li...
import numpy as np from scipy.stats import sem import scipy.constants as const from uncertainties import ufloat import uncertainties.unumpy as unp from uncertainties.unumpy import (nominal_values as noms, std_devs as stds) import matplotlib.pyplot as plt from scipy.optimize import curve_fit from PIL import Image import...
Q_(480.0, 'nanometer') n_b = 1.4635 h = Q_(const.
h, 'joule * second') e_0 = Q_(const.e, 'coulomb') mu_bohr = Q_(const.physical_constants['Bohr magneton'][0], 'joule/tesla') c = Q_(const.c, 'meter / second') d = Q_(4, 'millimeter') dispsgebiet_b = lambda_b**2 / (2 * d) * np.sqrt(1 / (n_b**2 - 1)) ## Hysterese, B in mT def poly(x, a, b, c, d): return a * x**3 ...
from mutant_django.generator import DjangoBase def register(app): app.extend_g
enerator('django', django_json_field) def django_json_field(gen): gen.field_generators['JSON'] = JSONField class JSONField(DjangoBase): DJANGO_FIE
LD = 'JSONField' def render_imports(self): return ['from jsonfield import JSONField']
self.is_bdb_compiled(): # Make a legacy wallet and check it is BDB self.nodes[0].createwallet(wallet_name="legacy1", descriptors=False) wallet_info = self.nodes[0].getwalletinfo() assert_equal(wallet_info['format'], 'bdb') self.nodes[0].unloadwallet("legacy1"...
fo3 = send_wrpc.getaddressinfo(addr) assert_equal(info2['desc'], info3['desc']) s
elf.log.info("Test that getnewaddress still works after keypool is exhausted in an encrypted wallet") for _ in range(500): send_wrpc.getnewaddress() self.log.info("Test that unlock is needed when deriving only hardened keys in an encrypted wallet") send_wrpc.walletpassphrase('pass',...
dimensions(8,2) wall((0, 2), (8, 2)) wall((1,
1.5),(1.5, 1.5)) wall((2, 1.6),(2.8, 1.6)) wall((3.1, 1.4),(3.5, 1.4))
initialRobotLoc(1.0, 1.0)
import web urls = ( '/hello','Index' ) app = web.ap
plication(urls,globals()) render = web.template.render('/usr/local/LPTHW/ex51/gothonweb/templates/',base="layout") class Index(object): def GET(self): return re
nder.hello_form() def POST(self): form = web.input(name="Nobody",greet="Hello") greeting = "%s,%s" % (form.greet,form.name) return render.index(greeting = greeting) if __name__ == '__main__': app.run()
import os, sys, re import ConfigParser import optparse import shutil import subprocess import difflib import collections #import numpy as np # Alberto Meseguer file; 18/11/2016 # Modified by Quim Aguirre; 13/03/2017 # This file is the master coordinator of the DIANA project. It is used to run multiple DIANA commands...
eck if the results are already done comp_results_dir = res_dir + "/results_" + drug1 + "_" + drug2 table_file = comp_results_dir + '/table_results_' + drug1 + '_' + drug2 + '.txt' if os.path.exists(table_file): continue command = 'python {}/diana_cluster/scripts/compare_prof...
me/quim/project/diana_cluster/scripts/compare_profiles.py -d1 'DCC0303' -d2 'DCC1743' -pt 'geneid' # To run the command at the local machine #os.system(command) #To run in the cluster submitting files to queues functions.submit_command_to_queue(command, max_jobs_in_queue=int(co...
for x in self._validModuleTargets: if x.name == name: return x return None def validModuleTargets(self): return self._validModuleTargets def invalidModuleTargets(self): return self._invalidModuleTargets # --- PARAMETERS ------------------------...
p def getCorePackage(self, name): tmpW = self.c
oreWorkspace.getPackageByName(name) tmpC = self.core.getPackageByName(name) if tmpW is not None: return tmpW else: if tmpC is not None: return tmpC return None def getCoreModule(self, name): tmpW = self.coreWorkspace.getModuleByName(...
es = self.get_agent_images(docker_client()) def get_agent_images(self, client): images = client.images(filters={'label': SYSTEM_LABEL}) system_images = {} for i in images: try: label_val = i['Labels'][SYSTEM_LABEL] for l in i['RepoTags']: ...
if l.endswith(':latest'): alias = l[:-7] system_images[alias] = label_val except KeyError: pass return system_images @staticmethod def get_container_by(client, func): containers = client.container
s(all=True, trunc=False) containers = filter(func, containers) if len(containers) > 0: return containers[0] return None @staticmethod def find_first(containers, func): containers = filter(func, containers) if len(containers) > 0: return contain...
#!/usr/bin/env python __author__ = 'Jamie Diprose' import rospy from sensor_msgs.msg import JointState from ros_pololu_servo.msg import servo_pololu import math class EinsteinController(): def __init__(self): rospy.init_node('einstein_controller') rospy.Subscriber("joint_angles", JointState, self...
rospy.Publisher("cmd_pololu", servo_pololu) self.joint_ids = {'neck_yaw': 23, 'neck_roll': 2, 'neck_pitch': 3} def handle_joint_angles(self, msg): rospy.logdebug("
Received a joint angle target") for i, joint_name in enumerate(msg.name): servo_msg = servo_pololu() servo_msg.id = self.joint_ids[joint_name] servo_msg.angle = msg.position[i] servo_msg.speed = (msg.velocity * 255.0) servo_msg.acceleration = msg.effo...
# -*- coding: utf-8
-*- # Generated by Django 1.9.7 on 2016-08-19 21:08 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
('coordinates', django.contrib.gis.db.models.fields.PointField(null=True, srid=4326)), ('name', models.CharField(max_length=64)), ], options={ 'abstract': False, }, ), ]
# Copyright 2015 Internap. # # 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, so...
self.reply(message_id, error_to_response(e)) handled = True if not handled: self.reply(message_id, error_to_response(OperationNotSupported(operation_name))) def reply(self, message_id, response): reply = etree.Element("rpc-reply",
xmlns=NS_BASE_1_0, nsmap=self.additionnal_namespaces) reply.attrib["message-id"] = message_id reply.append(response.etree) self.say(reply) if response.require_disconnect: self.logger.info("Disconnecting") self.transport.loseConnection() def say(self, etree_...
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] SECRET_KEY = 'my-key' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = [ 'tests', 'cloudinary_storage', # 'django.contrib.admin', 'django.contrib.auth', 'django.con...
cationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.stora...
ME', 'my-cloud-name'), 'API_KEY': os.getenv('CLOUDINARY_API_KEY', 'my-api-key'), 'API_SECRET': os.getenv('CLOUDINARY_API_SECRET', 'my-api-secret') } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', ...
import unittest from isbn_verifier import is_valid # Tests adapted from `problem-specifications//canonical-data.json` class IsbnVerifierTest(unittest.TestCase): def test_valid_isbn(self): self.assertIs(is_valid("3-598-21508-8"), True) def test_invalid_isbn_check_digit(self): self.assertIs(i...
def test_x_is_only_valid_as_a_check_digit(self):
self.assertIs(is_valid("3-598-2X507-9"), False) def test_valid_isbn_without_separating_dashes(self): self.assertIs(is_valid("3598215088"), True) def test_isbn_without_separating_dashes_and_x_as_check_digit(self): self.assertIs(is_valid("359821507X"), True) def test_isbn_without_check_...
from datetime import datetime import mock from nose.tools import eq_ import mkt import mkt.site.tests from mkt.account.serializers import (AccountSerializer, AccountInfoSerializer, TOSSerializer) from mkt.users.models import UserProfile class TestAccountSerializer(mkt.site.tests...
SOURCE_BROWSERID] def setUp(self): self.account = UserProfile() self.account.pk = 25 def serializer(self): return AccountInfoSerializer(instance=self.account) def test_source_is_a_slug_default(self): eq_(self.serializer().data['source'], self.PERSONA) def test_source_...
NOWN eq_(self.serializer().data['source'], self.PERSONA) def test_source_is_fxa(self): self.account.source = mkt.LOGIN_SOURCE_FXA eq_(self.serializer().data['source'], self.FIREFOX_ACCOUNTS) def test_source_is_invalid(self): self.account.source = -1 eq_(self.serializer(...
('sv_gq'), dp=gt_args.get('sv_dp'), max_dp=gt_args.get('sv_max_dp'), het_ab=gt_args.get('sv_het_ab'), hom_ab=gt_args.get('sv_hom_ab'), ...
amily_filter.g2p: if csqs is None: csqs = getattr(record, self.csq_attribute) if self.family_filter.check_g2p_consequence: fail = (not x for x in self.family_filter.g2p.csq_and_allelic_
requirement_met( csqs, inheritance)) else: fail = (not x for x in self.family_filter.g2p.allelic_requirement_met( csqs, inheritance)) if ignore_csq: ignore_csq = [x or y for x...
t, image_width, 1] assert blue.get_shape().as_list()[1:] == [image_height, image_width, 1] bgr = tf.concat([ blue - VGG_MEAN[0], green - VGG_MEAN[1], red - VGG_MEAN[2], ],3) assert bgr.get_shape().as_list()[1:] == [image_height, image_width, 3] ...
onv_cls_score, conv_cls_wd = self.conv_layer_new(self.relu_proposal_all, 'conv_cls_score', kernel_size=[1, 1], out_channel=18, stddev=0.01) self.conv_bbox_pred, conv_bbox_wd = self.conv_layer_n
ew(self.relu_proposal_all, 'conv_bbox_pred', kernel_size=[1, 1], out_channel=36, stddev=0.01) self.weight_dacay += conv_cls_wd + conv_bbox_wd assert self.conv_cls_score.get_shape().as_list()[1:] == [feature_height, feature_width, 18] ...
import sys import os import re import shutil from setuptools import setup name = 'django-skivvy' package = 'skivvy' description = ('Write faster integration tests for Django views – with less ' 'code.') url = 'https://github.com/oliverroick/django-skivvy' author = 'Oliver Roick' author_email = 'oliver.r...
get_version(package) if sys.argv[-1] == 'publish': if os.system("pip freeze | grep twine"): print("twine not installed.\nUse `pip install twine`.\nExiting.") sys.exit() shutil.rmtree('dist', ignore_errors=True) shutil.rmtree('build', ignore_errors=True) os.system("python setup.py sdist...
") print("You probably want to also tag the version now:") print(" git tag -a {0} -m 'version {0}'".format(version)) print(" git push --tags") sys.exit() setup( name=name, version=version, url=url, license=license, description=description, long_description=long_description, ...
a new primary partition for LVM - parted: device: /dev/sdb number: 2 flags: [ lvm ] state: present part_start: 1GiB # Read device information (always use unit when probing) - parted: device=/dev/sdb unit=MiB register: sdb_info # Remove all partitions from disk - parted: device: /dev/sdb ...
def format_disk_size(size_bytes, unit): """ Formats a size in bytes into a different unit, like parted does. It doesn't manage CYL and CHS formats, though. This function has been adapted from https://github.com/Distrotech/parted/blo b/279d9d869ff472c52b9ec2e180d5
68f0c99e30b0/libparted/unit.c """ global units_si, units_iec unit = unit.lower() # Shortcut if size_bytes == 0: return 0.0 # Cases where we default to 'compact' if unit in ['', 'compact', 'cyl', 'chs']: index = max(0, int( (math.log10(size_bytes) - 1.0) / 3.0 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html import os from smart_open import smart_open try: import cPickle as _pickle except ImportError: import pickle as _pickle from gensi...
=2): fname_dict = fname + '.d' self.index.save(fname) d = {'f': self.model.vector_size, 'num_trees': self.num_trees, 'labels': self.labels} with smart_open(fname_dict, 'wb') as fout: _pickle.dump(d, fout, protocol=protocol) def load(self, fname): fname_dict = fna...
restore AnnoyIndexer state." % (fname, fname_dict)) else: with smart_open(fname_dict) as f: d = _pickle.loads(f.read()) self.num_trees = d['num_trees'] self.index = AnnoyIndex(d['f']) self.index.load(fname) self.labels = d['labels'] ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Deepin, Inc. # 2011 Wang Yong # 2012 Reza Faiz A # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # Reza Faiz A <ylpmiskrad@gmail.com> # Remixed : Reza Faiz A <ylpmi...
upgradeAlign = gtk.Alignment() upgradeAlign.set(1.0, 0.0, 0.0, 1.0) upgradeAlign.add(upgradeBox) self.numLabel = gtk.Label() sel
f.ignoreNumBox = gtk.HBox() self.ignoreNumAlign = gtk.Alignment() self.ignoreNumAlign.set(0.0, 0.5, 0.0, 0.0) self.ignoreNumAlign.add(self.ignoreNumBox) self.selectAllId = "selectAll" self.unselectAllId = "unselectAll" self.labelId = self.selectAllId ...
# coding=utf8 from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from __future__ import division import os from os.path import join import tempfile import shutil from six.moves import configparser import pytest from tests import setenv, test_doc0 f...
app_dir, index
_dir @pytest.fixture def tmp_app_index_dirs(tmp_app_index_dir_paths): tmpd, appd, indexd = tmp_app_index_dir_paths os.mkdir(appd) os.mkdir(indexd) return tmpd, appd, indexd @pytest.fixture def index_empty(request, tmp_app_index_dirs): _, app_dir, index_dir = tmp_app_index_dirs orig_home = o...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class SexyItem(scrapy.Item): # define the fields for your item here like: name = scrapy.Field()
dirname = scrapy.Fiel
d() file_urls = scrapy.Field() files = scrapy.Field()
class Printer(object): """ """ def __init__(self): self._depth = -1 self._str = str self.emptyPrinter = str def doprint(self, e
xpr): """Returns the pretty representation for expr (as
a string)""" return self._str(self._print(expr)) def _print(self, expr): self._depth += 1 # See if the class of expr is known, or if one of its super # classes is known, and use that pretty function res = None for cls in expr.__class__.__mro__: if hasatt...
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-11-02 10:04 from __future__ import unicode_literals from django.db import migrations def update_version_queues(apps, schema_editor): VersionQueue = apps.get_model('repository', 'VersionQueue') for
queue in VersionQueue.objects.all(): queue.title = queue.preprint.title queue.abstract = queue.preprint.abstract queue.save()
class Migration(migrations.Migration): dependencies = [ ('repository', '0019_auto_20201030_1423'), ] operations = [ migrations.RunPython( update_version_queues, reverse_code=migrations.RunPython.noop, ) ]
# Copyright 2021 The Chromium OS Authors. All rights reserved. # Use of this source code is gove
rned by a BSD-style license that can be # found in the
LICENSE file. register_host_test("ec_app")
###########################
##### # These variables are overwritten by Zenoss when the ZenPac
k is exported # or saved. Do not modify them directly here. # NB: PACKAGES is deprecated NAME = "ZenPacks.community.SquidMon" VERSION = "1.0" AUTHOR = "Josh Baird" LICENSE = "GPLv2" NAMESPACE_PACKAGES = ['ZenPacks', 'ZenPacks.community'] PACKAGES = ['ZenPacks', 'ZenPacks.community', 'ZenPacks.community.SquidMon'] INST...
#!/usr/bin
/python # -*- coding: utf-8 -*- from .tinytag import TinyTag, StringWalker, ID3, Ogg, Wave, Flac __version__ = '0.9.1' if __name__ == '__main__'
: print(TinyTag.get(sys.argv[1]))
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015 Monk-ee (magic.monkee.magic@gmail.
com). # """__init__.py: Init for unit testing this module.""" __author__ = "monkee" __maintainer__ = "monk-ee" __email__ = "magic.monkee.magic@gmail.com" __status__ = "Development" import unittest from PuppetDBClientTestCaseV2 import PuppetDBClientTestCaseV2 from PuppetDBClientTestCaseV3 import PuppetDBClientTestCa...
e(PuppetDBClientTestCaseV3)) return suite
# -*- coding: utf-8 -*- # Copyright(C) 2013 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms o
f the GNU Affero General Public License as published by # the Free Software
Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for mor...
from pymander.e
xceptions import CantParseLine from pymander.handlers import LineHandler, RegexLineHandler, ArgparseLineHandler from pymander.contexts import StandardPrompt from pymander.commander import Commander from pymander.decorators import bind_command class DeeperLineHandler(LineHandler): def try_execute(self, line): ...
self.context.write('Going deeper!\nNow in: {0}\n'.format(deeper_context)) return deeper_context raise CantParseLine(line) class RaynorLineHandler(LineHandler): def try_execute(self, line): if line.strip() == 'kerrigan': self.context.write('Oh, Sarah...\n') ...
from django.conf.urls import include, url from django.contrib import admin from rest_framework.routers import DefaultRouter from sk_map.api.map import MapViewSet, WallViewSet, BoxViewSet, PointViewSet, MenViewSet,\ WallListViewSet, BoxListViewSet, PointListViewSet, MenListViewSet, MapListViewSet from sk_auth.api.au...
delete': 'destroy'} action_with_patch = {'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'} action_no_pk = {'get': 'list', 'post': 'create'} router = DefaultRouter() rout
er.register(r'skins', SkinView) router.register(r'auth/register', RegisterView) urlpatterns = router.urls urlpatterns_game = [ url('^game/(?P<map>\d+)/$', GameViewSet.as_view({'get': 'retrieve', 'patch': 'partial_update'})), url('^game/$', GameViewSet.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'des...
nd the most expansive ones (adv. stargate) ~ 6 days. # We are using log10() as it's quicker than log() _magicBase = 1.0 / (turnsPerDay * 2) _repairMagicBase = math.log10(480 * structDefaultCpCosts) ** 2 * _magicBase repairRatioFunc = lambda x: _repairMagicBase / math.log10(x) ** 2 # building decay ratio bigger or equiv...
combatRetreatWait = 3 starGateDamage = 0.2 # damage for 100% speed boost (doub
le for 200%, etc...) shipDecayRatio = 0.04 maxDamageAbsorb = 5 # max absorbed damage for tech "damageAbsorb" property. # max seq_mod equipments of equipType; anything not in list is unlimited maxEquipType = { 'ECM' : 1, # +Missile DEF 'Combat Bonuses' : 1, # +%ATT, +%DEF 'Combat Modifiers' : 1, # +ATT, +DEF...
"""__Main__.""" import sys import os import logging import argparse import traceback import shelve from datetime import datetime from CONSTANTS import CONSTANTS from settings.settings import load_config, load_core, load_remote, load_email from settings.settings import load_html, load_sms from core import read_structure...
il_log(CONSTANTS['log_file_path'], email, html) sys.exit() file(pidfile, 'w').write(pid) (ffmpeg, local) = load_core(config) # load core configs remote = load_remote(config) html = load_html(config) sms = load_sms(con
fig) email = load_email(config) if(args.log): email = load_email(config) if(args.report): html = load_html(config) if(args.remote): remote = load_remote(config) if(args.sms): sms = load_sms(config) video_db = shelve.open(CONSTANTS['video_db_path'], writeba...
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
for i, navire in enumerate(navires): msg += "\n |ent|{}|ff
| - {}".format(i + 1, navire.desc_survol) else: msg = "|att|Vous ne possédez aucun navire " \ "pouvant servir au recrutement.|ff|" personnage << msg