prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
er the License. # Glance Release Notes documentation build configuration file, created by # sphinx-quickstart on Tue Nov 3 17:40:50 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. #...
ll overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to t
his directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and das...
"""List the IP forwarding rules"
"" from baseCmd import * from baseResponse import * class listIpForwardingRulesCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "false" """list resources by account. Must be used with the domainId parameter.""" self.account = None self.typeInfo['account'] = 'str...
D.""" self.id = None self.typeInfo['id'] = 'uuid' """list the rule belonging to this public IP address""" self.ipaddressid = None self.typeInfo['ipaddressid'] = 'uuid' """defaults to false, but if true, lists all resources from the parent specified by the domainId till le...
import os from datetime import date from unittest.mock import MagicMock, call import pytest import imagesize from kaleidoscope import renderer, generator from kaleidoscope.model import Gallery, Album, Section, Photo from kaleidoscope.generator import generate, DefaultListener def test_generate_gallery_index(tmpdir,...
nail(tmpdir, gallery_with_one_photo): """Generator should create thumbnail file.""" generate(gallery_with_one_photo, str(tmpdir)) thumb_path = tmpdir.join("album", "thumb", "photo.jpg") assert thumb_path.exists() assert imagesize.get(str(thumb_path)) <= (300, 200) def test_resize_large(tmpdir, gal...
ery_with_one_photo, str(tmpdir)) large_path = tmpdir.join("album", "large", "photo.jpg") assert large_path.exists() assert imagesize.get(str(large_path)) <= (1500, 1000) def test_resize_existing(tmpdir, gallery_with_one_photo): """When resized image allready exists, do not resize it again.""" thum...
import announcements, users, corporate, api, volunteer, teams, innovation def configure_routes(app): app.add_url_rule('/', 'landing', view_func=users.views.landing, methods=['GET']) # Signing Up/Registration app.add_url_rule('/register', 'sign-up', view_func=users.views.sign_up, methods=['GET', 'POST']) ...
.views.create_announcement, methods=['POST']) app.add_url_rule('/api/partners', 'partners', view_func=api.views.partner_list, methods=['GET']) app.add_url_rule('/api/schedule', 'schedule', view_func=api.views.schedule, methods=['GET']) app.add_url_rule('/api
/schedule/<day>', 'day-schedule', view_func=api.views.schedule_day, methods=['GET']) app.add_url_rule('/api/check-in', 'check-in-api', view_func=api.views.check_in, methods=['GET', 'POST']) app.add_url_rule('/api/passbook', 'passbook', view_func=api.views.passbook, methods=['POST']) # Corporate Portal ...
as live_poll_main properties = { 'daemons': ['arbiter', 'receiver'], 'type': 'ws_nocout', 'external': True, } # called by the plugin manager to get a broker def get_instance(plugin): # info("[WS_Nocout] get_instance ...") instance = WsNocout(plugin) return instance # Main app var. Will be fill with our runni...
ne else current_time_stamp, h, r, o) else: cmd = '[%s] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%s;%s' % (t if t is not None else current_time_stamp, h,
s, r, o) logger.debug("[WS_Nocout] CMD: %s" % (cmd)) commands.append(cmd) # Trivial case: empty commmand list if (return_codes is None or len(return_codes) == 0): return commands # Sanity check: if we get N return codes, we must have N hosts. # The other values could be None if (len(return_codes) != len(h...
from __future__ import absolute_import from __future__ import division # Copyright (c) 2010-2016 openpyxl """Manage Excel date weirdness.""" # Python stdlib imports import datetime from datetime import timedelta, tzinfo import re from jdcal import ( gcal2jd, jd2gcal, MJD_0 ) from openpyxl.compat import ...
@lru_cache() def days_to_time(value):
mins, seconds = divmod(value.seconds, 60) hours, mins = divmod(mins, 60) return datetime.time(hours, mins, seconds, value.microseconds)
tabsClass import TabClass import simplejson from subprocess import Popen, PIPE, STDOUT import roslib import signal roslib.load_manifest('qbo_webi'); import rospy import time from uuid import getnode as get_mac from poster.encode import multipart_encode from poster.streaminghttp import register_openers import url...
elf.juliusPath=roslib.packages.get_pkg_dir("qbo_listen") self.juliusAMPath="/usr/share/qbo-julius-model/" self.htmlTemplate = Template(filename='voiceRecognition/templates/v
oiceRecognitionTemplate.html') self.jsTemplate = Template(filename='voiceRecognition/templates/voiceRecognitionTemplate.js') self.tmpdir="/tmp/" self.LMPaths="/config/LM/" self.LMFileName="/sentences.conf" self.PhonemsFileName="/phonems" self.TiedlistFileName="/tiedlist" ...
Debian, Ubuntu, Fedora, RedHat, openSUSE, Linaro, ScientificLinux, Arch, CentOS, AMI. - Any distribution that uses systemd as their init system. - Note, this module does *NOT* modify /etc/hosts. You need to modify it yourself using other modules like template or replace. options: name: required: tr...
me(self, name): self.strategy.set_permanent_hostname(name) class GenericStrategy(object): """ This is a generic Hostname manipulation strategy class. A subclass may wish to override some or all of these methods. - get_current_hostname() - get_permanent_hostname() - set_current_ho...
nent_hostname(name) """ def __init__(self, module): self.module = module self.hostname_cmd = self.module.get_bin_path('hostname', True) def get_current_hostname(self): cmd = [self.hostname_cmd] rc, out, err = self.module.run_command(cmd) if rc != 0: self...
#coding: utf-8 import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # Allow setup.py to be
run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-dbmessages', version='0.2.0a', packages=['dbmessages'], in
clude_package_data=True, license='BSD License', description='Request-independent messaging for Django on top of contrib.messages', long_description=README, author='Upwork, Anton Strogonoff', author_email='python@upwork.com', maintainer='Anton Strogonoff', maintainer_email='anton@strogonoff.n...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @author: Will """ from django import forms from app01 import models class ImportFrom(forms.Form): HOST_TYPE=((1,"001"),(
2,"002")) #替換爲文件 host_type = forms.IntegerField( widget=forms.Select(choices=HOST_TYPE) ) hostname = forms.CharField() def __init__(self,*args,**kwargs): super(ImportFrom,self).__init__(*args,**kwargs) HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件 ...
models.userInfo.objects.filter()
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-09-01 22:26:01 # @Author : Your Name (you@example.org) # @Link : http://example.org # @Version : $Id$ import os import threading import requests import lxml from threading import Thread from bs4 impor
t BeautifulSoup import sys reload(sys) sys.setdefaultencoding('utf-8') pic_path = 'pic/' # 保存文件路径 URL = 'http://www.nanrenwo.net/z/tupian/hashiqitupian/' URL1 = 'http://www.nanrenwo.net/' class Worker(threading.Thread): def __init__(self, url, img, filename): super(Worker, self).__init__() self.url = url ...
lename = filename def run(self): try: u = self.url + self.img r = requests.get(u, stream=True) with open(self.filename, 'wb') as fd: for chunk in r.iter_content(4096): fd.write(chunk) except Exception, e: raise def get_imgs(url): t = 1 r = requests.get(url, stream=True) soup = BeautifulS...
""" .. _tut_stats_cluster_source_2samp: ========================================================================= 2 samples permutation test on source data with spatio-temporal clustering ========================================================================= Tests if the source space data are significantly differe...
clustering. This can take a long time... # Here we set the threshold quite high to reduce computation. p_threshold = 0.0001 f_threshold = stats.distributions.f.ppf(1. - p_threshold / 2., n_subjects1 - 1, n_subjects2 - 1) print('Clustering.') T_obs, clusters, cluster_p_values, ...
d=f_threshold) # Now select the clusters that are sig. at p < 0.05 (note that this value # is multiple-comparisons corrected). good_cluster_inds = np.where(cluster_p_values < 0.05)[0] ############################################################################### # Visualize the clusters print('Visualizing clus...
# Download the Python helper librar
y from twilio.com/docs/python/install from twilio.rest.ip_messaging import TwilioIpMessagingClient # Your Account Sid and
Auth Token from twilio.com/user/account account = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" token = "your_auth_token" client = TwilioIpMessagingClient(account, token) service = client.services.get(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") channel = service.channels.get(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") messages = ...
from typing import Optional, Tuple import os import sys from distutils.version import LooseVersion from version import PROVISION_VERSION from scripts.lib.zulip_tools import get_dev_uuid_var_path def get_major_version(v): # type: (str) -> int return int(v.split('.')[0]) def get_version_file(): # type: () ...
is at version %s, and we compare it to the version in source control (version.py), which is %s. ''' def preamble(version): # type: (str) -> str text = PREAMBLE % (version, PROVISION_VERSION) text += '\n' return text NEED_TO_DOWNGRADE = ''' It loo
ks like you checked out a branch that expects an older version of dependencies than the version you provisioned last. This may be ok, but it's likely that you either want to rebase your branch on top of upstream/master or re-provision your VM. Do this: `./tools/provision` ''' NEED_TO_UPGRADE = ''' It looks like you c...
import json import pytest from indy import crypto, did, error @pytest.mark.asyncio async def test_auth_crypt_works_for_created_key(wallet_handle, seed_my1, verkey_my2, message): verkey = await did.create_key(wallet_handle, json.dumps({'seed': seed_my1})) await crypto.auth_crypt(wallet_handle, verkey, verkey...
let_handle, verkey_my1, verkey_my2, message): with pytest.raises(error.WalletInvalidHandle): invalid_wallet_handle = wallet_handle + 1 await crypto.auth_crypt(invalid_wallet_handle, verkey_my1, verkey_my2, message) @pytest.mark.asyncio async def test_auth_crypt_works_for_invalid_recipient_vk(walle...
y_trustee1, message): (_, key) = identity_trustee1 with pytest.raises(error.CommonInvalidStructure): await crypto.auth_crypt(wallet_handle, key, 'CnEDk___MnmiHXEV1WFgbV___eYnPqs___TdcZaNhFVW', message)
#!/usr/bin/python3 ############# # this is to be leaded by every module. # I think #import mysglobal as g # args,loggerr @every module ################# import logging from logzero import setup_logger,LogFormatter,colors import argparse import os,sys import json from blessings import Terminal import getpass # ...
looks for all executables; * ... already present in .config.json E ... atribute enable is there + or - ... attribute enable is true or false p ... attribute perm is ON; also a,x PATHS: when ~/.myservice/test/aaa myservice2 aaa enable : finds a path and ad...
connects to the screen -x myservice2_infinite """, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-d','--debug', action='store_true' , help='') #parser.add_argument('-s','--serfmsg', default='',nargs="+" , help='serf message to mmap') # list will come after #parser.add_argument('count', action=...
# Copyright 2015 - StackStorm, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
c_parser, dsl_yaml ) class WorkbookSpecValidationTestCase(WorkflowSpecValidationTestCase): def __init__(self, *args, **kwargs): super(WorkbookSpecValidationTes
tCase, self).__init__(*args, **kwargs) self._spec_parser = spec_parser.get_workbook_spec_from_yaml self._dsl_blank = { 'version': '2.0', 'name': 'test_wb' } def _parse_dsl_spec(self, dsl_file=None, add_tasks=False, changes=None, expect_error...
import requests import datetime import calendar class DeskTime(object): MAIN_URL = 'https://desktime.com/api/2/json/?{params}' def __init__(self, app_key, username, password): self.api_key = self._login(app_key, username, password) if self.api_key is None: raise Excepti...
tinue elif date > today: return None if not with_weeke
nds and date.weekday() in (5, 6): continue data.append(self.getAllDataForDate(date)) for elem in data: resdata[elem.get('date')] = elem.get('employees') return data def getEmployee(self, employee_id): raise(NotImplementedError)
ER_ZONE, task_id="id" ) mock_hook.return_value.create_instance.side_effect = mock.Mock( side_effect=google.api_core.exceptions.GoogleAPICallError('error')) with self.assertRaises(google.api_core.exceptions.GoogleAPICallError): op.execute(None) mock_...
rn_value = None with self.assertRaises(AirflowException) as e: op = BigtableClusterUpdateOperator( instance_id=INSTANCE_ID, cluster_id=CLUSTER_ID, nodes=NODES, task_id="id" ) op.execute(None) err = e.ex...
lled_once_with() mock_hook.return_value.update_cluster.assert_not_called() @mock.patch('airflow.contrib.operators.gcp_bigtable_operator.BigtableHook') def test_updating_cluster_that_does_not_exists(self, mock_hook): instance = mock_hook.return_value.get_instance.return_value = mock.Mock(Instanc...
changeme if issparse(A): A = np.array(A.todense()) else: A = np.array(A) d1, d2 = np.shape(Cn) d, nr = np.shape(A) if max_number is None: max_number = nr x, y = np.mgrid[0:d1:1, 0:d2:1] pl.imshow(Cn, interpolation=None, cmap=cmap) cm = com(A, d1, d2) Bmat ...
ag_AA = true flag_AA: boolean (default true)
Returns: parllcomp: list of sets list of subsets of components. The components of each subset can be updated in parallel len_parrllcomp: list length of each subset Author: Eftychios A. Pnevmatikakis, Simons Foundation, 2017 """ K = np.shape(A)[-1] ...
for i in range(100
0000): def f(x, y=1
, *args, **kw): pass
# pylint: skip-file class GCPResourc
e(object): '''Object to represent a gcp resource''' def __init__(self, rname, rtype, project, zone): '''constructor for gcp resource''' self._name = rname self._type = rtype self._project = project self._zone = zone @property def name(self): '''property ...
'''property for project''' return self._project @property def zone(self): '''property for zone''' return self._zone
__author__ = "Jacob Lydon" __copyright__ = "Copyright 2017" __credits__ = [] __license__ = "GPLv3"
__version__ = "0.1" __maintainer__ = "Jacob Lydon"
__email__ = "jlydon001@regis.edu" __status__ = "Development"
# /ciscripts/chec
k/python/__init__.py # # Module loader file for /ciscripts/check/python. # # See /LICENCE.md for Copyright
information """Module loader file for /ciscripts/check/python."""
# Build Code import os import subprocess import re class GCC: def __init__(self): self.enter_match = re.compile(r'Entering directory') self.leave_match = re.compile(r'Leaving directory') def can_build(self, dirname, ext): if ext in (".c", ".h", ".cpp", ".hpp"): files = [f.lower() for f in os.listdir(dirn...
tion, output): args = ["make"] if action: args.append(action) print(args) proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) errorLines = [] while True: line = proc.stdout.readline().decode("utf-8")
if len(line) == 0: break output.write(line) if line.startswith("In file included from"): errorLines.append(line) else: idx = line.find("Entering directory") if idx >= 0: errorLines.append(line) else: idx = line.find("Leaving directory") if idx >= 0: errorLines.append...
import maya.cmds as cmds from . import renamer_settings as settings class FieldReplacer(object): def __init__(self): print 'Initializing jsRenamer FieldReplacer...' #replaceMaterial = self.replaceMaterial def checkTemplate(self,node): #availPos = ['C','L','R','LF','RF','LB','RB','U',...
=each.split('|')[-1] else: replacerOldName = each bodySplit = replacerOldName.split('_') newBodyName = bodySplit[0]+'_'+bodySplit[1]+'_'+bodyReplace+'_'+bodySplit[3]+'_'+body
Split[4] #print newBodyName cmds.rename(each,newBodyName) else: cmds.error(each+' does not match naming Template (default_C_default_0000_???)') ###Replace GEO_Suffix def replaceGeoSuffix(self, args=None): ReplaceSel = cmds.ls(sl=1) ...
async def post(self, request): """Trigger a Google Actions sync.""" hass = request.app["hass"] cloud: Cloud = hass.data[DOMAIN] gconf = await cloud.client.get_google_config() status = await gconf.async_sync_entities(gconf.agent_user_id) return self.json({}, status_co...
e}) class CloudLogoutView(HomeAssistantView): """Log out of the Home Assistant cloud.""" url = "/api/cloud/logout" name = "api:cloud:logout" @_handle_cloud_errors async def post(self, request): """Handle logout request.""
" hass = request.app["hass"] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await cloud.logout() return self.json_message("ok") class CloudRegisterView(HomeAssistantView): """Register on the Home Assistant cloud.""" url = "/api/cloud/regis...
import web db = web.datab
ase(dbn='mysql', db='googlemodules', user='ale', passwd='3babes') for url in db.select('function', what='screenshot'): print 'http://www.googlemodules.com/image/screenshot'
class PSFModel(object): def __init__(self, scopeType, psfModel, xySpace, zSpace, emissionWavelength, numericalAperture, designImmersionOilRefractiveIndex, \ designSpecimenLayerRefractiveIndex, actualImmersionOilRefractiveIndex, \ actualSpecimenLayerRefractiveIndex, actualPointSourceDepthInSpecimenLayer, home...
umericalAperture=numericalAperture self.designImmersionOilRefractiveIndex=designImmersionOilRefractiveIndex self.designSpecimenLayerRefractiveIndex=designSpecimenLayerRefractiveIndex self.actualImmersionOilRefractiveIndex=actualImmersionOilRefractiveIndex self.actualSpecim
enLayerRefractiveIndex=actualSpecimenLayerRefractiveIndex self.actualPointSourceDepthInSpecimenLayer=actualPointSourceDepthInSpecimenLayer def CreatePsf(self, command, psfCommandName, xSize, ySize, zSize): module=command.run(psfCommandName, True, \ "xSize", xSize, \ "ySize", ySize, \ "zSize", zSize, \ "ff...
# -*- coding:utf-8 -*- '''Created on 2014-8-7 @author: Administrator ''' from sys import path as sys_path if not '..' in sys_path:sys_path.append("..") #用于import上级目录的模块 import web #早起的把一个文件分成多个文件,再把class导入 from login.login import (index,login,loginCheck,In,reset,register,find_password) from blog.blog imp...
sess
ion=session else: session=web.config._session #用以下方式可以解决多文件之间传递session的问题 def session_hook():web.ctx.session=session app.add_processor(web.loadhook(session_hook)) if __name__=='__main__': app.run()
#!/usr/bin/python import participantCollection participantCollection = participantCollection.ParticipantCollection() numberStillIn = participantCollection.sizeOfParticipantsWhoAreStillIn() initialNumber = participantCollection.size() print "There are currently **" + str(numberStillIn) + " out of " + str(initialNumber...
:" print "" for participant in participantCollection.participantsWhoAreStillInAndHaveCheckedIn(): print "/u/" + participant.name print "" print "These participants have not reported a relapse, so they are still in the running, but **if they do not check in
by the end of today, they will be removed from the list, and will not be considered victorious**:" print "" for participant in participantCollection.participantsWhoAreStillInAndHaveNotCheckedIn(): print "/u/" + participant.name + " ~" print ""
from __future__ import absolute_import, division, print_function, unicode_literals # Statsd client. Loosely based on the version by Steve Ivy <steveivy@gmail.com> import logging import random import socket import time from contextlib import contextmanager log = logging.getLogger(__name__) class StatsD(object): ...
e self.enabled = False @contextmanager de
f timed(self, stat, sample_rate=1): log.debug('Entering timed context for %r' % (stat,)) start = time.time() yield duration = int((time.time() - start) * 1000) log.debug('Exiting timed context for %r' % (stat,)) self.timing(stat, duration, sample_rate) def timing(sel...
__version
__ = '0.0
.1'
E|re.UNICODE), ': - ') re_mauseparador = (re.compile(ur'(?P<prevchar>[\)a-z])\:[ \.][\–\–\—\-](?P<firstword>[\w\»])', re.LOCALE|re.UNICODE), '\g<prevchar>: - \g<firstword>') re_titulo = (re.compile(ur'((O Sr[\.:])|(A Sr\.?(ª)?))(?!( Deputad))'), '') re_ministro = (re.compile(ur'^Ministr'), '') re_secestado = (re.comp...
text = re.split(re_separador[0], p, 1) speaker = re.sub(re_titulo[0], re_titulo[1], speaker,
count=1).strip(u'ª \n') p = speaker + ': - ' + text.strip() if p.startswith('Presidente'): return self.parse_president(p) elif re.match(re_ministro[0], p) or re.match(re_secestado[0], p): return self.parse_government(p) ...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distrib
uted 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 use this file except in compliance # with the License. You may ob
tain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the...
return_sequences=True, go_backwards=False, name='rnn_fw') self.rnn_bw = tf.keras.layers.CuDNNLSTM(units=num_units // 2, return_sequences=True, ...
sent_im_dist = - similarity_fn(text_feats, img_fe
ats) else: loss = embedding_loss(img_feats, text_feats, labels, self.margin, self.num_neg_sample, self.lambda1, self.lambda2) sent_im_dist = pdist(text_feats, img_feats) rec = recall_k(sent_im_dist, labels, ks=[1, 5, 10]) return loss, rec def order_sim(im, s): im ...
''' Created on 11/02/2010 @author: henry@henryjenkins.name ''' class webInterface(object): ''' classdocs ''' writeFile = None def __init__(self): pass def __openFile(self, fileName): self.writeFile = open(fileName, 'w') def closeFile(self): self.w...
File.write('</HEAD>\n') def writeBody(self, users): self.writeFile.write('<BODY>\n') self.writeFile.write('<table border="1">') self.writeFile.write('<tr>') self.writeFile.write('<td>IP address</td>') self.writeFile.write('<td>On-peak Packets</td>') self.wri...
self.writeFile.write('<td>Off-peak Data</td>') self.writeFile.write('<td>Total Packets</td>') self.writeFile.write('<td>Total Data</td>') self.writeFile.write('</tr>') usersList = users.keys() usersList.sort() for user in usersList: self.writeFi...
import platform # ----------------------------------------------------------------------------- # Guess platform we are running on def current_platform(): machine = platfor
m.machine() if machine == 'armv5tejl': return 'ev3' elif machine == 'armv6l': return 'brickpi' else: return 'unsupported' if current_platform() ==
'brickpi': from .brickpi import * else: # Import ev3 by default, so that it is covered by documentation. from .ev3 import *
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os import requests import sys import tempfile import zipfile from . import Command class Deploy(Command): """Deploy a module on an Odoo instance""" def __init__(self): super(Deploy, self).__init__() self.session = requests.se...
eturn temp except Exception: os.remove(temp) raise def run(self, cmdargs): parser = argparse.ArgumentParser( prog="%s deploy" % sys.argv[0].split(os.path.sep)[-1], description=self.__doc__ ) parser.add_argument('path', help="Path of th...
rl', nargs='?', help='Url of the server (default=http://localhost:8069)', default="http://localhost:8069") parser.add_argument('--db', dest='db', help='Database to use if server does not use db-filter.') parser.add_argument('--login', dest='login', default="admin", help='Login (default=admin)') ...
#!/usr/bin/python # # Urwid html fragment output wrapper for "screen shots" # Copyright (C) 2004-2007 Ian Ward # # 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 # v...
nd(html_span(run, aspec, cx-col)) el
se: l.append(html_span(run, aspec)) col += run_width else: l.append(html_span(run, aspec)) l.append("\n") # add the fragment to the list self.fragments.append( "<pre>%s</pre>" % "".join(l) ) def clear(self...
from django.contrib import admin # from models import Agent, ReCa, Accom
odation, Beach, Activity, Contact # # @admin.register(ReCa, Activity) # class VenueAdmin(admin.ModelAdmin): # list_display = ('name', 'internal_rating', 'ready', 'description',) # list_filter = ('ready', 'internal_rating',) # search_fields = ['name', 'description', 'address'] # ordering = ['id'] # s
ave_on_top = True # # # @admin.register(Accomodation) # class AccomodAdmin(VenueAdmin): # list_display = ('name', 'stars', 'ready', 'description',) # list_filter = ('ready', 'stars',) # # # @admin.register(Beach) # class BeachAdmin(admin.ModelAdmin): # list_display = ('name', 'type', 'description',) # list_filt...
029]') # This is required because u() will mangle the string and ur'' isn't valid # python3 syntax ESCAPE = re.compile(u'[\\x00-\\x1f\\\\"\\b\\f\\n\\r\\t\u2028\u2029]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', ...
ies will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for ...
sentation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ',...
The proportion of the mask which is ``True`` :type: double """ return (self.n_true * 1.0) / self.n_pixels @property def proportion_false(self): r""" The proportion of the mask which is ``False`` :type: double """ return (self.n_false * 1.0) / s...
""" # Ignore the channel axis return np.vstack(np.nonzero(self.pixels[..., 0])).T @property def false_indices(self): r""" The indices of pixels that are false. :type: (``n_dims``, ``n_false``) ndarray
""" # Ignore the channel axis return np.vstack(np.nonzero(~self.pixels[..., 0])).T @property def all_indices(self): r""" Indices into all pixels of the mask, as consistent with true_indices and false_indices :type: (``n_dims``, ``n_pixels``) ndarray "...
from buildbot.status import tests from buildbot.process.step import SUCCESS, FAILURE, BuildStep from buildbot.process.step_twisted import RunUnitTests from zope.interface import implements from twisted.python import log, failure from twisted.spread import jelly from twisted.pb.tokens import BananaError from twisted.w...
lts.countFailures() color = "green" text = [] if count == 0: text.extend(["%d %s" % \ (total, total == 1 and "test" or "tests"), "passed"]) else: text.append("tests") text.appe...
count == 1 and "failure" or "failures")) color = "red" self.updateCurrentActivity(color=color, text=text) self.addFileToCurrentActivity("tests", self.results) #self.finishStatusSummary() self.finishCurrentActivity()
#!/usr/bin/env python3 """ Calculate minor reads coverage. Minor-read ratio (MRR), which was defined as the ratio of reads for the less covered allele (reference or variant allele) over the total number of reads covering the position at which the variant was called. (Only applied to hetero sites.) ...
ad =[int(y) for y in temp[outGenoArrayIndex[1]].split(',')] ref += ad[0] alt += sum(ad[1:]) out = ss[:2] + ss[3:5] mrc = 1 if ref == 0 and alt == 0: mrc = 1 else: minor = min(alt*1.0/(alt + ref), ref*1.0/(alt + ref)) ...
'-f']: if mrc >= cutoff: sys.stdout.write('%s'%(str(line))) infile.close() sys.stdout.flush() sys.stdout.close() sys.stderr.flush() sys.stderr.close()
# -*- coding: utf-8 -*- # pylint: disable=no-init """ Django settings for home_web project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djang...
-production settings """ DEBUG = False SECRET_KEY = values.SecretValue() ADMINS = values.SingleNestedTupleValue()
ALLOWED_HOSTS = values.ListValue() DATABASES = values.DatabaseURLValue() EMAIL = values.EmailURLValue() REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONP...
#!/usr/bin/env python import sys def gen_test(n): print "CREATE TABLE t (a CHAR(%d));" % (n) for v in [ 'hi', 'there', 'people' ]: print "INSERT INTO t VALUES ('%s');" % (v) for i in range(2,256): if i < n: print "--replace_regex /MariaDB/XYZ/ /MySQL/XYZ/" print "--e...
GE COLUMN a a CHAR(%d);" % (i) if i >= n: print "let $diff_tables=test.t, test.ti;" print "source include/diff_tables.inc;"
print "DROP TABLE ti;" print "DROP TABLE t;" def main(): print "source include/have_tokudb.inc;" print "# this test is generated by change_char.py" print "# test char expansion" print "--disable_warnings" print "DROP TABLE IF EXISTS t,ti;" print "--enable_warnings" print "SET SESS...
from django.contrib import admin from devilry.devilry_dbcache.models import AssignmentGroupCachedData @admin.register(AssignmentGroupCachedData) class AssignmentGroupCachedDataAdmin(admin.ModelAdmin): list_display = [ 'id', 'group', 'first_feedbackset', 'last_feedbackset', ...
'group__parentnode__parentnode__short_name', 'group__parentnode__parentnode__long_name', 'group__parentnode__parentnode__parentnode__id', 'group__parentnode__parentnode__parentnode__short_name', 'group__parentnode__parentnode__parentnode__long_name', 'group__candidates__relatedst...
dates__relatedstudent__user__fullname', 'group__examiners__relatedexaminer__user__shortname', 'group__examiners__relatedexaminer__user__fullname', ]
# -*- coding: utf-8 -*- ############################################################################### # # GetTimestamp # Returns the current date and time, expressed as seconds or milliseconds since January 1, 1970 (epoch time). # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the...
is Choreo. ((optional, integer)
Sets the hours (0–23) of the specified date serial number.) """ super(GetTimestampInputSet, self)._set_input('SetHour', value) def set_SetMinute(self, value): """ Set the value of the SetMinute input for this Choreo. ((optional, integer) Sets the minutes (0–59) of the specified date ...
import sys, os def stop(arv): pwd = os.getcwd() # if argv given, f
olders = [argv] # else, folders = pwd ### for each folder in folders ##### check pwd/folder/temp/pids for existing pid files ####### kill -15 & rm files def main(): print "Please don't try to
run this script separately." if __name__ == '__main__': main()
unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin class TestListInterface(object): config = """ templates: global: disable: [seen] tasks: list_get: entry_list: test_list lis...
uRay DTS-HD MA 5 1 x264-FuzerHD.torrent", imdb_id: "tt0303933"} - {title: 'Drumline 2002 DVDRip x264-FuzerHD', url: "http://mock.url/Drumline 2002 DVDRip x264-FuzerHD.torrent", imdb_id: "tt0303933"} list_match: from: - movie_list: test_list_queue sin...
entry_list: test_list list_clear: what: - entry_list: test_list test_list_clear_exit: entry_list: test_list list_clear: what: - entry_list: test_list phase: exit test_list_clear_input: ...
Tetherless World Constellation at Rensselaer Polytechnic Institute # 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 use, copy,...
stname: str - hostname of remote server (default: localhost) @param port: port number on remote server (default: 22) @param inputfile: str - local path to the file to uploaded @param outputfile: remot
e path to the file to upload @param link: bolean [True, False] default False, print a link to download the file (remote path needs to be in a web available directory) @param apacheroot: path to apache root default to '/var/www/' required if link == True @para...
ord(cells, direction=DOWN): """ Under the hood: given two cells and a favoured direction, get the position of the cell with the column of one and the row of the other: A---->+ | ^ | | | | v | ...
return self.table.select_other(function, self) def select_other(self, function, other): """A
more general version of select, where another bag to select from is explicitly specified rather than using the original bag's table""" """note: self.select(f) = self.table.select_other(f, self)""" newbag = Bag(table=self.table) for bag_cell in self.__store: for other_cell in...
from django.db import models from stdimage import StdImageField from django.core.validators import RegexValidator import datetime YEAR_CHOICES = [] for r in range(1980, (datetime.datetime.now().year+1)): YEAR_CHOICES.append((r,r)) S_CHOICE = [('1stYear','1stYear'),('2ndYear','2ndYear'),('3rdYear','3rdYear'),('4t...
ame = models.CharField(max_length=100) PictureLoc
ation = StdImageField(upload_to='Hostels/galary/',variations={'large': (675, 300,True)}) def __str__(self): return self.PictureName class HostelBody(models.Model): HostelName = models.ForeignKey(Hostel) HostelbodyRole = models.CharField(max_length=100) HostelbodyRoleYear = models.IntegerField(choices=YEAR_CHOI...
#!/usr/bin/python2 # Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All...
plot.grid(True) plot.set_title(key + " (decision)") plot.plot(decisions[key]['time'], decisions[key]['value']) f.subplots_adjust(hspace=0.3) plt.show() if
__name__ == "__main__": main()
# coding=utf-8 """ Faça um programa, contendo subprogramas, que: a) Leia da entrada padrão as dimensões, quantidade de linhas e quantidade de colunas de uma matriz bidimensional; b) Gere uma matriz, onde cada célula é um número inteiro gerado aleatoriamente no intervalo 0 a 9; c) Mostre a matriz, linha a linha na tel...
andint def gera_matriz(linhas, colunas): matrix = [] for linha in range(linhas): linha = [] for coluna in range(colunas): linha.append(randint(0, 9)) matrix.append(linha) return matrix def imprime_matriz(matriz): for linha in matriz: for coluna
in linha: print(coluna, end=" ") print() print() def media_da_matriz(matriz): total = 0.0 for linha in matriz: for coluna in linha: total += coluna return total / (len(matriz) * len(matriz[0])) def imprive_valores_acima_da_media(matriz, media): for linha ...
#!/usr/bin/env python # Copyright 2015, Google, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in co
mpliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expres...
guage governing permissions and # limitations under the License. """Command-line application that demonstrates basic BigQuery API usage. This sample queries a public shakespeare dataset and displays the 10 of Shakespeare's works with the greatest number of distinct words. This sample is used on this page: https...
""" core.mixins - Mixins available to use with models """ from django.db.models.signals import post_save def on_changed(sender, **kwargs): """ Calls the `model_changed` method and then resets the state. """ instance = kwargs.get("instance") is_new
= kwargs.get("created") dirty_fields = instance.get_dirty_fields() instance.model_changed(instance.original_state, dirty_fields, is_new) i
nstance.original_state = instance.to_dict() class ModelChangedMixin(object): """ Mixin for detecting changes to a model """ def __init__(self, *args, **kwargs): super(ModelChangedMixin, self).__init__(*args, **kwargs) self.original_state = self.to_dict() identifier = "{0}_model...
# pyOCD debugger # Copyright (c) 2006-2020 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # 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...
! @brief Write data on the OUT endpoint associated to the HID interface """ data.extend([0] * (self.packet_size - len(data))) # LOG.debug("snd>(%d) %s" % (len(data), ' '.join(['%02x' % i for i in data]))) self.report.send([0] + data) def read(self, timeout=20.0):
"""! @brief Read data on the IN endpoint associated to the HID interface """ with Timeout(timeout) as t_o: while t_o.check(): if len(self.rcv_data): break sleep(0) else: # Read operations should typically take ~1...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
ce created. Default value: True . :type auto_start: bool :param monitoring_interval_in_seconds: Monitoring interval in seconds. Default value: 60 . :type monitoring_interval_in_seconds: int """ _validation = { 'source': {'required': True}, 'destination': {'required': True}, ...
ce'}, 'destination': {'key': 'destination', 'type': 'ConnectionMonitorDestination'}, 'auto_start': {'key': 'autoStart', 'type': 'bool'}, 'monitoring_interval_in_seconds': {'key': 'monitoringIntervalInSeconds', 'type': 'int'}, } def __init__(self, **kwargs): super(ConnectionMonit...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: r...
"Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH envir
onment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
import numpy as np import pandas as pd import pickle # Return 0 or 1 based on whether Course fulfills a General Education Requirement def lookupGenEd(cNum, college): fileName = "data/Dietrich Gen Eds.csv" picklepath = "data\\dietrich_gen_eds.p" t
ry: with open(picklepath,'rb') as file:
gen_eds = pickle.load(file) except: df = pd.read_csv(fileName,names=['Dept','Num','Title','1','2']) gen_eds = set(df['Dept'].values) with open(picklepath,'wb') as file: pickle.dump(gen_eds,file) return cNum in gen_eds ''' genEdubility = lookupGenEd(73100, "dietri...
#!/usr/bin/env python3 # -*-
coding: utf-8 -*- """ Created on Wed Jun 7 21:16:09 2017 @author: immersinn """ import regex as re def billsummaryaref_matcher(tag): return tag.name =='a' and hasattr(tag, 'text') and tag.text == 'View Available Bill Summaries' def extract_links(soup): """Extract Bill Text Links from Bill Page""" bill...
ent_table = target_a.parent.parent.parent for row in content_table.find_all('tr')[2:]: row_info = {} arefs = row.find_all('td')[0].find_all('a') for a in arefs: if a.text == 'HTML': row_info['html'] = a['href'] else: ...
#!/usr/bin/env python # # VM Backup extension # # Copyright 2015 Microsoft Corporation # # 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 # # U...
: 'patch_boot_system', 'dest': 'completed', 'conditions': 'should_exit_previous_state' }, ] def on_enter_state(self): super(Ubuntu1604EncryptionStateMachine, self).on_enter_state() def should_exit_previous_state(self): # when this is called, self.state is st...
r(Ubuntu1604EncryptionStateMachine, self).should_exit_previous_state() def __init__(self, hutil, distro_patcher, logger, encryption_environment): super(Ubuntu1604EncryptionStateMachine, self).__init__(hutil, distro_patcher, logger, encryption_environment) self.state_objs = { 'prereq': ...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Cumulus Networks <ce-ceng@cumulusnetworks.com> # 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 ANSIBLE_METADATA = {'metadata_versio...
on:
- List of ports to run initial run at 10G. speed_40g: description: - List of ports to run initial run at 40G. speed_4_by_10g: description: - List of 40G ports that will be unganged to run as 4 10G ports. speed_40g_div_4: description: - List of 1...
import numpy as np def gauss(win, sigma): x = np.arange(0, win, 1, float) y = x[:,np.newaxis] x0 = y0 = win // 2 g=1/(2*np.pi*sigma**2)*np.exp((((x-x0)**2+(y-y0)**2))/2*sigma**2) return g
def gaussx(win, sigma): x = np.arange(0, win, 1, float) y = x[:,np.newaxis] x0 = y0 = win // 2 gx=(x-x0)/(2*np.pi*sigma**4)*np.exp((((x-x0)**2+(y-y0)**2))/2*sigma**2) return gx def gaussy(win, sigma): x = np.arange(0, win, 1, float) y = x[:,np.newaxis] x0 = y0 ...
return gy
self._solver.add(x > 1) self._solver.add(y > 1) self._solver.add(x != y) self.assertEqual(self._solver.check(), "sat") x_val = self._solver.get_value(x) y_val = self._solver.get_value(y) z_val = self._solver.get_value(z) self.assertTrue((x_val * y_val) & 0xfff...
"x", x) self._solver.declare_fun("y", y) self._solver.declare_fun("z", z) self._solver.add(x % y == z) # Add constraints to avoid trivial solutions. self._solver.add(x > 1) self._solver.add(y > 1) self._solver.add(x != y) self.assertEqual(self._solver.c...
_solver.get_value(y) z_val = self._solver.get_value(z) self.assertTrue(x_val % y_val == z_val) def test_neg(self): x = BitVec(32, "x") z = BitVec(32, "z") self._solver.declare_fun("x", x) self._solver.declare_fun("z", z) self._solver.add(-x == z) ...
#!/usr/bin/env python ############################################################################### # $Id: sgi.py 31335 2015-11-04 00:17:39Z goatbar $ # # Project: GDAL/OGR Test Suite # Purpose: PNM (Portable Anyware Map) Testing. # Author: Frank Warmerdam <warmerdam@pobox.com> # #################################...
d documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the followin...
otice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHO...
import json import os import avasdk from zipfile import ZipFile, BadZipFile from avasdk.plugins.manifest import validate_manifest from avasdk.plugins.hasher import hash_plugin from django import forms from django.core.validators import ValidationError from .validators import ZipArchiveValidator class PluginArchive...
ile_path()) as plugin: prefix = self.get_prefix(plugin) prefix = prefix + '/' if len(prefix) else '' with plugin.open('{}/README.md'.format(prefix)) as myfile: readme = myfile.read() return readme except FileNotFoundError: ...
, please try again') except KeyError: return None def clean(self, data, initial=None): f = super().clean(data, initial) manifest = self.get_manifest(f) readme = self.get_readme(f) return { 'zipfile': f, 'manifest': manifest, 'r...
#author: Tobias Andermann, tobias.andermann@bioenv.gu.se import os import sys import re import glob import shutil import argparse from Bio import SeqIO from .utils import CompletePath # Get arguments def get_args(): parser = argparse.ArgumentParser( description="Set the maximum fraction of missing data that you ...
final_seqs.setdefault(header,[]).append(sequence) else: print("Dropped sequence for", header) for seqnam
e, seq in final_seqs.items(): sequence = str(seq[0]) outfile.write(">"+seqname+"\n") outfile.write(sequence+"\n") outfile.close manage_homzygous_samples(alignment,max_mis,out_dir)
# Copyright (C)2016 D. Plaindoux. # # This program 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, or (at your option) any # later version. import unittest import path_parse_test import path_match_test import provider_test import verb_test import mime_test import inspection_test import wsgi_test if ...
name__ == '__main__': suite = unittest.TestSuite() suite.addTest(path_parse_test.suite()) suite.addTest(path_match_test.suite()) suite.addTest(verb_test.suite()) suite.addTest(mime_test.suite()) suite.addTest(provider_test.suite()) suite.addTest(inspection_test.suite()) suite.addTest(wsg...
from django.apps import AppConfig cla
ss QsiteConfig(AppConfig):
name = 'qsite' verbose_name = '站点管理'
import json from httpretty import HTTPretty from social.p3 import urlencode from social.tests.backends.oauth import OAuth1Test class YahooOAuth1Test(OAuth1Test): backend_path = 'social.backends.yahoo.YahooOAuth' us
er_data_url = 'https://social.yahooapis.com/v1/user/a-guid/profile?' \ 'format=json' expected_username = 'foobar' access_token_body = js
on.dumps({ 'access_token': 'foobar', 'token_type': 'bearer' }) request_token_body = urlencode({ 'oauth_token_secret': 'foobar-secret', 'oauth_token': 'foobar', 'oauth_callback_confirmed': 'true' }) guid_body = json.dumps({ 'guid': { 'uri': 'htt...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import six import unittest2 from robottelo.ui.location import Location from robottelo.ui.locators import common_locators from robottelo.ui.locators import locators if six.PY2: import mock else: from unittest import mock class LocationTestCase(...
one, users=None, params=None ) def test_creation_with_parent_and_unassigned_host(self): location = Location(None) location.click = mock.Mock() location.assign_value = mock.Mock() location.wait_until_element = mock.Mock() location._configure_location = moc...
les all_capsules domains hostgroups medias organizations ' 'envs ptables resources select subnets templates users params ' 'select'.split() } location.create('foo', 'parent', **configure_arguments) click_calls = [ mock.call(locators['location.new']), ...
# Copyright 2020 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for
the specific language governing permissions and # limitations under the License. # from glob import glob import json from pathlib import Path import sys """Convert existing intent tests to behave tests.""" TEMPLATE = """ Scenario: {scenario} Given an english speaking user When the user says "{utterance}" ...
from django import template import datetime register = template.Library() # https://stackoverflow.com/a/8907269/2226755 def strfdelta(tdelta, fmt): d = {"days": tdelta.days} d["hours"], rem = divmod(tdelta.seconds, 3600) d["minutes"], d["seconds"] = divmod(rem, 60) return fmt.format(**d) # TODO add...
"" duration = dateti
me.timedelta(seconds=value) if datetime.timedelta(hours=1) > duration: return strfdelta(duration, "{minutes}m{seconds}s") else: return strfdelta(duration, "{hours}h{minutes}m{seconds}s")
import olymap.skill def test_learn_time(): tests = ( ({}, None), ({'SK': {'tl': ['14']}}, '14'), ({'SK': {'an': ['0']}}, None), ({'IT': {'tl': ['1']}}, None),
({'SK': {'an': ['1']}}, None), ) for box, answer in tests: assert olymap.skill.get_learn_time(box) == answer def test_get_required_s
kill(): tests = ( ({}, None), ({'SK': {'rs': ['632']}}, {'id': '632', 'oid': '632', 'name': 'Determine inventory of character'}), ({'SK': {'rs': ['630']}}, {'id': '630', 'oid': '630', 'name': 'Stealth'}), ({'SK': {'re': ['632']}}, None), ({'SL': {'rs': ['6...
fro
m Model import * import MemoryDecay # Note we cannot import TwoConcepts here because that ends up modifying the grammar, ruining it fo
r example loaders
mport string import tempfile import shutil import threading import exceptions import errno from collections import defaultdict from xml.etree import ElementTree import nixops.statefile import nixops.backends import nixops.logger import nixops.parallel from nixops.nix_expr import RawValue, Function, Call, nixmerge, py2n...
/../../../../share/nix/nixops")
if not os.path.exists(self.expr_path): self.expr_path = os.path.dirname(__file__) + "/../nix" self.resources = {} with self._db: c = self._db.cursor() c.execute("select id, name, type from Resources where deployment = ?", (self.uuid,)) for (id, name, type...
meter_name, None) def lookups(self, request, model_admin): """ Must be overridden to return a list of tuples (value, verbose value) """ raise NotImplementedError( 'The SimpleListFilter.lookups() method must be overridden to ' 'return a list of tuples (value, ...
self.field.null): extra = 1 else:
extra = 0 return len(self.lookup_choices) + extra > 1 def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def field_choices(self, field, request, model_admin): return field.get_choices(include_blank=False) def choices(self, cl): fr...
from django.contrib import admin from rawParser.models import flightSearch #
Register your models here. admin.site.register(flig
htSearch)
# -*- coding: utf-8 -*- # # Copyright (c) 2016-2017 Ircam # Copyright (c) 2016-2017 Guillaume Pellerin # Copyright (c) 2016-2017 Emilie Zawadzki # This file is part of mezzanine-organization. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public L...
istributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTAB
ILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
# -*- coding: utf-8 -*- # # powerschool_apps documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration valu...
r', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ...
tation', """Iron County School District""", 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show pa...
from parabem.pan2d
import doublet_2_1 import parabem import numpy as np v1 = par
abem.PanelVector2(-1, 0) v2 = parabem.PanelVector2(1, 0) panel = parabem.Panel2([v2, v1]) vals = ([doublet_2_1(parabem.Vector2(x, 0), panel, True) for x in np.linspace(-2, 2, 20)]) print(vals)
__author__ = 'rls' class Robot: """Represents a robot, with a name.""" # A class variable, counting the number of robots population = 0 def __init__(self, name): """Initializes the data.""" self.name = name print('(Initializing {})'.format(self.name)) # When this pers...
print("There are still {:d} robots working.".format(Robot.population)) def say_hi(self): """Greeting by the robot Long doc statement.""" print("Greetings, my masters have called me {}".format(self.name)) @classm
ethod def how_many(cls): """Prints the current population.""" print("We have {:d} robots.".format(cls.population)) droid1 = Robot("R2-D2") droid1.say_hi() Robot.how_many() __version__ = 0.2
None, bind=('_ui_mode',)) '''Defines tries to ascertain the kind of device the app is running on. Cane be one of `tablet` or `phone`. :data:`ui_mode` is a read only `AliasProperty` Defaults to 'phone' ''' def __init__(self, **kwargs): # i...
data.strip() if is_address(data): self.set_URI(data) return if data.startswith('fujicoin:'): self.set_URI(data) return
# try to decode transaction from electrum.transaction import Transaction from electrum.util import bh2u try: text = bh2u(base_decode(data, None, base=43)) tx = Transaction(text) tx.deserialize() except: tx = None if tx: ...
""" Order module has been split for its complexity. Proposed clean hierarchy for GASSupplierOrder that can be used in many contexts such as: DES: ChooseSupplier ChooseGAS ChooseReferrer GAS: ChooseSupplier OneGAS ChooseReferrer Supplier: OneSupplier ChooseGAS ChooseR...
is will be a FUTURE module update Factory function `form_class_factory_for_request` is there for: * composition of final classes (XAddOrderForm, PlannedAddOrderForm, InterGASAddOrderForm) * follows GAS configuration options and prepare delivery and withdrawal fields Where can you find above clas...
erForm (where X can be des,gas,supplier,pact) * __init__.form_class_factory_for_request * extra.PlannedAddOrderForm #TODO LEFT OUT NOW * intergas.InterGASAddOrderForm There are also some other classes that support order interactions: * gmo.SingleGASMemberOrderForm * gmo.BasketGASMemberOrderForm ...
#!/usr/bin/env python # Copyright (C) 2008,2011 Lanedo GmbH # # Author: Tim Janik # # 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 lat...
# carry out online bug queries def bug_summaries (buglisturl): if not buglisturl: re
turn [] # Bugzilla query to use query = buglisturl + '&ctype=csv' # buglisturl.replace (',', '%2c') query = add_auth (query) f = urllib.urlopen (query) csvdata = f.read() f.close() # read CSV lines reader = csv.reader (csvdata.splitlines (1)) # parse head to interpret columns col_bug_id = -1 col_d...
# *-* coding:utf-8 *-* from functools import partial # 可读性好 # range() print range
(0,9,2) #递增列表 for i in xrange(0,9,2): # 只用于for 循环中 print i albums = ("Poe","Gaudi","Freud","Poe2") years = (1976,1987,1990,2003) for album in sorted(albums): print album for album in reversed(albums): print album for i,album in enumerate(albums): print i,album for album,yr in
zip(albums,years): print album,yr # 列表表达式 # 8.12 列表解析,列表解析的表达式比map lambda效率更高 def fuc(a): return a**2 x = range(1,10,1) print x print map(fuc,x) # map 对所有的列表元素执行一个操作 # lambda 创建只有一行的函数 -- 只使用一次,非公用的函数 print map(lambda x:x**2,range(6)) print [x**2 for x in range(6) if x>3] print filter(lambda...
t=None): acquirer = self.browse(cr, uid, id, context=context) return self._get_paypal_urls(cr, uid, acquirer.environment, context=context)['paypal_form_url'] def _paypal_s2s_get_access_token(self, cr, uid, ids, context=None): """ Note: see # see http://stackoverflow.com/questions/24...
handling_amount' in data and float_compare(float(data.get('handling_amount')), tx.fees, 2) != 0: invalid_parameters.append(('handling_amount', data.get('handling_amount'), tx.fees)) # check buyer if tx.partner_reference and data.get('payer_id') != tx.partner_reference: invalid_pa...
id.paypal_seller_account and data['receiver_id'] != tx.acquirer_id.paypal_seller_account: invalid_parameters.append(('receiver_id', data.get('receiver_id'), tx.acquirer_id.paypal_seller_account)) if not data.get('receiver_id') or not tx.acquirer_id.paypal_seller_account: # Check receiver...
# Copyright (C) 2003-2009 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko 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 (a...
oin(self.ROOT, target_path[1:]) try: os.symlink(target_path, path) except OSError as e: return SFTPServer.convert_errno(e.errno) return SFTP_OK
def readlink(self, path): path = self._realpath(path) try: symlink = os.readlink(path) except OSError as e: return SFTPServer.convert_errno(e.errno) # if it's absolute, remove the root if os.path.isabs(symlink): if symlink[:len(self.ROOT)] == ...
, tmax, tstep): times = numpy.array(range(tmin, tmax, tstep)) spike_ids = sorted(spike_list) possible_neurons = range(min_idx, max_idx) spikeArray = dict([(neuron, times) for neuron in spike_ids if neuron in possible_neurons]) return spikeArray def convert_file_to_spikes(input_file_name, mi...
ible_input=True): # splice_files expects a list of files, a list of lists, one for each file, giving the onset # and offset times for each file, and a list of neuro
ns relevant to each file, which will be # spliced together into a single spike list. spikeArray = {} if input_times is None: input_times = [[(None, None)] for file_idx in len(input_files)] for file_idx in len(input_files): if input_neurons is None or input_neurons[file_idx] is None: m...
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import nu
mpy as np import os sourcefiles = [ 'fast_likelihood.pyx'] ext_modules = [Extension("fast_likelihood", sourcefiles, include_dirs = [np.get_include()], extra_compile_args=['-O3', '-fopenmp', '-lc++'], extra_link_args...
_modules = ext_modules )
# Extend the b26 chain to make sure bitcoind isn't accepting b26 b27 = block(27, spend=out[7]) yield rejected(RejectResult(0, b'bad-prevblk')) # Now try a too-large-coinbase script tip(15) b28 = block(28, spend=out[6]) b28.vtx[0].vin[0].scriptSig = b'\x00' * 101 ...
ck(34, spend=out[10], script=too_many_multisigs) yield rejected(RejectResult(16, b'bad-blk-sigops')) # CHECKSIGVERIFY tip(33) lots_of_checksigs = CScript([OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS - 1)) b35 = block(35, spend=out[10], script=lots_of_checksigs) yield accepte...
pendable_output() too_many_checksigs = CScript([OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS)) block(36, spend=out[11], script=too_many_checksigs) yield rejected(RejectResult(16, b'bad-blk-sigops')) # Check spending of a transaction in a block which failed to connect # # b6 ...
# encoding: utf-8 import datetime import django from south.db import db from south.v2 import SchemaMigration from django.db import models # Django 1.5+ compatibility if django.VERSION >= (1, 5): from django.contrib.auth import get_user_model else: from django.contrib.auth.models import User def get_user...
b.models.fields.NullBooleanField')(null=True, blank=True)), ('percent', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=3, decimal_places=1, blank=True)), ('superusers', self.gf('django.db.models.fields.BooleanField')(default=True)), ('staff', self.gf('django.db...
se)), ('rollout', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal('waffle', ['Flag']) # Adding M2M table for field groups on 'Flag' db.create_table('waffle_flag_groups', ( ('id', models.AutoField(verbose_name='ID', primar...
# -*- Mode: Python; py-indent-offset: 4 -*- # pygobject - Python bindings for the GObject library # Copyright (C) 2006-2012 Johan Dahlin # # glib/__init__.py: initialisation file for glib module # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Pub...
e = _glib.filename_display_basename filename_display_name = _glib.filename_display_name filename_from_utf8 = _glib.filename_from_utf8 find_program_in_path = _glib.find_program_in_path get_applicat
ion_name = _glib.get_application_name get_current_time = _glib.get_current_time get_prgname = _glib.get_prgname get_system_config_dirs = _glib.get_system_config_dirs get_system_data_dirs = _glib.get_system_data_dirs get_user_cache_dir = _glib.get_user_cache_dir get_user_config_dir = _glib.get_user_config_dir get_user_d...
""" HTMLParser-based link extractor """ from HTMLParser import HTMLParser from urlparse import urljoin from w3lib.url import safe_url_string from scrapy.link import Link from scrapy.utils.python import unique as unique_list class HtmlParserLinkExtractor(HTMLParser): def __init__(self, tag="a", attr="href", pro...
ponse
_text) self.close() links = unique_list(self.links, key=lambda link: link.url) if self.unique else self.links ret = [] base_url = urljoin(response_url, self.base_url) if self.base_url else response_url for link in links: if isinstance(link.url, unicode): ...
se ValidationError({ 'lag': f"The selected LAG interface ({self.lag}) belongs to {self.lag.device}, which is not part " f"of virtual chassis {self.device.virtual_chassis}." }) # A virtual interface cannot have a parent LAG if self.type == I...
serial = models.CharField( max_length=50, verbose_name='Serial number', blank=True ) asset_tag = models.CharField( max_length=50, unique=True, blank=True, n
ull=True, verbose_name='Asset tag', help_text='A unique tag used to ident
''' GameData.py Last Updated: 3/16/17 ''' import json, os import numpy as np import pygame as pg from GameAssets import GameAssets as ga class GameData(): """ GameData class is used to stores game state information. """ def __init__(self): ''' Method initiates game state variables. ...
_dim'] = self.screen_dim json_dump = json.dumps(data) f.write(json_dump) except Exception as e: print("Could Save Config:", filename) print(e) def load_config(self, filename): ''' Method loads game data configurations to file. ...
filename ;str config filename ''' try: with open("../data/" + filename, "r") as f: for json_dump in f: data = json.loads(json_dump) self.controls = data['controls'] self.screen_dim = data['screen_d...
# -*- coding: utf-8 -*- # Third Party Stuff # Third Party Stuff from rest_framework.pagination import PageNumberPagination as DrfPageNumberPagination class PageNumberPagination(DrfPageNumberPagination): # Client can co
ntrol the page using this query parameter. page_query_param = 'page' # Client can control the page size using this query parameter. # Default is 'None'. Set to eg 'page_size' to enable usage. page_size_query_param = 'per_page' # Set to an integer to limit the maximum page size the client may reque...
max_page_size = 1000