""" A few bits of helper functions for comment views. """ import textwrap from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, resolve_url from django.template import RequestContext from django.core.exceptions import ObjectDoesNotExist from django.contrib import comments from django.utils.http import is_safe_url from django.utils.six.moves.urllib.parse import urlencode def next_redirect(request, fallback, **get_kwargs): """ Handle the "where should I go next?" part of comment views. The next value could be a ``?next=...`` GET arg or the URL of a given view (``fallback``). See the view modules for examples. Returns an ``HttpResponseRedirect``. """ next = request.POST.get('next') if not is_safe_url(url=next, host=request.get_host()): next = resolve_url(fallback) if get_kwargs: if '#' in next: tmp = next.rsplit('#', 1) next = tmp[0] anchor = '#' + tmp[1] else: anchor = '' joiner = '&' if '?' in next else '?' next += joiner + urlencode(get_kwargs) + anchor return HttpResponseRedirect(next) def confirmation_view(template, doc="Display a confirmation view."): """ Confirmation view generator for the "comment was posted/flagged/deleted/approved" views. """ def confirmed(request): comment = None if 'c' in request.GET: try: comment = comments.get_model().objects.get(pk=request.GET['c']) except (ObjectDoesNotExist, ValueError): pass return render_to_response(template, {'comment': comment}, context_instance=RequestContext(request) ) confirmed.__doc__ = textwrap.dedent("""\ %s Templates: :template:`%s`` Context: comment The posted comment """ % (doc, template) ) return confirmed import collections class OrderedSet(collections.MutableSet): def __init__(self, iterable=None): self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.map = {} # key --> [key, prev, next] if iterable is not None: self |= iterable def __len__(self): return len(self.map) def __contains__(self, key): return key in self.map def add(self, key): if key not in self.map: end = self.end curr = end[1] curr[2] = end[1] = self.map[key] = [key, curr, end] def discard(self, key): if key in self.map: key, prev, next = self.map.pop(key) prev[2] = next next[1] = prev def __iter__(self): end = self.end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def pop(self, last=True): if not self: raise KeyError('set is empty') key = self.end[1][0] if last else self.end[2][0] self.discard(key) return key def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self)) def __eq__(self, other): if isinstance(other, OrderedSet): return len(self) == len(other) and list(self) == list(other) return set(self) == set(other) if __name__ == '__main__': s = OrderedSet('abracadaba') t = OrderedSet('simsalabim') print(s | t) print(s & t) print(s - t) #!/adsc/DDEA_PROTO/bin/python # coding: utf-8 """ ====================================================================== Learning and Visualizing the BMS sensor-time-weather data structure ====================================================================== This example employs several unsupervised learning techniques to extract the energy data structure from variations in Building Automation System (BAS) and historial weather data. The fundermental timelet for analysis are 15 min, referred to as Q. ** currently use H (Hour) as a fundermental timelet, need to change later ** The following analysis steps are designed and to be executed. Data Pre-processing -------------------------- - Data Retrieval and Standardization - Outlier Detection - Interpolation Data Summarization -------------------------- - Data Transformation - Sensor Clustering Model Discovery Bayesian Network -------------------------- - Automatic State Classification - Structure Discovery and Analysis """ #print(__doc__) # Author: Deokwooo Jung deokwoo.jung@gmail.compile ################################################################## # General Moduels from __future__ import division # To forace float point division import os import sys import numpy as np from numpy.linalg import inv from numpy.linalg import norm import uuid import pylab as pl from scipy import signal from scipy import stats from scipy.interpolate import interp1d import matplotlib.pyplot as plt from multiprocessing import Pool #from datetime import datetime import datetime as dt from dateutil import tz import shlex, subprocess import mytool as mt import time import retrieve_weather as rw import itertools import calendar import random from matplotlib.collections import LineCollection import pprint import radar_chart # Custom library from data_tools import * from data_retrieval import * from pack_cluster import * from data_preprocess import * from shared_constants import * from pre_bn_state_processing import * from data_summerization import * ################################################################## # Interactive mode for plotting plt.ion() ################################################################## # Processing Configuraiton Settings ################################################################## # all BEMS and weather data is built into a signel variable, 'data_dict'. # 'data_dict' is a 'dictionary' data structure of python. # For debugging or experiment purpose, the program allows to store 'data_dict' variable # to data_dict.bin by setting a flag variabe, IS_USING_SAVED_DICT # IS_USING_SAVED_DICT=0 (Default) : Build a new 'data_dict' variabe and store it to 'data_dict.bin' # IS_USING_SAVED_DICT=1 : Skip to build 'data_dict' and load 'data_dict.bin' instead # IS_USING_SAVED_DICT=-1 : Neither build nor load 'data_dict' # Default flag for processing PRE_BN_STAGE=0 if PRE_BN_STAGE>0: IS_USING_SAVED_DICT=1 CHECK_DATA_FORMAT=0 Data_Summarization=1 # Setting Analysis period where ANS_START_T and ANS_START_T are the starting and # and the ending timestamp. ANS_START_T=dt.datetime(2013,6,1,0) ANS_END_T=dt.datetime(2013,12,1,0) # Setting for analysis time interval where all BEMS and weather data is aligned # for a slotted time line quantized by TIMELET_INV. TIMELET_INV=dt.timedelta(minutes=60) print TIMELET_INV, 'time slot interval is set for this data set !!' print '-------------------------------------------------------------------' # Compute Average Feature if PROC_AVG ==True PROC_AVG=True # Compute Differential Feature if PROC_DIFF ==True PROC_DIFF=True ################################################################## # List buildings and substation names # Skip all data PRE_BN_STAGE #['GW1','GW2','VAK1','VAK2'] bldg_key_set=['GW2'] if PRE_BN_STAGE==0: bldg_key_set_run=[] print 'skip PRE_BN_STAGE....' else: bldg_key_set_run=bldg_key_set # Retrieving a set of sensors having a key value in bldg_key_set for bldg_key in bldg_key_set_run: print '###############################################################################' print '###############################################################################' print 'Processing '+ bldg_key+'.....' print '###############################################################################' print '###############################################################################' #temp=subprocess.check_output('ls '+DATA_DIR+'*'+bldg_key+'*.bin', shell=True) temp=subprocess.check_output('ls '+DATA_DIR+'*'+bldg_key+'*.bin | grep POWER', shell=True) input_files_temp =shlex.split(temp) # Get rid of duplicated files input_files_temp=list(set(input_files_temp)) input_files=input_files_temp ############################################################################### # This directly searches files from bin file name print '###############################################################################' print '# Data Pre-Processing' print '###############################################################################' # define input_files to be read if IS_USING_SAVED_DICT==0: print 'Extract a common time range...' ANS_START_T,ANS_END_T,input_file_to_be_included=\ time_range_check(input_files,ANS_START_T,ANS_END_T,TIMELET_INV) print 'time range readjusted to (' ,ANS_START_T, ', ', ANS_END_T,')' start__dictproc_t=time.time() data_dict,purge_list=\ construct_data_dict(input_file_to_be_included,ANS_START_T,ANS_END_T,TIMELET_INV,\ binfilename=PROC_OUT_DIR + 'data_dict',IS_USING_PARALLEL=IS_USING_PARALLEL_OPT) end__dictproc_t=time.time() print 'the time of construct data dict.bin is ', end__dictproc_t-start__dictproc_t, ' sec' print '--------------------------------------' elif IS_USING_SAVED_DICT==1: print 'Loading data dictionary......' start__dictproc_t=time.time() data_dict = mt.loadObjectBinaryFast(PROC_OUT_DIR +'data_dict.bin') end__dictproc_t=time.time() print 'the time of loading data dict.bin is ', end__dictproc_t-start__dictproc_t, ' sec' print '--------------------------------------' else: print 'Skip data dict' if CHECK_DATA_FORMAT==1: # This is for data verification purpose # You cab skip it if you are sure that there would be no bug in the 'construct_data_dict' function. list_of_wrong_data_format=verify_data_format(data_dict) if len(list_of_wrong_data_format)>0: print 'Measurement list below' print '----------------------------------------' print list_of_wrong_data_format raise NameError('Errors in data format') # This perform data summerization process. if Data_Summarization==1: bldg_out=data_summerization(bldg_key,data_dict,PROC_AVG=True,PROC_DIFF=True) RECON_BLDG_BIN_OUT=0 if RECON_BLDG_BIN_OUT==1: for bldg_key in ['GW1_','GW2_','VAK1_','VAK2_']: avgdata_dict=mt.loadObjectBinaryFast('./VTT/'+bldg_key+'avgdata_dict.bin') diffdata_dict=mt.loadObjectBinaryFast('./VTT/'+bldg_key+'diffdata_dict.bin') data_dict=mt.loadObjectBinaryFast('./VTT/'+bldg_key+'data_dict.bin') cmd_str=remove_dot(bldg_key)+'out={\'data_dict\':data_dict}' exec(cmd_str) cmd_str=remove_dot(bldg_key)+'out.update({\'avgdata_dict\':avgdata_dict})' exec(cmd_str) cmd_str=remove_dot(bldg_key)+'out.update({\'diffdata_dict\':diffdata_dict})' exec(cmd_str) cmd_str=remove_dot(bldg_key)+'out.update({\'bldg_key\':remove_dot(bldg_key)})' exec(cmd_str) cmd_str='mt.saveObjectBinaryFast('+remove_dot(bldg_key)+'out'+',\''+PROC_OUT_DIR+remove_dot(bldg_key)+'out.bin\')' exec(cmd_str) print '###############################################################################' print '# Model_Discovery' print '###############################################################################' #bldg_key_set=['GW1','GW2','VAK1','VAK2'] Model_Discovery=1 pwr_key='_POWER_'; bldg_dict={} for bldg_load_key in bldg_key_set: print 'Building for ',bldg_load_key, '....' try: bldg_tag='vtt_'+bldg_load_key bldg_load_out=mt.loadObjectBinaryFast(PROC_OUT_DIR+bldg_load_key+'_out.bin') except: print bldg_load_key+' bin file not found in PROC_OUT_DIR, skip....' pass mt.saveObjectBinaryFast(bldg_load_out['data_dict'],PROC_OUT_DIR+'data_dict.bin') if 'avgdata_dict' in bldg_load_out.keys(): mt.saveObjectBinaryFast(bldg_load_out['avgdata_dict'],PROC_OUT_DIR+'avgdata_dict.bin') if 'diffdata_dict' in bldg_load_out.keys(): mt.saveObjectBinaryFast(bldg_load_out['diffdata_dict'],PROC_OUT_DIR+'diffdata_dict.bin') pname_key= pwr_key bldg_dict.update({bldg_tag:create_bldg_obj(PROC_OUT_DIR,bldg_tag,pname_key)}) bldg_=obj(bldg_dict) #cmd_str='bldg_.'+bldg_tag+'.data_out=obj(bldg_load_out)' #exec(cmd_str) cmd_str='bldg_obj=bldg_.'+bldg_tag exec(cmd_str) anal_out={} if 'avgdata_dict' in bldg_load_out.keys(): anal_out.update({'avg':bn_prob_analysis(bldg_obj,sig_tag_='avg')}) if 'diffdata_dict' in bldg_load_out.keys(): anal_out.update({'diff':bn_prob_analysis(bldg_obj,sig_tag_='diff')}) cmd_str='bldg_.'+bldg_tag+'.anal_out=obj(anal_out)' exec(cmd_str) # Save vtt building object file. mt.saveObjectBinaryFast(bldg_ ,PROC_OUT_DIR+'vtt_bldg_obj.bin') # this is a vtt specific sensor name conversion def convert_vtt_name(id_labels): if isinstance(id_labels,list)==False: id_labels=[id_labels] out_name=[key_label_ for key_label_ in id_labels ] return out_name bldg_.convert_name=convert_vtt_name ####################################################################################### # Analysis For VTT ####################################################################################### # Analysis of BN network result - All result will be saved in fig_dir. BN_ANAL=1 if BN_ANAL==1: # Plotting individual LHs PLOTTING_LH=0 if PLOTTING_LH==1: plotting_bldg_lh(bldg_,attr_class='sensor',num_picks=30) plotting_bldg_lh(bldg_,attr_class='time',num_picks=30) plotting_bldg_lh(bldg_,attr_class='weather',num_picks=30) PLOTTING_BN=1 if PLOTTING_BN==1: plotting_bldg_bn(bldg_) print '**************************** End of Program ****************************' from south.db import db from django.db import models from cms.plugins.picture.models import * class Migration: depends_on = ( ("cms", "0001_initial"), ) def forwards(self, orm): # Adding model 'Picture' db.create_table('picture_picture', ( ('link', models.CharField(_("link"), max_length=255, null=True, blank=True)), ('image', models.ImageField(_("image"), upload_to=CMSPlugin.get_media_path)), ('cmsplugin_ptr', models.OneToOneField(orm['cms.CMSPlugin'])), ('alt', models.CharField(_("alternate text"), max_length=255, null=True, blank=True)), )) db.send_create_signal('picture', ['Picture']) def backwards(self, orm): # Deleting model 'Picture' db.delete_table('picture_picture') models = { 'cms.cmsplugin': { '_stub': True, 'id': ('models.AutoField', [], {'primary_key': 'True'}) }, 'cms.page': { 'Meta': {'ordering': "('tree_id','lft')"}, '_stub': True, 'id': ('models.AutoField', [], {'primary_key': 'True'}) } } # Copyright 2014 Deutsche Telekom AG # 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. import tempest.common.generator.base_generator as base from tempest.openstack.common import log as logging LOG = logging.getLogger(__name__) class ValidTestGenerator(base.BasicGeneratorSet): @base.generator_type("string") @base.simple_generator def generate_valid_string(self, schema): size = schema.get("minLength", 1) # TODO(dkr mko): handle format and pattern return "x" * size @base.generator_type("integer") @base.simple_generator def generate_valid_integer(self, schema): # TODO(dkr mko): handle multipleOf if "minimum" in schema: minimum = schema["minimum"] if "exclusiveMinimum" not in schema: return minimum else: return minimum + 1 if "maximum" in schema: maximum = schema["maximum"] if "exclusiveMaximum" not in schema: return maximum else: return maximum - 1 return 0 @base.generator_type("object") @base.simple_generator def generate_valid_object(self, schema): obj = {} for k, v in schema["properties"].iteritems(): obj[k] = self.generate_valid(v) return obj def generate(self, schema): schema_type = schema["type"] if isinstance(schema_type, list): if "integer" in schema_type: schema_type = "integer" else: raise Exception("non-integer list types not supported") result = [] if schema_type not in self.types_dict: raise TypeError("generator (%s) doesn't support type: %s" % (self.__class__.__name__, schema_type)) for generator in self.types_dict[schema_type]: ret = generator(schema) if ret is not None: if isinstance(ret, list): result.extend(ret) elif isinstance(ret, tuple): result.append(ret) else: raise Exception("generator (%s) returns invalid result: %s" % (generator, ret)) return result def generate_valid(self, schema): return self.generate(schema)[0][1] __version__ = '0.1.2' __author__ = 'Juan Batiz-Benet' __email__ = 'juan@benet.ai' __doc__ = ''' aws datastore implementation. Tested with: * boto 2.5.2 ''' #TODO: Implement queries using a key index. #TODO: Implement TTL (and key configurations) from boto.s3.key import Key as S3Key from boto.exception import S3ResponseError import datastore.core class S3BucketDatastore(datastore.Datastore): '''Simple aws s3 datastore. Does not support queries. The s3 interface is very similar to datastore's. The only differences are: - values must be strings (SerializerShimDatastore) - keys must be converted into strings Hello World: >>> import datastore.aws >>> from boto.s3.connection import S3Connection >>> >>> s3conn = S3Connection('', '') >>> s3bucket = s3conn.get_bucket('') >>> ds = datastore.aws.S3BucketDatastore(s3bucket) >>> >>> hello = datastore.Key('hello') >>> ds.put(hello, 'world') >>> ds.contains(hello) True >>> ds.get(hello) 'world' >>> ds.delete(hello) >>> ds.get(hello) None ''' def __init__(self, s3bucket): '''Initialize the datastore with given s3 bucket `s3bucket`. Args: s3bucket: An s3 bucket to use. Example:: from boto.s3.connection import S3Connection s3conn = S3Connection('', '') s3bucket = s3conn.get_bucket('') s3ds = S3BucketDatastore(s3bucket) ''' self._s3bucket = s3bucket def _s3key(self, key): '''Return an s3 key for given datastore key.''' k = S3Key(self._s3bucket) k.key = str(key) return k @classmethod def _s3keys_get_contents_as_string_gen(cls, s3keys): '''s3 content retriever generator.''' for s3key in s3keys: yield s3key.get_contents_as_string() def get(self, key): '''Return the object named by key or None if it does not exist. Args: key: Key naming the object to retrieve Returns: object or None ''' try: return self._s3key(key).get_contents_as_string() except S3ResponseError, e: return None def put(self, key, value): '''Stores the object `value` named by `key`. Args: key: Key naming `value` value: the object to store. ''' self._s3key(key).set_contents_from_string(value) def delete(self, key): '''Removes the object named by `key`. Args: key: Key naming the object to remove. ''' self._s3key(key).delete() def query(self, query): '''Returns an iterable of objects matching criteria expressed in `query` Implementations of query will be the largest differentiating factor amongst datastores. All datastores **must** implement query, even using query's worst case scenario, see :ref:class:`Query` for details. Args: query: Query object describing the objects to return. Raturns: iterable cursor with all objects matching criteria ''' allkeys = self._s3bucket.list(prefix=str(query.key).strip('/')) iterable = self._s3keys_get_contents_as_string_gen(allkeys) return query(iterable) # must apply filters, order, etc naively. def contains(self, key): '''Returns whether the object named by `key` exists. Args: key: Key naming the object to check. Returns: boalean whether the object exists ''' return self._s3key(key).exists() import sys import pytest from io import StringIO from django.core.management import call_command from awx.main.management.commands.update_password import UpdatePassword def run_command(name, *args, **options): command_runner = options.pop('command_runner', call_command) stdin_fileobj = options.pop('stdin_fileobj', None) options.setdefault('verbosity', 1) original_stdin = sys.stdin original_stdout = sys.stdout original_stderr = sys.stderr if stdin_fileobj: sys.stdin = stdin_fileobj sys.stdout = StringIO() sys.stderr = StringIO() result = None try: result = command_runner(name, *args, **options) except Exception as e: result = e finally: captured_stdout = sys.stdout.getvalue() captured_stderr = sys.stderr.getvalue() sys.stdin = original_stdin sys.stdout = original_stdout sys.stderr = original_stderr return result, captured_stdout, captured_stderr @pytest.mark.parametrize( "username,password,expected,changed", [ ('admin', 'dingleberry', 'Password updated', True), ('admin', 'admin', 'Password not updated', False), (None, 'foo', 'username required', False), ('admin', None, 'password required', False), ] ) def test_update_password_command(mocker, username, password, expected, changed): with mocker.patch.object(UpdatePassword, 'update_password', return_value=changed): result, stdout, stderr = run_command('update_password', username=username, password=password) if result is None: assert stdout == expected else: assert str(result) == expected #!/usr/bin/env python from flexbe_core import EventState, Logger class OperatorDecisionState(EventState): ''' Implements a state where the operator has to manually choose an outcome. Autonomy Level of all outcomes should be set to Full, because this state is not able to choose an outcome on its own. Only exception is the suggested outcome, which will be returned immediately by default. This state can be used to create alternative execution paths by setting the suggestion to High autonomy instead of Full. -- outcomes string[] A list of all possible outcomes of this state. -- hint string Text displayed to the operator to give instructions how to decide. -- suggestion string The outcome which is suggested. Will be returned if the level of autonomy is high enough. ''' def __init__(self, outcomes, hint=None, suggestion=None): super(OperatorDecisionState, self).__init__(outcomes=outcomes) self._hint = hint self._suggestion = suggestion def execute(self, userdata): if self._suggestion is not None and self._suggestion in self._outcomes: return self._suggestion def on_enter(self, userdata): if self._hint is not None: Logger.loghint(self._hint) #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_compute_router_facts description: - Gather facts for GCP Router short_description: Gather facts for GCP Router version_added: 2.7 author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: filters: description: A list of filter value pairs. Available filters are listed here U(https://cloud.google.com/sdk/gcloud/reference/topic/filters). Each additional filter in the list will act be added as an AND condition (filter1 and filter2) region: description: - Region where the router resides. required: true extends_documentation_fragment: gcp ''' EXAMPLES = ''' - name: a router facts gcp_compute_router_facts: region: us-central1 filters: - name = test_object project: test_project auth_kind: service_account service_account_file: "/tmp/auth.pem" ''' RETURN = ''' items: description: List of items returned: always type: complex contains: id: description: - The unique identifier for the resource. returned: success type: int creation_timestamp: description: - Creation timestamp in RFC3339 text format. returned: success type: str name: description: - Name of the resource. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. returned: success type: str description: description: - An optional description of this resource. returned: success type: str network: description: - A reference to the network to which this router belongs. returned: success type: dict bgp: description: - BGP information specific to this router. returned: success type: complex contains: asn: description: - Local BGP Autonomous System Number (ASN). Must be an RFC6996 private ASN, either 16-bit or 32-bit. The value will be fixed for this router resource. All VPN tunnels that link to this router will have the same local ASN. returned: success type: int advertise_mode: description: - User-specified flag to indicate which mode to use for advertisement. - 'Valid values of this enum field are: DEFAULT, CUSTOM .' returned: success type: str advertised_groups: description: - User-specified list of prefix groups to advertise in custom mode. - This field can only be populated if advertiseMode is CUSTOM and is advertised to all peers of the router. These groups will be advertised in addition to any specified prefixes. Leave this field blank to advertise no custom groups. - 'This enum field has the one valid value: ALL_SUBNETS .' returned: success type: list advertised_ip_ranges: description: - User-specified list of individual IP ranges to advertise in custom mode. This field can only be populated if advertiseMode is CUSTOM and is advertised to all peers of the router. These IP ranges will be advertised in addition to any specified groups. - Leave this field blank to advertise no custom IP ranges. returned: success type: complex contains: range: description: - The IP range to advertise. The value must be a CIDR-formatted string. returned: success type: str description: description: - User-specified description for the IP range. returned: success type: str region: description: - Region where the router resides. returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest import json ################################################################################ # Main ################################################################################ def main(): module = GcpModule( argument_spec=dict( filters=dict(type='list', elements='str'), region=dict(required=True, type='str') ) ) if 'scopes' not in module.params: module.params['scopes'] = ['https://www.googleapis.com/auth/compute'] items = fetch_list(module, collection(module), query_options(module.params['filters'])) if items.get('items'): items = items.get('items') else: items = [] return_value = { 'items': items } module.exit_json(**return_value) def collection(module): return "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/routers".format(**module.params) def fetch_list(module, link, query): auth = GcpSession(module, 'compute') response = auth.get(link, params={'filter': query}) return return_if_object(module, response) def query_options(filters): if not filters: return '' if len(filters) == 1: return filters[0] else: queries = [] for f in filters: # For multiple queries, all queries should have () if f[0] != '(' and f[-1] != ')': queries.append("(%s)" % ''.join(f)) else: queries.append(f) return ' '.join(queries) def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__": main() ## features.py ## ## Copyright (C) 2003-2004 Alexey "Snake" Nezhdanov ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2, 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 General Public License for more details. # $Id: features.py,v 1.25 2009/04/07 07:11:48 snakeru Exp $ """ This module contains variable stuff that is not worth splitting into separate modules. Here is: DISCO client and agents-to-DISCO and browse-to-DISCO emulators. IBR and password manager. jabber:iq:privacy methods All these methods takes 'disp' first argument that should be already connected (and in most cases already authorised) dispatcher instance. """ from protocol import * REGISTER_DATA_RECEIVED='REGISTER DATA RECEIVED' ### DISCO ### http://jabber.org/protocol/disco ### JEP-0030 #################### ### Browse ### jabber:iq:browse ### JEP-0030 ################################### ### Agents ### jabber:iq:agents ### JEP-0030 ################################### def _discover(disp,ns,jid,node=None,fb2b=0,fb2a=1): """ Try to obtain info from the remote object. If remote object doesn't support disco fall back to browse (if fb2b is true) and if it doesnt support browse (or fb2b is not true) fall back to agents protocol (if gb2a is true). Returns obtained info. Used internally. """ iq=Iq(to=jid,typ='get',queryNS=ns) if node: iq.setQuerynode(node) rep=disp.SendAndWaitForResponse(iq) if fb2b and not isResultNode(rep): rep=disp.SendAndWaitForResponse(Iq(to=jid,typ='get',queryNS=NS_BROWSE)) # Fallback to browse if fb2a and not isResultNode(rep): rep=disp.SendAndWaitForResponse(Iq(to=jid,typ='get',queryNS=NS_AGENTS)) # Fallback to agents if isResultNode(rep): return [n for n in rep.getQueryPayload() if isinstance(n, Node)] return [] def discoverItems(disp,jid,node=None): """ Query remote object about any items that it contains. Return items list. """ """ According to JEP-0030: query MAY have node attribute item: MUST HAVE jid attribute and MAY HAVE name, node, action attributes. action attribute of item can be either of remove or update value.""" ret=[] for i in _discover(disp,NS_DISCO_ITEMS,jid,node): if i.getName()=='agent' and i.getTag('name'): i.setAttr('name',i.getTagData('name')) ret.append(i.attrs) return ret def discoverInfo(disp,jid,node=None): """ Query remote object about info that it publishes. Returns identities and features lists.""" """ According to JEP-0030: query MAY have node attribute identity: MUST HAVE category and name attributes and MAY HAVE type attribute. feature: MUST HAVE var attribute""" identities , features = [] , [] for i in _discover(disp,NS_DISCO_INFO,jid,node): if i.getName()=='identity': identities.append(i.attrs) elif i.getName()=='feature': features.append(i.getAttr('var')) elif i.getName()=='agent': if i.getTag('name'): i.setAttr('name',i.getTagData('name')) if i.getTag('description'): i.setAttr('name',i.getTagData('description')) identities.append(i.attrs) if i.getTag('groupchat'): features.append(NS_GROUPCHAT) if i.getTag('register'): features.append(NS_REGISTER) if i.getTag('search'): features.append(NS_SEARCH) return identities , features ### Registration ### jabber:iq:register ### JEP-0077 ########################### def getRegInfo(disp,host,info={},sync=True): """ Gets registration form from remote host. You can pre-fill the info dictionary. F.e. if you are requesting info on registering user joey than specify info as {'username':'joey'}. See JEP-0077 for details. 'disp' must be connected dispatcher instance.""" iq=Iq('get',NS_REGISTER,to=host) for i in info.keys(): iq.setTagData(i,info[i]) if sync: resp=disp.SendAndWaitForResponse(iq) _ReceivedRegInfo(disp.Dispatcher,resp, host) return resp else: disp.SendAndCallForResponse(iq,_ReceivedRegInfo, {'agent': host}) def _ReceivedRegInfo(con, resp, agent): iq=Iq('get',NS_REGISTER,to=agent) if not isResultNode(resp): return df=resp.getTag('query',namespace=NS_REGISTER).getTag('x',namespace=NS_DATA) if df: con.Event(NS_REGISTER,REGISTER_DATA_RECEIVED,(agent, DataForm(node=df))) return df=DataForm(typ='form') for i in resp.getQueryPayload(): if type(i)<>type(iq): pass elif i.getName()=='instructions': df.addInstructions(i.getData()) else: df.setField(i.getName()).setValue(i.getData()) con.Event(NS_REGISTER,REGISTER_DATA_RECEIVED,(agent, df)) def register(disp,host,info): """ Perform registration on remote server with provided info. disp must be connected dispatcher instance. Returns true or false depending on registration result. If registration fails you can get additional info from the dispatcher's owner attributes lastErrNode, lastErr and lastErrCode. """ iq=Iq('set',NS_REGISTER,to=host) if type(info)<>type({}): info=info.asDict() for i in info.keys(): iq.setTag('query').setTagData(i,info[i]) resp=disp.SendAndWaitForResponse(iq) if isResultNode(resp): return 1 def unregister(disp,host): """ Unregisters with host (permanently removes account). disp must be connected and authorized dispatcher instance. Returns true on success.""" resp=disp.SendAndWaitForResponse(Iq('set',NS_REGISTER,to=host,payload=[Node('remove')])) if isResultNode(resp): return 1 def changePasswordTo(disp,newpassword,host=None): """ Changes password on specified or current (if not specified) server. disp must be connected and authorized dispatcher instance. Returns true on success.""" if not host: host=disp._owner.Server resp=disp.SendAndWaitForResponse(Iq('set',NS_REGISTER,to=host,payload=[Node('username',payload=[disp._owner.Server]),Node('password',payload=[newpassword])])) if isResultNode(resp): return 1 ### Privacy ### jabber:iq:privacy ### draft-ietf-xmpp-im-19 #################### #type=[jid|group|subscription] #action=[allow|deny] def getPrivacyLists(disp): """ Requests privacy lists from connected server. Returns dictionary of existing lists on success.""" try: dict={'lists':[]} resp=disp.SendAndWaitForResponse(Iq('get',NS_PRIVACY)) if not isResultNode(resp): return for list in resp.getQueryPayload(): if list.getName()=='list': dict['lists'].append(list.getAttr('name')) else: dict[list.getName()]=list.getAttr('name') return dict except: pass def getPrivacyList(disp,listname): """ Requests specific privacy list listname. Returns list of XML nodes (rules) taken from the server responce.""" try: resp=disp.SendAndWaitForResponse(Iq('get',NS_PRIVACY,payload=[Node('list',{'name':listname})])) if isResultNode(resp): return resp.getQueryPayload()[0] except: pass def setActivePrivacyList(disp,listname=None,typ='active'): """ Switches privacy list 'listname' to specified type. By default the type is 'active'. Returns true on success.""" if listname: attrs={'name':listname} else: attrs={} resp=disp.SendAndWaitForResponse(Iq('set',NS_PRIVACY,payload=[Node(typ,attrs)])) if isResultNode(resp): return 1 def setDefaultPrivacyList(disp,listname=None): """ Sets the default privacy list as 'listname'. Returns true on success.""" return setActivePrivacyList(disp,listname,'default') def setPrivacyList(disp,list): """ Set the ruleset. 'list' should be the simpleXML node formatted according to RFC 3921 (XMPP-IM) (I.e. Node('list',{'name':listname},payload=[...]) ) Returns true on success.""" resp=disp.SendAndWaitForResponse(Iq('set',NS_PRIVACY,payload=[list])) if isResultNode(resp): return 1 def delPrivacyList(disp,listname): """ Deletes privacy list 'listname'. Returns true on success.""" resp=disp.SendAndWaitForResponse(Iq('set',NS_PRIVACY,payload=[Node('list',{'name':listname})])) if isResultNode(resp): return 1 # encoding: utf-8 from south.db import db from django.db import models from south.v2 import SchemaMigration from pybb.compat import get_image_field_full_name, get_user_model_path, get_user_frozen_models from pybb.defaults import PYBB_INITIAL_CUSTOM_USER_MIGRATION AUTH_USER = get_user_model_path() AUTH_USER_COLUMN = AUTH_USER.split('.')[-1].lower() if PYBB_INITIAL_CUSTOM_USER_MIGRATION: # Runs custom user migrations (if there are) before # running pybb migrations DEPENDS_ON_CUSTOM_USER_MIGRATION = ( (AUTH_USER.split('.')[0], PYBB_INITIAL_CUSTOM_USER_MIGRATION), ) else: DEPENDS_ON_CUSTOM_USER_MIGRATION = () class Migration(SchemaMigration): depends_on = DEPENDS_ON_CUSTOM_USER_MIGRATION def forwards(self, orm): # Adding model 'Post' db.create_table('pybb_post', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('body', self.gf('django.db.models.fields.TextField')()), ('body_html', self.gf('django.db.models.fields.TextField')()), ('body_text', self.gf('django.db.models.fields.TextField')()), ('topic', self.gf('django.db.models.fields.related.ForeignKey')(related_name='posts', to=orm['pybb.Topic'])), ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='posts', to=orm[AUTH_USER])), ('created', self.gf('django.db.models.fields.DateTimeField')(db_index=True, blank=True)), ('updated', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)), ('user_ip', self.gf('django.db.models.fields.IPAddressField')(default='0.0.0.0', max_length=15, blank=True)), ('markup', self.gf('django.db.models.fields.CharField')(max_length=15)), )) db.send_create_signal('pybb', ['Post']) # Adding model 'Category' db.create_table('pybb_category', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=80)), ('position', self.gf('django.db.models.fields.IntegerField')(default=0, blank=True)), )) db.send_create_signal('pybb', ['Category']) # Adding model 'Forum' db.create_table('pybb_forum', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('category', self.gf('django.db.models.fields.related.ForeignKey')(related_name='forums', to=orm['pybb.Category'])), ('name', self.gf('django.db.models.fields.CharField')(max_length=80)), ('position', self.gf('django.db.models.fields.IntegerField')(default=0, blank=True)), ('description', self.gf('django.db.models.fields.TextField')(blank=True)), ('updated', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)), ('post_count', self.gf('django.db.models.fields.IntegerField')(default=0, blank=True)), ('topic_count', self.gf('django.db.models.fields.IntegerField')(default=0, blank=True)), )) db.send_create_signal('pybb', ['Forum']) # Adding model 'Profile' db.create_table('pybb_profile', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('signature', self.gf('django.db.models.fields.TextField')(max_length=1024, blank=True)), ('signature_html', self.gf('django.db.models.fields.TextField')(max_length=1054, blank=True)), ('time_zone', self.gf('django.db.models.fields.FloatField')(default=3.0)), ('language', self.gf('django.db.models.fields.CharField')(default='en-us', max_length=10, blank=True)), ('show_signatures', self.gf('django.db.models.fields.BooleanField')(default=True)), ('post_count', self.gf('django.db.models.fields.IntegerField')(default=0, blank=True)), ('avatar', self.gf(get_image_field_full_name())(max_length=100, null=True, blank=True)), ('user', self.gf('annoying.fields.AutoOneToOneField')(related_name='pybb_profile', unique=True, to=orm[AUTH_USER])), ('markup', self.gf('django.db.models.fields.CharField')(max_length=15)), ('ban_status', self.gf('django.db.models.fields.SmallIntegerField')(default=0)), ('ban_till', self.gf('django.db.models.fields.DateTimeField')(default=None, null=True, blank=True)), )) db.send_create_signal('pybb', ['Profile']) # Adding model 'Attachment' db.create_table('pybb_attachment', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('post', self.gf('django.db.models.fields.related.ForeignKey')(related_name='attachments', to=orm['pybb.Post'])), ('size', self.gf('django.db.models.fields.IntegerField')()), ('hash', self.gf('django.db.models.fields.CharField')(blank=True, default='', max_length=40, db_index=True)), ('content_type', self.gf('django.db.models.fields.CharField')(max_length=255)), ('name', self.gf('django.db.models.fields.TextField')()), ('path', self.gf('django.db.models.fields.CharField')(max_length=255)), )) db.send_create_signal('pybb', ['Attachment']) # Adding model 'ReadTracking' db.create_table('pybb_readtracking', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[AUTH_USER])), ('topics', self.gf('django.db.models.fields.TextField')(null=True)), ('last_read', self.gf('django.db.models.fields.DateTimeField')(null=True)), )) db.send_create_signal('pybb', ['ReadTracking']) # Adding model 'Topic' db.create_table('pybb_topic', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('forum', self.gf('django.db.models.fields.related.ForeignKey')(related_name='topics', to=orm['pybb.Forum'])), ('name', self.gf('django.db.models.fields.CharField')(max_length=255)), ('created', self.gf('django.db.models.fields.DateTimeField')(null=True)), ('updated', self.gf('django.db.models.fields.DateTimeField')(null=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[AUTH_USER])), ('views', self.gf('django.db.models.fields.IntegerField')(default=0, blank=True)), ('sticky', self.gf('django.db.models.fields.BooleanField')(default=False)), ('closed', self.gf('django.db.models.fields.BooleanField')(default=False)), ('post_count', self.gf('django.db.models.fields.IntegerField')(default=0, blank=True)), )) db.send_create_signal('pybb', ['Topic']) # Adding M2M table for field subscribers on 'Topic' db.create_table('pybb_topic_subscribers', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('topic', models.ForeignKey(orm['pybb.topic'], null=False)), (AUTH_USER_COLUMN, models.ForeignKey(orm[AUTH_USER], null=False)) )) db.create_unique('pybb_topic_subscribers', ['topic_id', '%s_id' % AUTH_USER_COLUMN]) # Adding M2M table for field moderators on 'Forum' db.create_table('pybb_forum_moderators', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('forum', models.ForeignKey(orm['pybb.forum'], null=False)), (AUTH_USER_COLUMN, models.ForeignKey(orm[AUTH_USER], null=False)) )) db.create_unique('pybb_forum_moderators', ['forum_id', '%s_id' % AUTH_USER_COLUMN]) def backwards(self, orm): # Deleting model 'Post' db.delete_table('pybb_post') # Deleting model 'Category' db.delete_table('pybb_category') # Deleting model 'Forum' db.delete_table('pybb_forum') # Deleting model 'Profile' db.delete_table('pybb_profile') # Deleting model 'Attachment' db.delete_table('pybb_attachment') # Deleting model 'ReadTracking' db.delete_table('pybb_readtracking') # Deleting model 'Topic' db.delete_table('pybb_topic') # Dropping ManyToManyField 'Topic.subscribers' db.delete_table('pybb_topic_subscribers') # Dropping ManyToManyField 'Forum.moderators' db.delete_table('pybb_forum_moderators') models = { 'auth.group': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'unique': 'True'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)"}, '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'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", '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'}) }, 'pybb.attachment': { 'content_type': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'hash': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '40', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.TextField', [], {}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'post': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'attachments'", 'to': "orm['pybb.Post']"}), 'size': ('django.db.models.fields.IntegerField', [], {}) }, 'pybb.category': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}), 'position': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}) }, 'pybb.forum': { 'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'forums'", 'to': "orm['pybb.Category']"}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderators': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['%s']"% AUTH_USER, 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}), 'position': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}), 'post_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}), 'topic_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'pybb.post': { 'body': ('django.db.models.fields.TextField', [], {}), 'body_html': ('django.db.models.fields.TextField', [], {}), 'body_text': ('django.db.models.fields.TextField', [], {}), 'created': ('django.db.models.fields.DateTimeField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'markup': ('django.db.models.fields.CharField', [], {'default': "'bbcode'", 'max_length': '15'}), 'topic': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'posts'", 'to': "orm['pybb.Topic']"}), 'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'posts'", 'to': "orm['%s']"% AUTH_USER}), 'user_ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15', 'blank': 'True'}) }, 'pybb.profile': { 'avatar': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'ban_status': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'ban_till': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '10', 'blank': 'True'}), 'markup': ('django.db.models.fields.CharField', [], {'default': "'bbcode'", 'max_length': '15'}), 'post_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}), 'show_signatures': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'signature': ('django.db.models.fields.TextField', [], {'max_length': '1024', 'blank': 'True'}), 'signature_html': ('django.db.models.fields.TextField', [], {'max_length': '1054', 'blank': 'True'}), 'time_zone': ('django.db.models.fields.FloatField', [], {'default': '3.0'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['%s']"% AUTH_USER, 'related_name': "'pybb_profile'", 'unique': 'True'}) }, 'pybb.readtracking': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_read': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'topics': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'unique': 'True', 'to': "orm['%s']"% AUTH_USER}) }, 'pybb.topic': { 'closed': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'topics'", 'to': "orm['pybb.Forum']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'post_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}), 'sticky': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'subscribers': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['%s']"% AUTH_USER, 'blank': 'True'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'blank': 'True', 'null': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']"% AUTH_USER}), 'views': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}) } } models.update(get_user_frozen_models(AUTH_USER)) complete_apps = ['pybb'] # pgn.py rel. 1.1 17-sep-2004 # # Demonstration of the parsing module, implementing a pgn parser. # # The aim of this parser is not to support database application, # but to create automagically a pgn annotated reading the log console file # of a lecture of ICC (Internet Chess Club), saved by Blitzin. # Of course you can modify the Abstract Syntax Tree to your purpose. # # Copyright 2004, by Alberto Santini http://www.albertosantini.it/chess/ # from pyparsing import alphanums, nums, quotedString from pyparsing import Combine, Forward, Group, Literal, oneOf, OneOrMore, Optional, Suppress, ZeroOrMore, White, Word from pyparsing import ParseException # # define pgn grammar # tag = Suppress("[") + Word(alphanums) + Combine(quotedString) + Suppress("]") comment = Suppress("{") + Word(alphanums + " ") + Suppress("}") dot = Literal(".") piece = oneOf("K Q B N R") file_coord = oneOf("a b c d e f g h") rank_coord = oneOf("1 2 3 4 5 6 7 8") capture = oneOf("x :") promote = Literal("=") castle_queenside = Literal("O-O-O") | Literal("0-0-0") | Literal("o-o-o") castle_kingside = Literal("O-O") | Literal("0-0") | Literal("o-o") move_number = Optional(comment) + Word(nums) + dot m1 = file_coord + rank_coord # pawn move e.g. d4 m2 = file_coord + capture + file_coord + rank_coord # pawn capture move e.g. dxe5 m3 = file_coord + "8" + promote + piece # pawn promotion e.g. e8=Q m4 = piece + file_coord + rank_coord # piece move e.g. Be6 m5 = piece + file_coord + file_coord + rank_coord # piece move e.g. Nbd2 m6 = piece + rank_coord + file_coord + rank_coord # piece move e.g. R4a7 m7 = piece + capture + file_coord + rank_coord # piece capture move e.g. Bxh7 m8 = castle_queenside | castle_kingside # castling e.g. o-o check = oneOf("+ ++") mate = Literal("#") annotation = Word("!?", max=2) nag = " $" + Word(nums) decoration = check | mate | annotation | nag variant = Forward() half_move = Combine((m3 | m1 | m2 | m4 | m5 | m6 | m7 | m8) + Optional(decoration)) \ + Optional(comment) +Optional(variant) move = Suppress(move_number) + half_move + Optional(half_move) variant << "(" + OneOrMore(move) + ")" # grouping the plies (half-moves) for each move: useful to group annotations, variants... # suggested by Paul McGuire :) move = Group(Suppress(move_number) + half_move + Optional(half_move)) variant << Group("(" + OneOrMore(move) + ")") game_terminator = oneOf("1-0 0-1 1/2-1/2 *") pgnGrammar = Suppress(ZeroOrMore(tag)) + ZeroOrMore(move) + Suppress(game_terminator) def parsePGN( pgn, bnf=pgnGrammar, fn=None ): try: return bnf.parseString( pgn ) except ParseException, err: print err.line print " "*(err.column-1) + "^" print err if __name__ == "__main__": # input string pgn = """ [Event "ICC 5 0 u"] [Site "Internet Chess Club"] [Date "2004.01.25"] [Round "-"] [White "guest920"] [Black "IceBox"] [Result "0-1"] [ICCResult "White checkmated"] [BlackElo "1498"] [Opening "French defense"] [ECO "C00"] [NIC "FR.01"] [Time "04:44:56"] [TimeControl "300+0"] 1. e4 e6 2. Nf3 d5 $2 3. exd5 (3. e5 g6 4. h4) exd5 4. Qe2+ Qe7 5. Qxe7+ Bxe7 6. d3 Nf6 7. Be3 Bg4 8. Nbd2 c5 9. h3 Be6 10. O-O-O Nc6 11. g4 Bd6 12. g5 Nd7 13. Rg1 d4 14. g6 fxg6 15. Bg5 Rf8 16. a3 Bd5 17. Re1+ Nde5 18. Nxe5 Nxe5 19. Bf4 Rf5 20. Bxe5 Rxe5 21. Rg5 Rxe1# {Black wins} 0-1 """ # parse input string tokens = parsePGN(pgn, pgnGrammar) print "tokens = ", tokens #!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages try: readme_text = file('README.rst', 'rb').read() except IOError,e: readme_text = '' setup(name = "gsconfig", version = "1.0.0", description = "GeoServer REST Configuration", long_description = readme_text, keywords = "GeoServer REST Configuration", license = "MIT", url = "https://github.com/boundlessgeo/gsconfig", author = "David Winslow, Sebastian Benthall", author_email = "dwinslow@opengeo.org", install_requires = [ 'httplib2>=0.7.4', 'gisdata==0.5.4' ], package_dir = {'':'src'}, packages = find_packages('src'), test_suite = "test.catalogtests", classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: GIS', ] ) # This file is part of OpenHatch. # Copyright (C) 2009 OpenHatch, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from south.db import db from django.db import models from mysite.profile.models import * class Migration: def forwards(self, orm): # Adding field 'PortfolioEntry.is_published' db.add_column('profile_portfolioentry', 'is_published', orm['profile.portfolioentry:is_published']) # Changing field 'DataImportAttempt.date_created' # (to signature: django.db.models.fields.DateTimeField(default=datetime.datetime(2009, 10, 29, 21, 52, 38, 701735))) db.alter_column('profile_dataimportattempt', 'date_created', orm['profile.dataimportattempt:date_created']) # Changing field 'PortfolioEntry.date_created' # (to signature: django.db.models.fields.DateTimeField(default=datetime.datetime(2009, 10, 29, 21, 52, 39, 254639))) db.alter_column('profile_portfolioentry', 'date_created', orm['profile.portfolioentry:date_created']) # Changing field 'Citation.date_created' # (to signature: django.db.models.fields.DateTimeField(default=datetime.datetime(2009, 10, 29, 21, 52, 39, 313650))) db.alter_column('profile_citation', 'date_created', orm['profile.citation:date_created']) def backwards(self, orm): # Deleting field 'PortfolioEntry.is_published' db.delete_column('profile_portfolioentry', 'is_published') # Changing field 'DataImportAttempt.date_created' # (to signature: django.db.models.fields.DateTimeField(default=datetime.datetime(2009, 10, 29, 15, 40, 11, 889042))) db.alter_column('profile_dataimportattempt', 'date_created', orm['profile.dataimportattempt:date_created']) # Changing field 'PortfolioEntry.date_created' # (to signature: django.db.models.fields.DateTimeField(default=datetime.datetime(2009, 10, 29, 15, 40, 11, 412825))) db.alter_column('profile_portfolioentry', 'date_created', orm['profile.portfolioentry:date_created']) # Changing field 'Citation.date_created' # (to signature: django.db.models.fields.DateTimeField(default=datetime.datetime(2009, 10, 29, 15, 40, 11, 832834))) db.alter_column('profile_citation', 'date_created', orm['profile.citation:date_created']) models = { 'auth.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']", 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)"}, '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': { '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']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), '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']", 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", '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'}) }, 'profile.citation': { 'contributor_role': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'data_import_attempt': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.DataImportAttempt']", 'null': 'True'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2009, 10, 29, 21, 52, 40, 124865)'}), 'distinct_months': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'first_commit_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'languages': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'old_summary': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True'}), 'portfolio_entry': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.PortfolioEntry']"}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'}) }, 'profile.dataimportattempt': { 'completed': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2009, 10, 29, 21, 52, 40, 225441)'}), 'failed': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Person']"}), 'query': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '2'}) }, 'profile.link_person_tag': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Person']"}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Tag']"}) }, 'profile.link_project_tag': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['search.Project']"}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Tag']"}) }, 'profile.link_projectexp_tag': { 'Meta': {'unique_together': "[('tag', 'project_exp', 'source')]"}, 'favorite': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'project_exp': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.ProjectExp']"}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Tag']"}) }, 'profile.link_sf_proj_dude_fm': { 'Meta': {'unique_together': "[('person', 'project')]"}, 'date_collected': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_admin': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.SourceForgePerson']"}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.SourceForgeProject']"}) }, 'profile.person': { 'gotten_name_from_ohloh': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'interested_in_working_on': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024'}), 'last_polled': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(1970, 1, 1, 0, 0)'}), 'photo': ('django.db.models.fields.files.ImageField', [], {'default': "''", 'max_length': '100'}), 'show_email': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'profile.portfolioentry': { 'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2009, 10, 29, 21, 52, 39, 522055)'}), 'experience_description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Person']"}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['search.Project']"}), 'project_description': ('django.db.models.fields.TextField', [], {}) }, 'profile.projectexp': { 'data_import_attempt': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.DataImportAttempt']", 'null': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'man_months': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}), 'modified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Person']", 'null': 'True'}), 'person_role': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'primary_language': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['search.Project']"}), 'should_show_this': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'}) }, 'profile.sourceforgeperson': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'profile.sourceforgeproject': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'unixname': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'profile.tag': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tag_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.TagType']"}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'profile.tagtype': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'prefix': ('django.db.models.fields.CharField', [], {'max_length': '20'}) }, 'search.project': { 'date_icon_was_fetched_from_ohloh': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True'}), 'icon': ('django.db.models.fields.files.ImageField', [], {'default': 'None', 'max_length': '100', 'null': 'True'}), 'icon_smaller_for_badge': ('django.db.models.fields.files.ImageField', [], {'default': 'None', 'max_length': '100', 'null': 'True'}), 'icon_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}) } } complete_apps = ['profile'] # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013,2014,2015,2016 Contributor # # 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. """Load all exporters""" import os import logging from traceback import format_exc __all__ = [] _thisdir = os.path.dirname(os.path.realpath(__file__)) for f in os.listdir(_thisdir): full = os.path.join(_thisdir, f) if os.path.isfile(full) and f.endswith('.py') and f != '__init__.py': moduleshort = f[:-3] modulename = __name__ + '.' + moduleshort try: mymodule = __import__(modulename) except Exception as e: # pragma: no cover logger = logging.getLogger(__name__) logger.info("Error importing %s: %s", modulename, format_exc()) continue """ This module defines common methods used in simulator specific build modules @author Tom Close """ ########################################################################## # # Copyright 2011 Okinawa Institute of Science and Technology (OIST), Okinawa # ########################################################################## from __future__ import absolute_import from builtins import object from future.utils import PY3 import platform import os import subprocess as sp import time from itertools import chain from copy import deepcopy import shutil from os.path import join from jinja2 import Environment, FileSystemLoader, StrictUndefined from future.utils import with_metaclass from abc import ABCMeta, abstractmethod import sympy from nineml import units from nineml.exceptions import NineMLNameError, NineMLSerializationError from pype9.exceptions import ( Pype9BuildError, Pype9CommandNotFoundError, Pype9RuntimeError) from ..cells.with_synapses import read import pype9.annotations from pype9.annotations import PYPE9_NS, BUILD_PROPS from os.path import expanduser import re from nineml.serialization import url_re import sysconfig from pype9 import __version__ from pype9.utils.paths import remove_ignore_missing from pype9.utils.logging import logger BASE_BUILD_DIR = os.path.join( expanduser("~"), '.pype9', 'build', 'v{}'.format(__version__), 'python{}'.format(sysconfig.get_config_var('py_version'))) class BaseCodeGenerator(with_metaclass(ABCMeta, object)): """ Parameters ---------- base_dir : str | None The base directory for the generated code. If None a directory will be created in user's home directory. """ BUILD_MODE_OPTIONS = ['lazy', # Build iff source has been updated 'force', # Build always 'require', # Don't build, requires pre-built 'build_only', # Only build 'generate_only', # Only generate source files 'purge' # Remove all configure files and rebuild ] _PARAMS_DIR = 'params' _SRC_DIR = 'src' _INSTL_DIR = 'install' _CMPL_DIR = 'compile' # Ignored for NEURON but used for NEST _BUILT_COMP_CLASS = 'built_component_class.xml' # Python functions and annotations to be made available in the templates _globals = dict( [('len', len), ('zip', zip), ('enumerate', enumerate), ('range', range), ('next', next), ('chain', chain), ('sorted', sorted), ('hash', hash), ('deepcopy', deepcopy), ('units', units), ('hasattr', hasattr), ('set', set), ('list', list), ('None', None), ('sympy', sympy)] + [(n, v) for n, v in list(pype9.annotations.__dict__.items()) if n != '__builtins__']) # Derived classes should provide mapping from 9ml dimensions to default # units DEFAULT_UNITS = {} def __init__(self, base_dir=None, **kwargs): # @UnusedVariable if base_dir is None: base_dir = BASE_BUILD_DIR self._base_dir = os.path.join( base_dir, self.SIMULATOR_NAME + self.SIMULATOR_VERSION) def __repr__(self): return "{}CodeGenerator(base_dir='{}')".format( self.SIMULATOR_NAME.capitalize(), self.base_dir) def __eq__(self, other): try: return (self.SIMULATOR_NAME == other.SIMULATOR_NAME and self.base_dir == other.base_dir) except AttributeError: return False def __ne__(self, other): return not self.__eq__(other) @property def base_dir(self): return self._base_dir @abstractmethod def generate_source_files(self, dynamics, src_dir, name, **kwargs): """ Generates the source files for the relevant simulator """ pass def configure_build_files(self, name, src_dir, compile_dir, install_dir, **kwargs): """ Configures the build files before compiling """ pass @abstractmethod def compile_source_files(self, compile_dir, name): pass def generate(self, component_class, build_mode='lazy', url=None, **kwargs): """ Generates and builds the required simulator-specific files for a given NineML cell class Parameters ---------- component_class : nineml.Dynamics 9ML Dynamics object name : str Name of the generated cell class install_dir : str Path to the directory where the NMODL files will be generated and compiled build_mode : str Available build options: lazy - only build if files are modified force - always generate and build purge - remove all config files, generate and rebuild require - require built binaries are present build_only - build and then quit generate_only - generate src and then quit recompile - don't generate src but compile build_version : str A suffix appended to the cell build name to distinguish it from other code generated from the component class url : str The URL where the component class is stored (used to form the build path) kwargs : dict A dictionary of (potentially simulator- specific) template arguments """ # Save original working directory to reinstate it afterwards (just to # be polite) name = component_class.name orig_dir = os.getcwd() if url is None: url = component_class.url # Calculate compile directory path within build directory src_dir = self.get_source_dir(name, url) compile_dir = self.get_compile_dir(name, url) install_dir = self.get_install_dir(name, url) # Path of the build component class built_comp_class_pth = os.path.join(src_dir, self._BUILT_COMP_CLASS) # Determine whether the installation needs rebuilding or whether there # is an existing library module to use. if build_mode == 'purge': remove_ignore_missing(src_dir) remove_ignore_missing(install_dir) remove_ignore_missing(compile_dir) generate_source = compile_source = True elif build_mode in ('force', 'build_only'): # Force build generate_source = compile_source = True elif build_mode == 'require': # Just check that prebuild is present generate_source = compile_source = False elif build_mode == 'generate_only': # Only generate generate_source = True compile_source = False elif build_mode == 'lazy': # Generate if source has been modified compile_source = True if not os.path.exists(built_comp_class_pth): generate_source = True else: try: built_component_class = read(built_comp_class_pth)[name] if built_component_class.equals(component_class, annotations_ns=[PYPE9_NS]): generate_source = False logger.info("Found existing source in '{}' directory, " "code generation skipped (set 'build_mode'" " argument to 'force' or 'build_only' to " "enforce regeneration)".format(src_dir)) else: generate_source = True logger.info("Found existing source in '{}' directory, " "but the component classes differ so " "regenerating sources".format(src_dir)) except (NineMLNameError, NineMLSerializationError): generate_source = True logger.info("Found existing source in '{}' directory, " "but could not find '{}' component class so " "regenerating sources".format(name, src_dir)) # Check if required directories are present depending on build_mode elif build_mode == 'require': if not os.path.exists(install_dir): raise Pype9BuildError( "Prebuilt installation directory '{}' is not " "present, and is required for 'require' build option" .format(install_dir)) else: raise Pype9BuildError( "Unrecognised build option '{}', must be one of ('{}')" .format(build_mode, "', '".join(self.BUILD_MODE_OPTIONS))) # Generate source files from NineML code if generate_source: self.clean_src_dir(src_dir, name) self.generate_source_files( name=name, component_class=component_class, src_dir=src_dir, compile_dir=compile_dir, install_dir=install_dir, **kwargs) component_class.write(built_comp_class_pth, preserve_order=True, version=2.0) if compile_source: # Clean existing compile & install directories from previous builds if generate_source: self.clean_compile_dir(compile_dir, purge=(build_mode == 'purge')) self.configure_build_files( name=name, src_dir=src_dir, compile_dir=compile_dir, install_dir=install_dir, **kwargs) self.clean_install_dir(install_dir) self.compile_source_files(compile_dir, name) # Switch back to original dir os.chdir(orig_dir) # Cache any dimension maps that were calculated during the generation # process return install_dir def get_build_dir(self, name, url): return os.path.join(self.base_dir, self.url_build_path(url), name) def get_source_dir(self, name, url): return os.path.abspath(os.path.join( self.get_build_dir(name, url), self._SRC_DIR)) def get_compile_dir(self, name, url): return os.path.abspath(os.path.join( self.get_build_dir(name, url), self._CMPL_DIR)) def get_install_dir(self, name, url): return os.path.abspath(os.path.join( self.get_build_dir(name, url), self._INSTL_DIR)) def clean_src_dir(self, src_dir, component_name): # @UnusedVariable # Clean existing src directories from previous builds. shutil.rmtree(src_dir, ignore_errors=True) try: os.makedirs(src_dir) except OSError as e: raise Pype9BuildError( "Could not create source directory ({}), please check the " "required permissions or specify a different \"build dir" "base\" ('build_dir_base'):\n{}".format(src_dir, e)) def clean_compile_dir(self, compile_dir, purge=False): # @UnusedVariable # Clean existing compile & install directories from previous builds shutil.rmtree(compile_dir, ignore_errors=True) try: os.makedirs(compile_dir) except OSError as e: raise Pype9BuildError( "Could not create compile directory ({}), please check the " "required permissions or specify a different \"build dir" "base\" ('build_dir_base'):\n{}".format(compile_dir, e)) def clean_install_dir(self, install_dir): # Clean existing compile & install directories from previous builds shutil.rmtree(install_dir, ignore_errors=True) try: os.makedirs(install_dir) except OSError as e: raise Pype9BuildError( "Could not create install directory ({}), please check the " "required permissions or specify a different \"build dir" "base\" ('build_dir_base'):\n{}".format(install_dir, e)) def render_to_file(self, template, args, filename, directory, switches={}, post_hoc_subs={}): # Initialise the template loader to include the flag directories template_paths = [ self.BASE_TMPL_PATH, os.path.join(self.BASE_TMPL_PATH, 'includes')] # Add include paths for various switches (e.g. solver type) for name, value in list(switches.items()): if value is not None: template_paths.append(os.path.join(self.BASE_TMPL_PATH, 'includes', name, value)) # Add default path for template includes template_paths.append( os.path.join(self.BASE_TMPL_PATH, 'includes', 'default')) # Initialise the Jinja2 environment jinja_env = Environment(loader=FileSystemLoader(template_paths), trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined) # Add some globals used by the template code jinja_env.globals.update(**self._globals) # Actually render the contents contents = jinja_env.get_template(template).render(**args) for old, new in list(post_hoc_subs.items()): contents = contents.replace(old, new) # Write the contents to file with open(os.path.join(directory, filename), 'w') as f: f.write(contents) def path_to_utility(self, utility_name, env_var='', **kwargs): # @UnusedVariable @IgnorePep8 """ Returns the full path to an executable by searching the "PATH" environment variable Parameters ---------- utility_name : str Name of executable to search the execution path env_var : str Name of a environment variable to lookup first before searching path default : str | None The default value to assign to the path if it cannot be found. Returns ------- utility_path : str Full path to executable """ if kwargs and list(kwargs) != ['default']: raise Pype9RuntimeError( "Should only provide 'default' as kwarg to path_to_utility " "provided ({})".format(kwargs)) try: utility_path = os.environ[env_var] except KeyError: if platform.system() == 'Windows': utility_name += '.exe' # Get the system path system_path = os.environ['PATH'].split(os.pathsep) # Append NEST_INSTALL_DIR/NRNHOME if present system_path.extend(self.simulator_specific_paths()) # Check the system path for the command utility_path = None for dr in system_path: path = join(dr, utility_name) if os.path.exists(path): utility_path = path break if not utility_path: try: utility_path = kwargs['default'] except KeyError: raise Pype9CommandNotFoundError( "Could not find executable '{}' on the system path " "'{}'".format(utility_name, ':'.join(system_path))) else: if not os.path.exists(utility_path): raise Pype9CommandNotFoundError( "Could not find executable '{}' at path '{}' provided by " "'{}' environment variable" .format(utility_name, env_var)) return utility_path def simulator_specific_paths(self): """ To be overridden by derived classes if required. """ return [] def transform_for_build(self, name, component_class, **kwargs): # @UnusedVariable @IgnorePep8 """ Copies and transforms the component class to match the format of the simulator (overridden in derived class) Parameters ---------- name : str The name of the transformed component class component_class : nineml.Dynamics The component class to be transformed """ # --------------------------------------------------------------------- # Clone original component class and properties # --------------------------------------------------------------------- component_class = component_class.clone() component_class.name = name self._set_build_props(component_class, **kwargs) return component_class def _set_build_props(self, component_class, **build_props): """ Sets the build properties in the component class annotations Parameters ---------- component_class : Dynamics | MultiDynamics The build component class build_props : dict(str, str) Build properties to save into the annotations of the build component class """ for k, v in list(build_props.items()) + [ ('version', pype9.__version__)]: component_class.annotations.set((BUILD_PROPS, PYPE9_NS), k, v) def run_command(self, cmd, fail_msg=None, **kwargs): env = os.environ.copy() try: process = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, env=env, **kwargs) stdout, stderr = process.communicate() if PY3: stdout = str(stdout.decode('utf-8')) stderr = str(stderr.decode('utf-8')) logger.debug("'{}' stdout:\n{}".format(cmd, stdout)) logger.debug("'{}' stderr:\n{}".format(cmd, stderr)) except sp.CalledProcessError as e: if fail_msg is None: raise else: msg = fail_msg.format(e) raise Pype9BuildError(msg) return stdout, stderr @classmethod def get_mod_time(cls, url): if url is None: mod_time = time.ctime(0) # Return the earliest date if no url else: mod_time = time.ctime(os.path.getmtime(url)) return mod_time @classmethod def url_build_path(cls, url): if url is None: path = 'generated' else: if url_re.match(url) is not None: path = os.path.join( 'url', re.match(r'(:?\w+://)?([\.\/\w]+).*', url).group(1)) else: path = os.path.join('file', os.path.realpath(url)[1:]) return path def load_libraries(self, name, url, **kwargs): """ To be overridden by derived classes to allow the model to be loaded from compiled external libraries """ pass #!/usr/bin/env python # # Copyright 2010 Google Inc. 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 Google Inc. 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. """Tests Google Test's exception catching behavior. This script invokes googletest-catch-exceptions-test_ and googletest-catch-exceptions-ex-test_ (programs written with Google Test) and verifies their output. """ import gtest_test_utils # Constants. FLAG_PREFIX = '--gtest_' LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0' FILTER_FLAG = FLAG_PREFIX + 'filter' # Path to the googletest-catch-exceptions-ex-test_ binary, compiled with # exceptions enabled. EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath( 'googletest-catch-exceptions-ex-test_') # Path to the googletest-catch-exceptions-test_ binary, compiled with # exceptions disabled. EXE_PATH = gtest_test_utils.GetTestExecutablePath( 'googletest-catch-exceptions-no-ex-test_') environ = gtest_test_utils.environ SetEnvVar = gtest_test_utils.SetEnvVar # Tests in this file run a Google-Test-based test program and expect it # to terminate prematurely. Therefore they are incompatible with # the premature-exit-file protocol by design. Unset the # premature-exit filepath to prevent Google Test from creating # the file. SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None) TEST_LIST = gtest_test_utils.Subprocess( [EXE_PATH, LIST_TESTS_FLAG], env=environ).output SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST if SUPPORTS_SEH_EXCEPTIONS: BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output EX_BINARY_OUTPUT = gtest_test_utils.Subprocess( [EX_EXE_PATH], env=environ).output # The tests. if SUPPORTS_SEH_EXCEPTIONS: # pylint:disable-msg=C6302 class CatchSehExceptionsTest(gtest_test_utils.TestCase): """Tests exception-catching behavior.""" def TestSehExceptions(self, test_output): self.assert_('SEH exception with code 0x2a thrown ' 'in the test fixture\'s constructor' in test_output) self.assert_('SEH exception with code 0x2a thrown ' 'in the test fixture\'s destructor' in test_output) self.assert_('SEH exception with code 0x2a thrown in SetUpTestSuite()' in test_output) self.assert_('SEH exception with code 0x2a thrown in TearDownTestSuite()' in test_output) self.assert_('SEH exception with code 0x2a thrown in SetUp()' in test_output) self.assert_('SEH exception with code 0x2a thrown in TearDown()' in test_output) self.assert_('SEH exception with code 0x2a thrown in the test body' in test_output) def testCatchesSehExceptionsWithCxxExceptionsEnabled(self): self.TestSehExceptions(EX_BINARY_OUTPUT) def testCatchesSehExceptionsWithCxxExceptionsDisabled(self): self.TestSehExceptions(BINARY_OUTPUT) class CatchCxxExceptionsTest(gtest_test_utils.TestCase): """Tests C++ exception-catching behavior. Tests in this test case verify that: * C++ exceptions are caught and logged as C++ (not SEH) exceptions * Exception thrown affect the remainder of the test work flow in the expected manner. """ def testCatchesCxxExceptionsInFixtureConstructor(self): self.assertTrue( 'C++ exception with description ' '"Standard C++ exception" thrown ' 'in the test fixture\'s constructor' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assert_('unexpected' not in EX_BINARY_OUTPUT, 'This failure belongs in this test only if ' '"CxxExceptionInConstructorTest" (no quotes) ' 'appears on the same line as words "called unexpectedly"') if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in EX_BINARY_OUTPUT): def testCatchesCxxExceptionsInFixtureDestructor(self): self.assertTrue( 'C++ exception with description ' '"Standard C++ exception" thrown ' 'in the test fixture\'s destructor' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInDestructorTest::TearDownTestSuite() ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInSetUpTestCase(self): self.assertTrue( 'C++ exception with description "Standard C++ exception"' ' thrown in SetUpTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInConstructorTest::TearDownTestSuite() ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInSetUpTestSuiteTest constructor ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInSetUpTestSuiteTest destructor ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInSetUpTestSuiteTest::SetUp() ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInSetUpTestSuiteTest::TearDown() ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInSetUpTestSuiteTest test body ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInTearDownTestCase(self): self.assertTrue( 'C++ exception with description "Standard C++ exception"' ' thrown in TearDownTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInSetUp(self): self.assertTrue( 'C++ exception with description "Standard C++ exception"' ' thrown in SetUp()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInSetUpTest::TearDownTestSuite() ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInSetUpTest destructor ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInSetUpTest::TearDown() ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assert_('unexpected' not in EX_BINARY_OUTPUT, 'This failure belongs in this test only if ' '"CxxExceptionInSetUpTest" (no quotes) ' 'appears on the same line as words "called unexpectedly"') def testCatchesCxxExceptionsInTearDown(self): self.assertTrue( 'C++ exception with description "Standard C++ exception"' ' thrown in TearDown()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInTearDownTest::TearDownTestSuite() ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInTearDownTest destructor ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInTestBody(self): self.assertTrue( 'C++ exception with description "Standard C++ exception"' ' thrown in the test body' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInTestBodyTest::TearDownTestSuite() ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInTestBodyTest destructor ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assertTrue( 'CxxExceptionInTestBodyTest::TearDown() ' 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesNonStdCxxExceptions(self): self.assertTrue( 'Unknown C++ exception thrown in the test body' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testUnhandledCxxExceptionsAbortTheProgram(self): # Filters out SEH exception tests on Windows. Unhandled SEH exceptions # cause tests to show pop-up windows there. FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*' # By default, Google Test doesn't catch the exceptions. uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess( [EX_EXE_PATH, NO_CATCH_EXCEPTIONS_FLAG, FITLER_OUT_SEH_TESTS_FLAG], env=environ).output self.assert_('Unhandled C++ exception terminating the program' in uncaught_exceptions_ex_binary_output) self.assert_('unexpected' not in uncaught_exceptions_ex_binary_output) if __name__ == '__main__': gtest_test_utils.Main() SPCM_ERROR_ORIGIN_MASK = (-2147483648) SPCM_ERROR_ORIGIN_LOCAL = 0x00000000 SPCM_ERROR_ORIGIN_REMOTE = (-2147483648) ERR_OK = 0x0000 ERR_INIT = 0x0001 ERR_NR = 0x0002 ERR_TYP = 0x0003 ERR_FNCNOTSUPPORTED = 0x0004 ERR_BRDREMAP = 0x0005 ERR_KERNELVERSION = 0x0006 ERR_HWDRVVERSION = 0x0007 ERR_ADRRANGE = 0x0008 ERR_INVALIDHANDLE = 0x0009 ERR_BOARDNOTFOUND = 0x000A ERR_BOARDINUSE = 0x000B ERR_EXPHW64BITADR = 0x000C ERR_FWVERSION = 0x000D ERR_LASTERR = 0x0010 ERR_ABORT = 0x0020 ERR_BOARDLOCKED = 0x0030 ERR_DEVICE_MAPPING = 0x0032 ERR_NETWORKSETUP = 0x0040 ERR_NETWORKTRANSFER = 0x0041 ERR_FWPOWERCYCLE = 0x0042 ERR_NETWORKTIMEOUT = 0x0043 ERR_BUFFERSIZE = 0x0044 ERR_RESTRICTEDACCESS = 0x0045 ERR_INVALIDPARAM = 0x0046 ERR_REG = 0x0100 ERR_VALUE = 0x0101 ERR_FEATURE = 0x0102 ERR_SEQUENCE = 0x0103 ERR_READABORT = 0x0104 ERR_NOACCESS = 0x0105 ERR_POWERDOWN = 0x0106 ERR_TIMEOUT = 0x0107 ERR_CALLTYPE = 0x0108 ERR_EXCEEDSINT32 = 0x0109 ERR_NOWRITEALLOWED = 0x010A ERR_SETUP = 0x010B ERR_CLOCKNOTLOCKED = 0x010C ERR_MEMINIT = 0x010D ERR_POWERSUPPLY = 0x010E ERR_ADCCOMMUNICATION = 0x010F ERR_CHANNEL = 0x0110 ERR_NOTIFYSIZE = 0x0111 ERR_RUNNING = 0x0120 ERR_ADJUST = 0x0130 ERR_PRETRIGGERLEN = 0x0140 ERR_DIRMISMATCH = 0x0141 ERR_POSTEXCDSEGMENT = 0x0142 ERR_SEGMENTINMEM = 0x0143 ERR_MULTIPLEPW = 0x0144 ERR_NOCHANNELPWOR = 0x0145 ERR_ANDORMASKOVRLAP = 0x0146 ERR_ANDMASKEDGE = 0x0147 ERR_ORMASKLEVEL = 0x0148 ERR_EDGEPERMOD = 0x0149 ERR_DOLEVELMINDIFF = 0x014A ERR_STARHUBENABLE = 0x014B ERR_PATPWSMALLEDGE = 0x014C ERR_NOPCI = 0x0200 ERR_PCIVERSION = 0x0201 ERR_PCINOBOARDS = 0x0202 ERR_PCICHECKSUM = 0x0203 ERR_DMALOCKED = 0x0204 ERR_MEMALLOC = 0x0205 ERR_EEPROMLOAD = 0x0206 ERR_CARDNOSUPPORT = 0x0207 ERR_CONFIGACCESS = 0x0208 ERR_FIFOBUFOVERRUN = 0x0300 ERR_FIFOHWOVERRUN = 0x0301 ERR_FIFOFINISHED = 0x0302 ERR_FIFOSETUP = 0x0309 ERR_TIMESTAMP_SYNC = 0x0310 ERR_STARHUB = 0x0320 ERR_INTERNAL_ERROR = 0xFFFF # Copyright 2014 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. from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class ToughMemoryMultiTabPage(page_module.Page): def __init__(self, url, page_set): super(ToughMemoryMultiTabPage, self).__init__(url=url, page_set=page_set) self.credentials_path = 'data/credentials.json' self.user_agent_type = 'mobile' self.archive_data_file = 'data/key_mobile_sites.json' class ToughMemoryMultiTabPageSet(page_set_module.PageSet): """ Mobile sites for exercising multi-tab memory issues """ def __init__(self): super(ToughMemoryMultiTabPageSet, self).__init__( credentials_path='data/credentials.json', user_agent_type='mobile', archive_data_file='data/key_mobile_sites.json') urls_list = [ 'https://www.google.com/#hl=en&q=barack+obama', 'http://theverge.com', 'http://techcrunch.com' ] for url in urls_list: self.AddPage(ToughMemoryMultiTabPage(url, self)) import antlr3 import testbase import unittest class t010lexer(testbase.ANTLRTest): def setUp(self): self.compileGrammar() def lexerClass(self, base): class TLexer(base): def emitErrorMessage(self, msg): # report errors to /dev/null pass def reportError(self, re): # no error recovery yet, just crash! raise re return TLexer def testValid(self): stream = antlr3.StringStream('foobar _Ab98 \n A12sdf') lexer = self.getLexer(stream) token = lexer.nextToken() assert token.type == self.lexerModule.IDENTIFIER assert token.start == 0, token.start assert token.stop == 5, token.stop assert token.text == 'foobar', token.text token = lexer.nextToken() assert token.type == self.lexerModule.WS assert token.start == 6, token.start assert token.stop == 6, token.stop assert token.text == ' ', token.text token = lexer.nextToken() assert token.type == self.lexerModule.IDENTIFIER assert token.start == 7, token.start assert token.stop == 11, token.stop assert token.text == '_Ab98', token.text token = lexer.nextToken() assert token.type == self.lexerModule.WS assert token.start == 12, token.start assert token.stop == 14, token.stop assert token.text == ' \n ', token.text token = lexer.nextToken() assert token.type == self.lexerModule.IDENTIFIER assert token.start == 15, token.start assert token.stop == 20, token.stop assert token.text == 'A12sdf', token.text token = lexer.nextToken() assert token.type == self.lexerModule.EOF def testMalformedInput(self): stream = antlr3.StringStream('a-b') lexer = self.getLexer(stream) lexer.nextToken() try: token = lexer.nextToken() raise AssertionError, token except antlr3.NoViableAltException, exc: assert exc.unexpectedType == '-', repr(exc.unexpectedType) assert exc.charPositionInLine == 1, repr(exc.charPositionInLine) assert exc.line == 1, repr(exc.line) if __name__ == '__main__': unittest.main() #!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Ruggero Marchei # (c) 2015, Brian Coca # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see import os import stat import fnmatch import time import re DOCUMENTATION = ''' --- module: find author: Brian Coca (based on Ruggero Marchei's Tidy) version_added: "2.0" short_description: return a list of files based on specific criteria requirements: [] description: - Return a list files based on specific criteria. Multiple criteria are AND'd together. options: age: required: false default: null description: - Select files whose age is equal to or greater than the specified time. Use a negative age to find files equal to or less than the specified time. You can choose seconds, minutes, hours, days, or weeks by specifying the first letter of any of those words (e.g., "1w"). patterns: required: false default: '*' description: - One or more (shell or regex) patterns, which type is controled by C(use_regex) option. - The patterns restrict the list of files to be returned to those whose basenames match at least one of the patterns specified. Multiple patterns can be specified using a list. aliases: ['pattern'] contains: required: false default: null description: - One or more re patterns which should be matched against the file content paths: required: true aliases: [ "name", "path" ] description: - List of paths to the file or directory to search. All paths must be fully qualified. file_type: required: false description: - Type of file to select choices: [ "file", "directory" ] default: "file" recurse: required: false default: "no" choices: [ "yes", "no" ] description: - If target is a directory, recursively descend into the directory looking for files. size: required: false default: null description: - Select files whose size is equal to or greater than the specified size. Use a negative size to find files equal to or less than the specified size. Unqualified values are in bytes, but b, k, m, g, and t can be appended to specify bytes, kilobytes, megabytes, gigabytes, and terabytes, respectively. Size is not evaluated for directories. age_stamp: required: false default: "mtime" choices: [ "atime", "mtime", "ctime" ] description: - Choose the file property against which we compare age. Default is mtime. hidden: required: false default: "False" choices: [ True, False ] description: - Set this to true to include hidden files, otherwise they'll be ignored. follow: required: false default: "False" choices: [ True, False ] description: - Set this to true to follow symlinks in path for systems with python 2.6+ get_checksum: required: false default: "False" choices: [ True, False ] description: - Set this to true to retrieve a file's sha1 checksum use_regex: required: false default: "False" choices: [ True, False ] description: - If false the patterns are file globs (shell) if true they are python regexes ''' EXAMPLES = ''' # Recursively find /tmp files older than 2 days - find: paths="/tmp" age="2d" recurse=yes # Recursively find /tmp files older than 4 weeks and equal or greater than 1 megabyte - find: paths="/tmp" age="4w" size="1m" recurse=yes # Recursively find /var/tmp files with last access time greater than 3600 seconds - find: paths="/var/tmp" age="3600" age_stamp=atime recurse=yes # find /var/log files equal or greater than 10 megabytes ending with .old or .log.gz - find: paths="/var/tmp" patterns="*.old,*.log.gz" size="10m" # find /var/log files equal or greater than 10 megabytes ending with .old or .log.gz via regex - find: paths="/var/tmp" patterns="^.*?\.(?:old|log\.gz)$" size="10m" use_regex=True ''' RETURN = ''' files: description: all matches found with the specified criteria (see stat module for full output of each dictionary) returned: success type: list of dictionaries sample: [ { path="/var/tmp/test1", mode=0644, ..., checksum=16fac7be61a6e4591a33ef4b729c5c3302307523 }, { path="/var/tmp/test2", ... }, ] matched: description: number of matches returned: success type: string sample: 14 examined: description: number of filesystem objects looked at returned: success type: string sample: 34 ''' def pfilter(f, patterns=None, use_regex=False): '''filter using glob patterns''' if patterns is None: return True if use_regex: for p in patterns: r = re.compile(p) if r.match(f): return True else: for p in patterns: if fnmatch.fnmatch(f, p): return True return False def agefilter(st, now, age, timestamp): '''filter files older than age''' if age is None or \ (age >= 0 and now - st.__getattribute__("st_%s" % timestamp) >= abs(age)) or \ (age < 0 and now - st.__getattribute__("st_%s" % timestamp) <= abs(age)): return True return False def sizefilter(st, size): '''filter files greater than size''' if size is None or \ (size >= 0 and st.st_size >= abs(size)) or \ (size < 0 and st.st_size <= abs(size)): return True return False def contentfilter(fsname, pattern): '''filter files which contain the given expression''' if pattern is None: return True try: f = open(fsname) prog = re.compile(pattern) for line in f: if prog.match (line): f.close() return True f.close() except: pass return False def statinfo(st): return { 'mode' : "%04o" % stat.S_IMODE(st.st_mode), 'isdir' : stat.S_ISDIR(st.st_mode), 'ischr' : stat.S_ISCHR(st.st_mode), 'isblk' : stat.S_ISBLK(st.st_mode), 'isreg' : stat.S_ISREG(st.st_mode), 'isfifo' : stat.S_ISFIFO(st.st_mode), 'islnk' : stat.S_ISLNK(st.st_mode), 'issock' : stat.S_ISSOCK(st.st_mode), 'uid' : st.st_uid, 'gid' : st.st_gid, 'size' : st.st_size, 'inode' : st.st_ino, 'dev' : st.st_dev, 'nlink' : st.st_nlink, 'atime' : st.st_atime, 'mtime' : st.st_mtime, 'ctime' : st.st_ctime, 'wusr' : bool(st.st_mode & stat.S_IWUSR), 'rusr' : bool(st.st_mode & stat.S_IRUSR), 'xusr' : bool(st.st_mode & stat.S_IXUSR), 'wgrp' : bool(st.st_mode & stat.S_IWGRP), 'rgrp' : bool(st.st_mode & stat.S_IRGRP), 'xgrp' : bool(st.st_mode & stat.S_IXGRP), 'woth' : bool(st.st_mode & stat.S_IWOTH), 'roth' : bool(st.st_mode & stat.S_IROTH), 'xoth' : bool(st.st_mode & stat.S_IXOTH), 'isuid' : bool(st.st_mode & stat.S_ISUID), 'isgid' : bool(st.st_mode & stat.S_ISGID), } def main(): module = AnsibleModule( argument_spec = dict( paths = dict(required=True, aliases=['name','path'], type='list'), patterns = dict(default=['*'], type='list', aliases=['pattern']), contains = dict(default=None, type='str'), file_type = dict(default="file", choices=['file', 'directory'], type='str'), age = dict(default=None, type='str'), age_stamp = dict(default="mtime", choices=['atime','mtime','ctime'], type='str'), size = dict(default=None, type='str'), recurse = dict(default='no', type='bool'), hidden = dict(default="False", type='bool'), follow = dict(default="False", type='bool'), get_checksum = dict(default="False", type='bool'), use_regex = dict(default="False", type='bool'), ), supports_check_mode=True, ) params = module.params filelist = [] if params['age'] is None: age = None else: # convert age to seconds: m = re.match("^(-?\d+)(s|m|h|d|w)?$", params['age'].lower()) seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800} if m: age = int(m.group(1)) * seconds_per_unit.get(m.group(2), 1) else: module.fail_json(age=params['age'], msg="failed to process age") if params['size'] is None: size = None else: # convert size to bytes: m = re.match("^(-?\d+)(b|k|m|g|t)?$", params['size'].lower()) bytes_per_unit = {"b": 1, "k": 1024, "m": 1024**2, "g": 1024**3, "t": 1024**4} if m: size = int(m.group(1)) * bytes_per_unit.get(m.group(2), 1) else: module.fail_json(size=params['size'], msg="failed to process size") now = time.time() msg = '' looked = 0 for npath in params['paths']: if os.path.isdir(npath): ''' ignore followlinks for python version < 2.6 ''' for root,dirs,files in (sys.version_info < (2,6,0) and os.walk(npath)) or \ os.walk( npath, followlinks=params['follow']): looked = looked + len(files) + len(dirs) for fsobj in (files + dirs): fsname=os.path.normpath(os.path.join(root, fsobj)) if os.path.basename(fsname).startswith('.') and not params['hidden']: continue try: st = os.stat(fsname) except: msg+="%s was skipped as it does not seem to be a valid file or it cannot be accessed\n" % fsname continue r = {'path': fsname} if stat.S_ISDIR(st.st_mode) and params['file_type'] == 'directory': if pfilter(fsobj, params['patterns'], params['use_regex']) and agefilter(st, now, age, params['age_stamp']): r.update(statinfo(st)) filelist.append(r) elif stat.S_ISREG(st.st_mode) and params['file_type'] == 'file': if pfilter(fsobj, params['patterns'], params['use_regex']) and \ agefilter(st, now, age, params['age_stamp']) and \ sizefilter(st, size) and \ contentfilter(fsname, params['contains']): r.update(statinfo(st)) if params['get_checksum']: r['checksum'] = module.sha1(fsname) filelist.append(r) if not params['recurse']: break else: msg+="%s was skipped as it does not seem to be a valid directory or it cannot be accessed\n" % npath matched = len(filelist) module.exit_json(files=filelist, changed=False, msg=msg, matched=matched, examined=looked) # import module snippets from ansible.module_utils.basic import * main() # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. # ============================================================================== """Example of debugging TensorFlow runtime errors using tfdbg.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import sys import numpy as np import tensorflow as tf from tensorflow.python import debug as tf_debug def main(_): sess = tf.Session() # Construct the TensorFlow network. ph_float = tf.placeholder(tf.float32, name="ph_float") x = tf.transpose(ph_float, name="x") v = tf.Variable(np.array([[-2.0], [-3.0], [6.0]], dtype=np.float32), name="v") m = tf.constant( np.array([[0.0, 1.0, 2.0], [-4.0, -1.0, 0.0]]), dtype=tf.float32, name="m") y = tf.matmul(m, x, name="y") z = tf.matmul(m, v, name="z") if FLAGS.debug: sess = tf_debug.LocalCLIDebugWrapperSession(sess, ui_type=FLAGS.ui_type) if FLAGS.error == "shape_mismatch": print(sess.run(y, feed_dict={ph_float: np.array([[0.0], [1.0], [2.0]])})) elif FLAGS.error == "uninitialized_variable": print(sess.run(z)) elif FLAGS.error == "no_error": print(sess.run(y, feed_dict={ph_float: np.array([[0.0, 1.0, 2.0]])})) else: raise ValueError("Unrecognized error type: " + FLAGS.error) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.register("type", "bool", lambda v: v.lower() == "true") parser.add_argument( "--error", type=str, default="shape_mismatch", help="""\ Type of the error to generate (shape_mismatch | uninitialized_variable | no_error).\ """) parser.add_argument( "--ui_type", type=str, default="curses", help="Command-line user interface type (curses | readline)") parser.add_argument( "--debug", type="bool", nargs="?", const=True, default=False, help="Use debugger to track down bad values during training") FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) # This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # Copyright (c) 2015 Peter Sprygada, # Copyright (c) 2017 Red Hat Inc. # # 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. # # 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 HOLDER 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. # from ansible.module_utils._text import to_text from ansible.module_utils.basic import env_fallback, return_values from ansible.module_utils.network_common import to_list, ComplexList from ansible.module_utils.connection import exec_command _DEVICE_CONFIGS = {} iosxr_provider_spec = { 'host': dict(), 'port': dict(type='int'), 'username': dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])), 'password': dict(fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD']), no_log=True), 'ssh_keyfile': dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'), 'timeout': dict(type='int'), } iosxr_argument_spec = { 'provider': dict(type='dict', options=iosxr_provider_spec) } iosxr_argument_spec.update(iosxr_provider_spec) def get_argspec(): return iosxr_argument_spec def check_args(module, warnings): for key in iosxr_argument_spec: if module._name == 'iosxr_user': if key not in ['password', 'provider'] and module.params[key]: warnings.append('argument %s has been deprecated and will be in a future version' % key) else: if key != 'provider' and module.params[key]: warnings.append('argument %s has been deprecated and will be removed in a future version' % key) def get_config(module, flags=[]): cmd = 'show running-config ' cmd += ' '.join(flags) cmd = cmd.strip() try: return _DEVICE_CONFIGS[cmd] except KeyError: rc, out, err = exec_command(module, cmd) if rc != 0: module.fail_json(msg='unable to retrieve current config', stderr=to_text(err, errors='surrogate_or_strict')) cfg = to_text(out, errors='surrogate_or_strict').strip() _DEVICE_CONFIGS[cmd] = cfg return cfg def to_commands(module, commands): spec = { 'command': dict(key=True), 'prompt': dict(), 'answer': dict() } transform = ComplexList(spec, module) return transform(commands) def run_commands(module, commands, check_rc=True): responses = list() commands = to_commands(module, to_list(commands)) for cmd in to_list(commands): cmd = module.jsonify(cmd) rc, out, err = exec_command(module, cmd) if check_rc and rc != 0: module.fail_json(msg=to_text(err, errors='surrogate_or_strict'), rc=rc) responses.append(to_text(out, errors='surrogate_or_strict')) return responses def load_config(module, commands, warnings, commit=False, replace=False, comment=None, admin=False): cmd = 'configure terminal' if admin: cmd = 'admin ' + cmd rc, out, err = exec_command(module, cmd) if rc != 0: module.fail_json(msg='unable to enter configuration mode', err=to_text(err, errors='surrogate_or_strict')) failed = False for command in to_list(commands): if command == 'end': continue rc, out, err = exec_command(module, command) if rc != 0: failed = True break if failed: exec_command(module, 'abort') module.fail_json(msg=to_text(err, errors='surrogate_or_strict'), commands=commands, rc=rc) rc, diff, err = exec_command(module, 'show commit changes diff') if rc != 0: # If we failed, maybe we are in an old version so # we run show configuration instead rc, diff, err = exec_command(module, 'show configuration') if module._diff: warnings.append('device platform does not support config diff') if commit: cmd = 'commit' if comment: cmd += ' comment {0}'.format(comment) else: cmd = 'abort' rc, out, err = exec_command(module, cmd) if rc != 0: exec_command(module, 'abort') module.fail_json(msg=err, commands=commands, rc=rc) return to_text(diff, errors='surrogate_or_strict') # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # # $Id: CmpImg.py 36560 2004-07-18 06:16:08Z tim_one $ # # Tix Demostration Program # # This sample program is structured in such a way so that it can be # executed from the Tix demo program "tixwidgets.py": it must have a # procedure called "RunSample". It should also have the "if" statment # at the end of this file so that it can be run as a standalone # program. # This file demonstrates the use of the compound images: it uses compound # images to display a text string together with a pixmap inside # buttons # import Tix network_pixmap = """/* XPM */ static char * netw_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 7 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #404040", "+ c blue", "@ c red", /* pixels */ " ", " .............. ", " .XXXXXXXXXXXX. ", " .XooooooooooO. ", " .Xo.......XoO. ", " .Xo.++++o+XoO. ", " .Xo.++++o+XoO. ", " .Xo.++oo++XoO. ", " .Xo.++++++XoO. ", " .Xo.+o++++XoO. ", " .Xo.++++++XoO. ", " .Xo.XXXXXXXoO. ", " .XooooooooooO. ", " .Xo@ooo....oO. ", " .............. .XooooooooooO. ", " .XXXXXXXXXXXX. .XooooooooooO. ", " .XooooooooooO. .OOOOOOOOOOOO. ", " .Xo.......XoO. .............. ", " .Xo.++++o+XoO. @ ", " .Xo.++++o+XoO. @ ", " .Xo.++oo++XoO. @ ", " .Xo.++++++XoO. @ ", " .Xo.+o++++XoO. @ ", " .Xo.++++++XoO. ..... ", " .Xo.XXXXXXXoO. .XXX. ", " .XooooooooooO.@@@@@@.X O. ", " .Xo@ooo....oO. .OOO. ", " .XooooooooooO. ..... ", " .XooooooooooO. ", " .OOOOOOOOOOOO. ", " .............. ", " "}; """ hard_disk_pixmap = """/* XPM */ static char * drivea_xpm[] = { /* width height ncolors chars_per_pixel */ "32 32 5 1", /* colors */ " s None c None", ". c #000000000000", "X c white", "o c #c000c000c000", "O c #800080008000", /* pixels */ " ", " ", " ", " ", " ", " ", " ", " ", " ", " .......................... ", " .XXXXXXXXXXXXXXXXXXXXXXXo. ", " .XooooooooooooooooooooooO. ", " .Xooooooooooooooooo..oooO. ", " .Xooooooooooooooooo..oooO. ", " .XooooooooooooooooooooooO. ", " .Xoooooooo.......oooooooO. ", " .Xoo...................oO. ", " .Xoooooooo.......oooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .XooooooooooooooooooooooO. ", " .oOOOOOOOOOOOOOOOOOOOOOOO. ", " .......................... ", " ", " ", " ", " ", " ", " ", " ", " "}; """ network_bitmap = """ #define netw_width 32 #define netw_height 32 static unsigned char netw_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x8a, 0x51, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x4a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x02, 0x40, 0xfe, 0x7f, 0x52, 0x55, 0x02, 0x40, 0xaa, 0x6a, 0xfa, 0x5f, 0xfe, 0x7f, 0x0a, 0x50, 0xfe, 0x7f, 0x0a, 0x52, 0x80, 0x00, 0x0a, 0x52, 0x80, 0x00, 0x8a, 0x51, 0x80, 0x00, 0x0a, 0x50, 0x80, 0x00, 0x4a, 0x50, 0x80, 0x00, 0x0a, 0x50, 0xe0, 0x03, 0x0a, 0x50, 0x20, 0x02, 0xfa, 0xdf, 0x3f, 0x03, 0x02, 0x40, 0xa0, 0x02, 0x52, 0x55, 0xe0, 0x03, 0xaa, 0x6a, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; """ hard_disk_bitmap = """ #define drivea_width 32 #define drivea_height 32 static unsigned char drivea_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0x1f, 0x08, 0x00, 0x00, 0x18, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0xd5, 0x1d, 0xa8, 0xaa, 0xaa, 0x1b, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a, 0xc8, 0xff, 0xff, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0xf8, 0xff, 0xff, 0x1f, 0xf8, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; """ def RunSample(w): w.img0 = Tix.Image('pixmap', data=network_pixmap) if not w.img0: w.img0 = Tix.Image('bitmap', data=network_bitmap) w.img1 = Tix.Image('pixmap', data=hard_disk_pixmap) if not w.img0: w.img1 = Tix.Image('bitmap', data=hard_disk_bitmap) hdd = Tix.Button(w, padx=4, pady=1, width=120) net = Tix.Button(w, padx=4, pady=1, width=120) # Create the first image: we create a line, then put a string, # a space and a image into this line, from left to right. # The result: we have a one-line image that consists of three # individual items # # The tk.calls should be methods in Tix ... w.hdd_img = Tix.Image('compound', window=hdd) w.hdd_img.tk.call(str(w.hdd_img), 'add', 'line') w.hdd_img.tk.call(str(w.hdd_img), 'add', 'text', '-text', 'Hard Disk', '-underline', '0') w.hdd_img.tk.call(str(w.hdd_img), 'add', 'space', '-width', '7') w.hdd_img.tk.call(str(w.hdd_img), 'add', 'image', '-image', w.img1) # Put this image into the first button # hdd['image'] = w.hdd_img # Next button w.net_img = Tix.Image('compound', window=net) w.net_img.tk.call(str(w.net_img), 'add', 'line') w.net_img.tk.call(str(w.net_img), 'add', 'text', '-text', 'Network', '-underline', '0') w.net_img.tk.call(str(w.net_img), 'add', 'space', '-width', '7') w.net_img.tk.call(str(w.net_img), 'add', 'image', '-image', w.img0) # Put this image into the first button # net['image'] = w.net_img close = Tix.Button(w, pady=1, text='Close', command=lambda w=w: w.destroy()) hdd.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1) net.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1) close.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1) if __name__ == '__main__': root = Tix.Tk() RunSample(root) root.mainloop() # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not 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 __future__ import print_function from pyspark import SparkContext # $example on$ from pyspark.mllib.linalg import Matrices, Vectors from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.stat import Statistics # $example off$ if __name__ == "__main__": sc = SparkContext(appName="HypothesisTestingExample") # $example on$ vec = Vectors.dense(0.1, 0.15, 0.2, 0.3, 0.25) # a vector composed of the frequencies of events # compute the goodness of fit. If a second vector to test against # is not supplied as a parameter, the test runs against a uniform distribution. goodnessOfFitTestResult = Statistics.chiSqTest(vec) # summary of the test including the p-value, degrees of freedom, # test statistic, the method used, and the null hypothesis. print("%s\n" % goodnessOfFitTestResult) mat = Matrices.dense(3, 2, [1.0, 3.0, 5.0, 2.0, 4.0, 6.0]) # a contingency matrix # conduct Pearson's independence test on the input contingency matrix independenceTestResult = Statistics.chiSqTest(mat) # summary of the test including the p-value, degrees of freedom, # test statistic, the method used, and the null hypothesis. print("%s\n" % independenceTestResult) obs = sc.parallelize( [LabeledPoint(1.0, [1.0, 0.0, 3.0]), LabeledPoint(1.0, [1.0, 2.0, 0.0]), LabeledPoint(1.0, [-1.0, 0.0, -0.5])] ) # LabeledPoint(feature, label) # The contingency table is constructed from an RDD of LabeledPoint and used to conduct # the independence test. Returns an array containing the ChiSquaredTestResult for every feature # against the label. featureTestResults = Statistics.chiSqTest(obs) for i, result in enumerate(featureTestResults): print("Column %d:\n%s" % (i + 1, result)) # $example off$ sc.stop() """Middleware for embargoing site and courses. IMPORTANT NOTE: This code WILL NOT WORK if you have a misconfigured proxy server. If you are configuring embargo functionality, or if you are experiencing mysterious problems with embargoing, please check that your reverse proxy is setting any of the well known client IP address headers (ex., HTTP_X_FORWARDED_FOR). This middleware allows you to: * Embargoing courses (access restriction by courses) * Embargoing site (access restriction of the main site) Embargo can restrict by states and whitelist/blacklist (IP Addresses (ie. 10.0.0.0), Networks (ie. 10.0.0.0/24)), or the user profile country. Usage: # Enable the middleware in your settings # To enable Embargo for particular courses, set: FEATURES['EMBARGO'] = True # blocked ip will be redirected to /embargo # To enable the Embargo feature for the whole site, set: FEATURES['SITE_EMBARGOED'] = True # With SITE_EMBARGOED, you can define an external url to redirect with: EMBARGO_SITE_REDIRECT_URL = 'https://www.edx.org/' # if EMBARGO_SITE_REDIRECT_URL is missing, a HttpResponseForbidden is returned. """ from functools import partial import logging import pygeoip from lazy import lazy from django.core.exceptions import MiddlewareNotUsed from django.core.cache import cache from django.conf import settings from django.shortcuts import redirect from django.http import HttpResponseRedirect, HttpResponseForbidden from ipware.ip import get_ip from util.request import course_id_from_url from student.models import unique_id_for_user from embargo.models import EmbargoedCourse, EmbargoedState, IPFilter log = logging.getLogger(__name__) class EmbargoMiddleware(object): """ Middleware for embargoing site and courses This is configured by creating ``EmbargoedCourse``, ``EmbargoedState``, and optionally ``IPFilter`` rows in the database, using the django admin site. """ # Reasons a user might be blocked. # These are used to generate info messages in the logs. REASONS = { "ip_blacklist": u"Restricting IP address {ip_addr} {from_course} because IP is blacklisted.", "ip_country": u"Restricting IP address {ip_addr} {from_course} because IP is from country {ip_country}.", "profile_country": ( u"Restricting user {user_id} {from_course} because " u"the user set the profile country to {profile_country}." ) } def __init__(self): self.site_enabled = settings.FEATURES.get('SITE_EMBARGOED', False) # If embargoing is turned off, make this middleware do nothing if not settings.FEATURES.get('EMBARGO', False) and not self.site_enabled: raise MiddlewareNotUsed() def process_request(self, request): """ Processes embargo requests. """ url = request.path course_id = course_id_from_url(url) course_is_embargoed = EmbargoedCourse.is_embargoed(course_id) # If they're trying to access a course that cares about embargoes if self.site_enabled or course_is_embargoed: # Construct the list of functions that check whether the user is embargoed. # We wrap each of these functions in a decorator that logs the reason the user # was blocked. # Each function should return `True` iff the user is blocked by an embargo. check_functions = [ self._log_embargo_reason(check_func, course_id, course_is_embargoed) for check_func in [ partial(self._is_embargoed_by_ip, get_ip(request)), partial(self._is_embargoed_by_profile_country, request.user) ] ] # Perform each of the checks # If the user fails any of the checks, immediately redirect them # and skip later checks. for check_func in check_functions: if check_func(): return self._embargo_redirect_response # If all the check functions pass, implicitly return None # so that the middleware processor can continue processing # the response. def _is_embargoed_by_ip(self, ip_addr, course_id=u"", course_is_embargoed=False): """ Check whether the user is embargoed based on the IP address. Args: ip_addr (str): The IP address the request originated from. Keyword Args: course_id (unicode): The course the user is trying to access. course_is_embargoed (boolean): Whether the course the user is accessing has been embargoed. Returns: A unicode message if the user is embargoed, otherwise `None` """ # If blacklisted, immediately fail if ip_addr in IPFilter.current().blacklist_ips: return self.REASONS['ip_blacklist'].format( ip_addr=ip_addr, from_course=self._from_course_msg(course_id, course_is_embargoed) ) # If we're white-listed, then allow access if ip_addr in IPFilter.current().whitelist_ips: return None # Retrieve the country code from the IP address # and check it against the list of embargoed countries ip_country = self._country_code_from_ip(ip_addr) if ip_country in self._embargoed_countries: return self.REASONS['ip_country'].format( ip_addr=ip_addr, ip_country=ip_country, from_course=self._from_course_msg(course_id, course_is_embargoed) ) # If none of the other checks caught anything, # implicitly return None to indicate that the user can access the course def _is_embargoed_by_profile_country(self, user, course_id="", course_is_embargoed=False): """ Check whether the user is embargoed based on the country code in the user's profile. Args: user (User): The user attempting to access courseware. Keyword Args: course_id (unicode): The course the user is trying to access. course_is_embargoed (boolean): Whether the course the user is accessing has been embargoed. Returns: A unicode message if the user is embargoed, otherwise `None` """ cache_key = u'user.{user_id}.profile.country'.format(user_id=user.id) profile_country = cache.get(cache_key) if profile_country is None: profile = getattr(user, 'profile', None) if profile is not None and profile.country.code is not None: profile_country = profile.country.code.upper() else: profile_country = "" cache.set(cache_key, profile_country) if profile_country in self._embargoed_countries: return self.REASONS['profile_country'].format( user_id=unique_id_for_user(user), profile_country=profile_country, from_course=self._from_course_msg(course_id, course_is_embargoed) ) else: return None def _country_code_from_ip(self, ip_addr): """ Return the country code associated with an IP address. Handles both IPv4 and IPv6 addresses. Args: ip_addr (str): The IP address to look up. Returns: str: A 2-letter country code. """ if ip_addr.find(':') >= 0: return pygeoip.GeoIP(settings.GEOIPV6_PATH).country_code_by_addr(ip_addr) else: return pygeoip.GeoIP(settings.GEOIP_PATH).country_code_by_addr(ip_addr) @property def _embargo_redirect_response(self): """ The HTTP response to send when the user is blocked from a course. This will either be a redirect to a URL configured in Django settings or a forbidden response. Returns: HTTPResponse """ response = redirect('embargo') # Set the proper response if site is enabled if self.site_enabled: redirect_url = getattr(settings, 'EMBARGO_SITE_REDIRECT_URL', None) response = ( HttpResponseRedirect(redirect_url) if redirect_url else HttpResponseForbidden('Access Denied') ) return response @lazy def _embargoed_countries(self): """ Return the list of 2-letter country codes for embargoed countries. The result is cached within the scope of the response. Returns: list """ return EmbargoedState.current().embargoed_countries_list def _from_course_msg(self, course_id, course_is_embargoed): """ Format a message indicating whether the user was blocked from a specific course. This can be used in info messages, but should not be used in user-facing messages. Args: course_id (unicode): The ID of the course being accessed. course_is_embarged (boolean): Whether the course being accessed is embargoed. Returns: unicode """ return ( u"from course {course_id}".format(course_id=course_id) if course_is_embargoed else u"" ) def _log_embargo_reason(self, check_func, course_id, course_is_embargoed): """ Decorator for embargo check functions that will: * execute the check function * check whether the user is blocked by an embargo, and if so, log the reason * return a boolean indicating whether the user was blocked. Args: check_func (partial): A function that should return unicode reason if the user was blocked, otherwise should return None. This function will be passed `course_id` and `course_is_embarged` kwargs so it can format a detailed reason message. course_id (unicode): The ID of the course the user is trying to access. course_is_embargoed (boolean): Whether the course the user is trying to access is under an embargo. Returns: boolean: True iff the user was blocked by an embargo """ def _inner(): # Perform the check and retrieve the reason string. # The reason will be `None` if the user passes the check and can access the course. # We pass in the course ID and whether the course is embargoed # so that the check function can fill in the "reason" message with more specific details. reason = check_func( course_id=course_id, course_is_embargoed=course_is_embargoed ) # If the reason was `None`, indicate that the user was not blocked. if reason is None: return False # Otherwise, log the reason the user was blocked # and return True. else: msg = u"Embargo: {reason}".format(reason=reason) log.info(msg) return True return _inner # -*- coding: utf-8 -*- """ Admin site configuration for third party authentication """ from django.contrib import admin from config_models.admin import ConfigurationModelAdmin, KeyedConfigurationModelAdmin from .models import OAuth2ProviderConfig, SAMLProviderConfig, SAMLConfiguration, SAMLProviderData, LTIProviderConfig from .tasks import fetch_saml_metadata class OAuth2ProviderConfigAdmin(KeyedConfigurationModelAdmin): """ Django Admin class for OAuth2ProviderConfig """ def get_list_display(self, request): """ Don't show every single field in the admin change list """ return ( 'name', 'enabled', 'backend_name', 'secondary', 'skip_registration_form', 'skip_email_verification', 'change_date', 'changed_by', 'edit_link', ) admin.site.register(OAuth2ProviderConfig, OAuth2ProviderConfigAdmin) class SAMLProviderConfigAdmin(KeyedConfigurationModelAdmin): """ Django Admin class for SAMLProviderConfig """ def get_list_display(self, request): """ Don't show every single field in the admin change list """ return ( 'name', 'enabled', 'backend_name', 'entity_id', 'metadata_source', 'has_data', 'icon_class', 'change_date', 'changed_by', 'edit_link' ) def has_data(self, inst): """ Do we have cached metadata for this SAML provider? """ if not inst.is_active: return None # N/A data = SAMLProviderData.current(inst.entity_id) return bool(data and data.is_valid()) has_data.short_description = u'Metadata Ready' has_data.boolean = True def save_model(self, request, obj, form, change): """ Post save: Queue an asynchronous metadata fetch to update SAMLProviderData. We only want to do this for manual edits done using the admin interface. Note: This only works if the celery worker and the app worker are using the same 'configuration' cache. """ super(SAMLProviderConfigAdmin, self).save_model(request, obj, form, change) fetch_saml_metadata.apply_async((), countdown=2) admin.site.register(SAMLProviderConfig, SAMLProviderConfigAdmin) class SAMLConfigurationAdmin(ConfigurationModelAdmin): """ Django Admin class for SAMLConfiguration """ def get_list_display(self, request): """ Shorten the public/private keys in the change view """ return ( 'change_date', 'changed_by', 'enabled', 'entity_id', 'org_info_str', 'key_summary', ) def key_summary(self, inst): """ Short summary of the key pairs configured """ public_key = inst.get_setting('SP_PUBLIC_CERT') private_key = inst.get_setting('SP_PRIVATE_KEY') if not public_key or not private_key: return u'Key pair incomplete/missing' pub1, pub2 = public_key[0:10], public_key[-10:] priv1, priv2 = private_key[0:10], private_key[-10:] return u'Public: {}…{}
Private: {}…{}'.format(pub1, pub2, priv1, priv2) key_summary.allow_tags = True admin.site.register(SAMLConfiguration, SAMLConfigurationAdmin) class SAMLProviderDataAdmin(admin.ModelAdmin): """ Django Admin class for SAMLProviderData (Read Only) """ list_display = ('entity_id', 'is_valid', 'fetched_at', 'expires_at', 'sso_url') readonly_fields = ('is_valid', ) def get_readonly_fields(self, request, obj=None): if obj: # editing an existing object return self.model._meta.get_all_field_names() # pylint: disable=protected-access return self.readonly_fields admin.site.register(SAMLProviderData, SAMLProviderDataAdmin) class LTIProviderConfigAdmin(KeyedConfigurationModelAdmin): """ Django Admin class for LTIProviderConfig """ exclude = ( 'icon_class', 'secondary', ) def get_list_display(self, request): """ Don't show every single field in the admin change list """ return ( 'name', 'enabled', 'lti_consumer_key', 'lti_max_timestamp_age', 'change_date', 'changed_by', 'edit_link', ) admin.site.register(LTIProviderConfig, LTIProviderConfigAdmin) import unittest, sys, time sys.path.extend(['.','..','../..','py']) import h2o2 as h2o import h2o_cmd, h2o_import as h2i from h2o_test import dump_json, verboseprint, OutputObj class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): h2o.init(1, java_heap_GB=4) @classmethod def tearDownClass(cls): h2o.tear_down_cloud() def test_GBM_basic_regress(self): bucket = 'home-0xdiag-datasets' importFolderPath = 'standard' trainFilename = 'covtype.shuffled.90pct.data' train_key = 'covtype.train.hex' model_key = 'GBMModelKey' timeoutSecs = 1800 csvPathname = importFolderPath + "/" + trainFilename parseResult = h2i.import_parse(bucket=bucket, path=csvPathname, schema='local', hex_key=train_key, timeoutSecs=timeoutSecs) pA = h2o_cmd.ParseObj(parseResult) iA = h2o_cmd.InspectObj(pA.parse_key) parse_key = pA.parse_key numRows = iA.numRows numCols = iA.numCols labelList = iA.labelList labelListUsed = list(labelList) numColsUsed = numCols parameters = { 'validation_frame': train_key, 'ignored_columns': None, 'response_column': 'C55', # 'balance_classes': # 'max_after_balance_size': 'ntrees': 2, 'max_depth': 10, 'min_rows': 3, 'nbins': 40, 'learn_rate': 0.2, # FIX! doesn't like it? # 'loss': 'Bernoulli', # FIX..no variable importance for GBM yet? # 'variable_importance': False, # 'seed': } model_key = 'covtype_gbm.hex' bmResult = h2o.n0.build_model( algo='gbm', model_id=model_key, training_frame=parse_key, parameters=parameters, timeoutSecs=60) bm = OutputObj(bmResult, 'bm') modelResult = h2o.n0.models(key=model_key) model = OutputObj(modelResult['models'][0]['output'], 'model') cmmResult = h2o.n0.compute_model_metrics(model=model_key, frame=parse_key, timeoutSecs=60) cmm = OutputObj(cmmResult, 'cmm') # just check that it's something non-zero # assert cmm.cm['prediction_error']!=0.0 mmResult = h2o.n0.model_metrics(model=model_key, frame=parse_key, timeoutSecs=60) mmResultShort = mmResult['model_metrics'][0] del mmResultShort['frame'] # too much! mm = OutputObj(mmResultShort, 'mm') prResult = h2o.n0.predict(model=model_key, frame=parse_key, timeoutSecs=60) pr = OutputObj(prResult['model_metrics'][0]['predictions'], 'pr') # too slow! # h2o_cmd.runStoreView() if __name__ == '__main__': h2o.unit_main() from __future__ import division import argparse import atexit import os import numpy as np import pycuda.driver as cuda import neurokernel.LPU.utils.simpleio as sio import retina.retina as ret import retina.geometry.hexagon as hx import retina.classmapper as cls_map from retina.screen.map.mapimpl import AlbersProjectionMap def gen_input(config): cuda.init() ctx = cuda.Device(0).make_context() atexit.register(ctx.pop) suffix = config['General']['file_suffix'] eye_num = config['General']['eye_num'] eulerangles = config['Retina']['eulerangles'] radius = config['Retina']['radius'] rings = config['Retina']['rings'] steps = config['General']['steps'] screen_write_step = config['Retina']['screen_write_step'] config['Retina']['screen_write_step'] = 1 screen_type = config['Retina']['screentype'] screen_cls = cls_map.get_screen_cls(screen_type) for i in range(eye_num): screen = screen_cls(config) screen_file = 'intensities_tmp{}.h5'.format(i) screen.setup_file(screen_file) retina_elev_file = 'retina_elev{}.h5'.format(i) retina_azim_file = 'retina_azim{}.h5'.format(i) screen_dima_file = 'grid_dima{}.h5'.format(i) screen_dimb_file = 'grid_dimb{}.h5'.format(i) retina_dima_file = 'retina_dima{}.h5'.format(i) retina_dimb_file = 'retina_dimb{}.h5'.format(i) input_file = 'retina_input{}.h5'.format(i) transform = AlbersProjectionMap(radius, eulerangles[3*i:3*(i+1)]).invmap hexagon = hx.HexagonArray(num_rings=rings, radius=radius, transform=transform) retina = ret.RetinaArray(hexagon, config) print('Acceptance angle: {}'.format(retina.acceptance_angle)) print('Neurons: {}'.format(retina.num_photoreceptors)) elev_v, azim_v = retina.get_ommatidia_pos() rfs = _get_receptive_fields(retina, screen, screen_type) steps_count = steps write_mode = 'w' while (steps_count > 0): steps_batch = min(100, steps_count) im = screen.get_screen_intensity_steps(steps_batch) photor_inputs = rfs.filter(im) sio.write_array(photor_inputs, filename=input_file, mode=write_mode) steps_count -= steps_batch write_mode = 'a' tmp = sio.read_array(screen_file) sio.write_array(tmp[::screen_write_step], 'intensities{}{}.h5'.format(suffix, i), complevel = 9) del tmp os.remove(screen_file) for data, filename in [(elev_v, retina_elev_file), (azim_v, retina_azim_file), (screen.grid[0], screen_dima_file), (screen.grid[1], screen_dimb_file), (rfs.refa, retina_dima_file), (rfs.refb, retina_dimb_file)]: sio.write_array(data, filename) def _get_receptive_fields(retina, screen, screen_type): mapdr_cls = cls_map.get_mapdr_cls(screen_type) projection_map = mapdr_cls.from_retina_screen(retina, screen) rf_params = projection_map.map(*retina.get_all_photoreceptors_dir()) if np.isnan(np.sum(rf_params)): print('Warning, Nan entry in array of receptive field centers') vrf_cls = cls_map.get_vrf_cls(screen_type) rfs = vrf_cls(screen.grid) rfs.load_parameters(refa=rf_params[0], refb=rf_params[1], acceptance_angle=retina.get_angle(), radius=screen.radius) return rfs def main(): parser = argparse.ArgumentParser() parser.add_argument('-r', '--rings', type=int, default=14, help='number of layers of ommatidia on circle') parser.add_argument('-l', dest='sublpus', type=int, default=0, help='number of sublpus') parser.add_argument('--steps', default=1000, type=int, help='simulation steps') args = parser.parse_args() gen_input(args.steps, args.rings, 1, args.sublpus) if __name__ == '__main__': main() # # Copyright 2016 The BigDL Authors. # # 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. # import itertools import re from optparse import OptionParser from bigdl.dataset import news20 from bigdl.nn.layer import * from bigdl.nn.criterion import * from bigdl.optim.optimizer import * from bigdl.util.common import * from bigdl.util.common import Sample def text_to_words(review_text): letters_only = re.sub("[^a-zA-Z]", " ", review_text) words = letters_only.lower().split() return words def analyze_texts(data_rdd): def index(w_c_i): ((w, c), i) = w_c_i return (w, (i + 1, c)) return data_rdd.flatMap(lambda text_label: text_to_words(text_label[0])) \ .map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b) \ .sortBy(lambda w_c: - w_c[1]).zipWithIndex() \ .map(lambda w_c_i: index(w_c_i)).collect() # pad([1, 2, 3, 4, 5], 0, 6) def pad(l, fill_value, width): if len(l) >= width: return l[0: width] else: l.extend([fill_value] * (width - len(l))) return l def to_vec(token, b_w2v, embedding_dim): if token in b_w2v: return b_w2v[token] else: return pad([], 0, embedding_dim) def to_sample(vectors, label, embedding_dim): # flatten nested list flatten_features = list(itertools.chain(*vectors)) features = np.array(flatten_features, dtype='float').reshape( [sequence_len, embedding_dim]) if model_type.lower() == "cnn": features = features.transpose(1, 0) return Sample.from_ndarray(features, np.array(label)) def build_model(class_num): model = Sequential() if model_type.lower() == "cnn": model.add(Reshape([embedding_dim, 1, sequence_len])) model.add(SpatialConvolution(embedding_dim, 128, 5, 1)) model.add(ReLU()) model.add(SpatialMaxPooling(5, 1, 5, 1)) model.add(SpatialConvolution(128, 128, 5, 1)) model.add(ReLU()) model.add(SpatialMaxPooling(5, 1, 5, 1)) model.add(Reshape([128])) elif model_type.lower() == "lstm": model.add(Recurrent() .add(LSTM(embedding_dim, 128, p))) model.add(Select(2, -1)) elif model_type.lower() == "gru": model.add(Recurrent() .add(GRU(embedding_dim, 128, p))) model.add(Select(2, -1)) else: raise ValueError('model can only be cnn, lstm, or gru') model.add(Linear(128, 100)) model.add(Linear(100, class_num)) model.add(LogSoftMax()) return model def train(sc, data_path, batch_size, sequence_len, max_words, embedding_dim, training_split): print('Processing text dataset') texts = news20.get_news20(source_dir=data_path) data_rdd = sc.parallelize(texts, 2) word_to_ic = analyze_texts(data_rdd) # Only take the top wc between [10, sequence_len] word_to_ic = dict(word_to_ic[10: max_words]) bword_to_ic = sc.broadcast(word_to_ic) w2v = news20.get_glove_w2v(dim=embedding_dim) filtered_w2v = dict((w, v) for w, v in w2v.items() if w in word_to_ic) bfiltered_w2v = sc.broadcast(filtered_w2v) tokens_rdd = data_rdd.map(lambda text_label: ([w for w in text_to_words(text_label[0]) if w in bword_to_ic.value], text_label[1])) padded_tokens_rdd = tokens_rdd.map( lambda tokens_label: (pad(tokens_label[0], "##", sequence_len), tokens_label[1])) vector_rdd = padded_tokens_rdd.map(lambda tokens_label: ([to_vec(w, bfiltered_w2v.value, embedding_dim) for w in tokens_label[0]], tokens_label[1])) sample_rdd = vector_rdd.map( lambda vectors_label: to_sample(vectors_label[0], vectors_label[1], embedding_dim)) train_rdd, val_rdd = sample_rdd.randomSplit( [training_split, 1-training_split]) optimizer = Optimizer( model=build_model(news20.CLASS_NUM), training_rdd=train_rdd, criterion=ClassNLLCriterion(), end_trigger=MaxEpoch(max_epoch), batch_size=batch_size, optim_method=Adagrad(learningrate=0.01, learningrate_decay=0.0002)) optimizer.set_validation( batch_size=batch_size, val_rdd=val_rdd, trigger=EveryEpoch(), val_method=[Top1Accuracy()] ) train_model = optimizer.optimize() if __name__ == "__main__": parser = OptionParser() parser.add_option("-a", "--action", dest="action", default="train") parser.add_option("-b", "--batchSize", dest="batchSize", default="128") parser.add_option("-e", "--embedding_dim", dest="embedding_dim", default="50") # noqa parser.add_option("-m", "--max_epoch", dest="max_epoch", default="15") parser.add_option("--model", dest="model_type", default="cnn") parser.add_option("-p", "--p", dest="p", default="0.0") parser.add_option("-d", "--data_path", dest="data_path", default="/tmp/news20/") (options, args) = parser.parse_args(sys.argv) if options.action == "train": batch_size = int(options.batchSize) embedding_dim = int(options.embedding_dim) max_epoch = int(options.max_epoch) p = float(options.p) model_type = options.model_type sequence_len = 50 max_words = 1000 training_split = 0.8 sc = SparkContext(appName="text_classifier", conf=create_spark_conf()) data_path = options.data_path redire_spark_logs() show_bigdl_info_logs() init_engine() train(sc, data_path, batch_size, sequence_len, max_words, embedding_dim, training_split) sc.stop() elif options.action == "test": pass # 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. import mock from nova.scheduler.filters import ram_filter from nova import test from nova.tests.unit.scheduler import fakes class TestRamFilter(test.NoDBTestCase): def setUp(self): super(TestRamFilter, self).setUp() self.filt_cls = ram_filter.RamFilter() def test_ram_filter_fails_on_memory(self): filter_properties = {'instance_type': {'memory_mb': 1024}} host = fakes.FakeHostState('host1', 'node1', {'free_ram_mb': 1023, 'total_usable_ram_mb': 1024, 'ram_allocation_ratio': 1.0}) self.assertFalse(self.filt_cls.host_passes(host, filter_properties)) def test_ram_filter_passes(self): filter_properties = {'instance_type': {'memory_mb': 1024}} host = fakes.FakeHostState('host1', 'node1', {'free_ram_mb': 1024, 'total_usable_ram_mb': 1024, 'ram_allocation_ratio': 1.0}) self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) def test_ram_filter_oversubscribe(self): filter_properties = {'instance_type': {'memory_mb': 1024}} host = fakes.FakeHostState('host1', 'node1', {'free_ram_mb': -1024, 'total_usable_ram_mb': 2048, 'ram_allocation_ratio': 2.0}) self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) self.assertEqual(2048 * 2.0, host.limits['memory_mb']) def test_ram_filter_oversubscribe_singe_instance_fails(self): filter_properties = {'instance_type': {'memory_mb': 1024}} host = fakes.FakeHostState('host1', 'node1', {'free_ram_mb': 512, 'total_usable_ram_mb': 512, 'ram_allocation_ratio': 2.0}) self.assertFalse(self.filt_cls.host_passes(host, filter_properties)) @mock.patch('nova.scheduler.filters.utils.aggregate_values_from_key') class TestAggregateRamFilter(test.NoDBTestCase): def setUp(self): super(TestAggregateRamFilter, self).setUp() self.filt_cls = ram_filter.AggregateRamFilter() def test_aggregate_ram_filter_value_error(self, agg_mock): filter_properties = {'context': mock.sentinel.ctx, 'instance_type': {'memory_mb': 1024}} host = fakes.FakeHostState('host1', 'node1', {'free_ram_mb': 1024, 'total_usable_ram_mb': 1024, 'ram_allocation_ratio': 1.0}) agg_mock.return_value = set(['XXX']) self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) self.assertEqual(1024 * 1.0, host.limits['memory_mb']) def test_aggregate_ram_filter_default_value(self, agg_mock): filter_properties = {'context': mock.sentinel.ctx, 'instance_type': {'memory_mb': 1024}} host = fakes.FakeHostState('host1', 'node1', {'free_ram_mb': 1023, 'total_usable_ram_mb': 1024, 'ram_allocation_ratio': 1.0}) # False: fallback to default flag w/o aggregates agg_mock.return_value = set() self.assertFalse(self.filt_cls.host_passes(host, filter_properties)) agg_mock.return_value = set(['2.0']) # True: use ratio from aggregates self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) self.assertEqual(1024 * 2.0, host.limits['memory_mb']) def test_aggregate_ram_filter_conflict_values(self, agg_mock): filter_properties = {'context': mock.sentinel.ctx, 'instance_type': {'memory_mb': 1024}} host = fakes.FakeHostState('host1', 'node1', {'free_ram_mb': 1023, 'total_usable_ram_mb': 1024, 'ram_allocation_ratio': 1.0}) agg_mock.return_value = set(['1.5', '2.0']) # use the minimum ratio from aggregates self.assertTrue(self.filt_cls.host_passes(host, filter_properties)) self.assertEqual(1024 * 1.5, host.limits['memory_mb']) # This file is part of Fail2Ban. # # Fail2Ban 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. # # Fail2Ban 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 Fail2Ban; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # Author: Cyril Jaquier # # $Revision: 696 $ __author__ = "Cyril Jaquier" __version__ = "$Revision: 696 $" __date__ = "$Date: 2008-05-19 23:05:32 +0200 (Mon, 19 May 2008) $" __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" from failmanager import FailManagerEmpty from filter import FileFilter from mytime import MyTime import time, logging, gamin # Gets the instance of the logger. logSys = logging.getLogger("fail2ban.filter") ## # Log reader class. # # This class reads a log file and detects login failures or anything else # that matches a given regular expression. This class is instanciated by # a Jail object. class FilterGamin(FileFilter): ## # Constructor. # # Initialize the filter object with default values. # @param jail the jail object def __init__(self, jail): FileFilter.__init__(self, jail) self.__modified = False # Gamin monitor self.monitor = gamin.WatchMonitor() logSys.debug("Created FilterGamin") def callback(self, path, event): logSys.debug("Got event: " + `event` + " for " + path) if event in (gamin.GAMCreated, gamin.GAMChanged, gamin.GAMExists): logSys.debug("File changed: " + path) self.getFailures(path) self.__modified = True ## # Add a log file path # # @param path log file path def addLogPath(self, path, tail = False): if self.containsLogPath(path): logSys.error(path + " already exists") else: self.monitor.watch_file(path, self.callback) FileFilter.addLogPath(self, path, tail) logSys.info("Added logfile = %s" % path) ## # Delete a log path # # @param path the log file to delete def delLogPath(self, path): if not self.containsLogPath(path): logSys.error(path + " is not monitored") else: self.monitor.stop_watch(path) FileFilter.delLogPath(self, path) logSys.info("Removed logfile = %s" % path) ## # Main loop. # # This function is the main loop of the thread. It checks if the # file has been modified and looks for failures. # @return True when the thread exits nicely def run(self): self.setActive(True) while self._isActive(): if not self.getIdle(): # We cannot block here because we want to be able to # exit. if self.monitor.event_pending(): self.monitor.handle_events() if self.__modified: try: while True: ticket = self.failManager.toBan() self.jail.putFailTicket(ticket) except FailManagerEmpty: self.failManager.cleanup(MyTime.time()) self.dateDetector.sortTemplate() self.__modified = False time.sleep(self.getSleepTime()) else: time.sleep(self.getSleepTime()) # Cleanup Gamin self.__cleanup() logSys.debug(self.jail.getName() + ": filter terminated") return True ## # Desallocates the resources used by Gamin. def __cleanup(self): for path in self.getLogPath(): self.monitor.stop_watch(path.getFileName()) del self.monitor # -*- coding: utf-8 -*- """ Exodus Add-on This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 . """ import re, urllib, urlparse, json from resources.lib.modules import cleantitle from resources.lib.modules import client class source: def __init__(self): self.priority = 1 self.language = ['fr'] self.domains = ['streamay.ws'] self.base_link = 'http://streamay.ws' self.search_link = '/search' def movie(self, imdb, title, localtitle, aliases, year): return self.__search(title, localtitle, year, 'Film') def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year): return self.__search(tvshowtitle, localtvshowtitle, year, 'Série') def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: if not url: return r = client.request(urlparse.urljoin(self.base_link, url)) r = client.parseDOM(r, 'a', attrs={'class': 'item', 'href': '[^\'"]*/saison-%s/episode-%s[^\'"]*' % (season, episode)}, ret='href')[0] url = re.findall('(?://.+?|)(/.+)', r)[0] url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def sources(self, url, hostDict, hostprDict): sources = [] try: if not url: return hostDict = [(i.rsplit('.', 1)[0], i) for i in hostDict] hostDict.append(['okru', 'ok.ru']) locDict = [i[0] for i in hostDict] url = urlparse.urljoin(self.base_link, url) r = client.request(url) r = client.parseDOM(r, 'ul', attrs={'class': '[^\'"]*lecteurs nop[^\'"]*'}) r = client.parseDOM(r, 'li') r = [(client.parseDOM(i, 'a', ret='data-streamer'), client.parseDOM(i, 'a', ret='data-id')) for i in r] r = [(i[0][0], i[1][0], re.search('([a-zA-Z]+)(?:_([a-zA-Z]+))?', i[0][0]), ) for i in r if i[0] and i[1]] r = [(i[0], i[1], i[2].group(1), i[2].group(2)) for i in r if i[2]] for streamer, id, host, info in r: if host not in locDict: continue host = [x[1] for x in hostDict if x[0] == host][0] link = urlparse.urljoin(self.base_link, '/%s/%s/%s' % (('streamerSerie' if '/series/' in url else 'streamer'), id, streamer)) sources.append({'source': host, 'quality': 'SD', 'url': link, 'language': 'FR', 'info': info if info else '', 'direct': False, 'debridonly': False}) return sources except: return sources def resolve(self, url): try: url = json.loads(client.request(url)).get('code') url = url.replace('\/', '/') url = client.replaceHTMLCodes(url).encode('utf-8') if url.startswith('/'): url = 'http:%s' % url return url except: return def __search(self, title, localtitle, year, content_type): try: t = cleantitle.get(title) tq = cleantitle.get(localtitle) y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0'] query = urlparse.urljoin(self.base_link, self.search_link) post = urllib.urlencode({'k': "%s"}) % tq r = client.request(query, post=post) r = json.loads(r) r = [i.get('result') for i in r if i.get('type', '').encode('utf-8') == content_type] r = [(i.get('url'), i.get('originalTitle'), i.get('title'), i.get('anneeProduction', 0), i.get('dateStart', 0)) for i in r] r = [(i[0], re.sub('<.+?>|', '', i[1] if i[1] else ''), re.sub('<.+?>|', '', i[2] if i[2] else ''), i[3] if i[3] else re.findall('(\d{4})', i[4])[0]) for i in r if i[3] or i[4]] r = sorted(r, key=lambda i: int(i[3]), reverse=True) # with year > no year r = [i[0] for i in r if i[3] in y and (t.lower() == cleantitle.get(i[1].lower()) or tq.lower() == cleantitle.query(i[2].lower()))][0] url = re.findall('(?://.+?|)(/.+)', r)[0] url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return # -*- coding: utf-8 -*- from gitdh import git, module from collections import Mapping from configparser import ConfigParser import os.path class Config(ConfigParser): @staticmethod def fromPath(path): if os.path.isfile(path): return Config.fromFilePath(path) elif os.path.isdir(path): return Config.fromGitRepo(path) else: raise Exception("Can't read config from '%s'" % (path,)) @staticmethod def fromGitRepo(repoPath): gC = git.Git(repoPath) if not 'gitdh' in gC.getBranches(): raise Exception("No Branch 'gitdh' in repository '%s'" % (repoPath,)) gFile = None for file in gC.getFiles(branch='gitdh'): if file.getFileName() == 'gitdh.conf': gFile = file break if gFile is None: raise Exception("No File 'gitdh.conf' in branch 'gitdh' in repository '%s'" % (repoPath,)) config = Config() config.read_string(gFile.getFileContent()) config.repoPath = repoPath return config @staticmethod def fromFilePath(filePath): with open(filePath) as f: config = Config.fromFile(f) return config @staticmethod def fromFile(fileObj): c = Config() c.read_file(fileObj) return c def __init__(self): super().__init__() self.branches = ConfigBranches(self) self._repoPath = None @property def repoPath(self): if self._repoPath is None: return self.get('Git', 'RepositoryPath', fallback=None) return self._repoPath @repoPath.setter def repoPath(self, repoPath): self._repoPath = repoPath class ConfigBranches(Mapping): def __init__(self, cfgParser): self._cfgParser = cfgParser self._confRegEx = None def getboolean(self, section, option, fallback=None, *, raw=False, vars=None): if not self._isBranchSection(section): return fallback return self._cfgParser.getboolean(section, option, fallback=fallback, raw=raw, vars=vars) def keys(self): return (s for s in self._cfgParser if self._isBranchSection(s)) def __len__(self): return len([i for i in self.keys()]) def __contains__(self, item): return item in self.keys() def __iter__(self): return self.keys() def __getitem__(self, key): if not self._isBranchSection(key): raise KeyError("Invalid branch section '%s'" % (key,)) return self._cfgParser[key] def _isBranchSection(self, key): if self._confRegEx is None: self._confRegEx = module.ModuleLoader().getConfRegEx() regEx = self._confRegEx return regEx.match(key) is None # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # Copyright 2010 Canonical # Author: Alex Launi # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. from time import sleep from gtk import Clipboard from testtools.matchers import Equals, NotEquals from autopilot.matchers import Eventually from autopilot.tests import AutopilotTestCase class DashTestCase(AutopilotTestCase): def setUp(self): super(DashTestCase, self).setUp() self.set_unity_log_level("unity.shell", "DEBUG") self.set_unity_log_level("unity.launcher", "DEBUG") self.dash.ensure_hidden() # On shutdown, ensure hidden too. Also add a delay. Cleanup is LIFO. self.addCleanup(self.dash.ensure_hidden) self.addCleanup(sleep, 1) class DashRevealTests(DashTestCase): """Test the Unity dash Reveal.""" def test_dash_reveal(self): """Ensure we can show and hide the dash.""" self.dash.ensure_visible() self.dash.ensure_hidden() def test_application_lens_shortcut(self): """Application lense must reveal when Super+a is pressed.""" self.dash.reveal_application_lens() self.assertThat(self.dash.active_lens, Eventually(Equals('applications.lens'))) def test_music_lens_shortcut(self): """Music lense must reveal when Super+w is pressed.""" self.dash.reveal_music_lens() self.assertThat(self.dash.active_lens, Eventually(Equals('music.lens'))) def test_file_lens_shortcut(self): """File lense must reveal when Super+f is pressed.""" self.dash.reveal_file_lens() self.assertThat(self.dash.active_lens, Eventually(Equals('files.lens'))) def test_command_lens_shortcut(self): """Run Command lens must reveat on alt+F2.""" self.dash.reveal_command_lens() self.assertThat(self.dash.active_lens, Eventually(Equals('commands.lens'))) def test_alt_f4_close_dash(self): """Dash must close on alt+F4.""" self.dash.ensure_visible() self.keyboard.press_and_release("Alt+F4") self.assertThat(self.dash.visible, Eventually(Equals(False))) class DashSearchInputTests(DashTestCase): """Test features involving input to the dash search""" def assertSearchText(self, text): self.assertThat(self.dash.search_string, Eventually(Equals(text))) def test_search_keyboard_focus(self): """Dash must put keyboard focus on the search bar at all times.""" self.dash.ensure_visible() self.keyboard.type("Hello") self.assertSearchText("Hello") class DashMultiKeyTests(DashSearchInputTests): def setUp(self): # set the multi key first so that we're not getting a new _DISPLAY while keys are held down. old_value = self.call_gsettings_cmd('get', 'org.gnome.libgnomekbd.keyboard', 'options') self.addCleanup(self.call_gsettings_cmd, 'set', 'org.gnome.libgnomekbd.keyboard', 'options', old_value) self.call_gsettings_cmd('set', 'org.gnome.libgnomekbd.keyboard', 'options', "['Compose key\tcompose:caps']") super(DashMultiKeyTests, self).setUp() def test_multi_key(self): """Pressing 'Multi_key' must not add any characters to the search.""" self.dash.reveal_application_lens() self.keyboard.press_and_release('Multi_key') self.keyboard.type("o") self.assertSearchText("") def test_multi_key_o(self): """Pressing the sequences 'Multi_key' + '^' + 'o' must produce 'ô'.""" self.dash.reveal_application_lens() self.keyboard.press_and_release('Multi_key') self.keyboard.type("^o") self.assertSearchText("ô") def test_multi_key_copyright(self): """Pressing the sequences 'Multi_key' + 'c' + 'o' must produce '©'.""" self.dash.reveal_application_lens() self.keyboard.press_and_release('Multi_key') self.keyboard.type("oc") self.assertSearchText("©") def test_multi_key_delete(self): """Pressing 'Multi_key' must not get stuck looking for a sequence.""" self.dash.reveal_application_lens() self.keyboard.type("dd") self.keyboard.press_and_release('Multi_key') self.keyboard.press_and_release('BackSpace') self.keyboard.press_and_release('BackSpace') self.assertSearchText("d") class DashKeyNavTests(DashTestCase): """Test the unity Dash keyboard navigation.""" def test_lensbar_gets_keyfocus(self): """Test that the lensbar gets key focus after using Down keypresses.""" self.dash.ensure_visible() # Make sure that the lens bar can get the focus for i in range(self.dash.get_num_rows()): self.keyboard.press_and_release("Down") lensbar = self.dash.view.get_lensbar() self.assertThat(lensbar.focused_lens_icon, Eventually(NotEquals(''))) def test_lensbar_focus_changes(self): """Lensbar focused icon should change with Left and Right keypresses.""" self.dash.ensure_visible() for i in range(self.dash.get_num_rows()): self.keyboard.press_and_release("Down") lensbar = self.dash.view.get_lensbar() current_focused_icon = lensbar.focused_lens_icon self.keyboard.press_and_release("Right"); self.assertThat(lensbar.focused_lens_icon, Eventually(NotEquals(current_focused_icon))) self.keyboard.press_and_release("Left") self.assertThat(lensbar.focused_lens_icon, Eventually(Equals(current_focused_icon))) def test_lensbar_enter_activation(self): """Must be able to activate LensBar icons that have focus with an Enter keypress.""" self.dash.ensure_visible() for i in range(self.dash.get_num_rows()): self.keyboard.press_and_release("Down") self.keyboard.press_and_release("Right"); lensbar = self.dash.view.get_lensbar() focused_icon = lensbar.focused_lens_icon self.keyboard.press_and_release("Enter"); self.assertThat(lensbar.active_lens, Eventually(Equals(focused_icon))) # lensbar should lose focus after activation. # TODO this should be a different test to make sure focus # returns to the correct place. self.assertThat(lensbar.focused_lens_icon, Eventually(Equals(""))) def test_category_header_keynav(self): """ Tests that a category header gets focus when 'down' is pressed after the dash is opened OK important to note that this test only tests that A category is focused, not the first and from doing this it seems that it's common for a header other than the first to get focus. """ self.dash.ensure_visible() # Make sure that a category have the focus. self.keyboard.press_and_release("Down") lens = self.dash.get_current_lens() category = lens.get_focused_category() self.assertIsNot(category, None) # Make sure that the category is highlighted. self.assertTrue(category.header_is_highlighted) def test_control_tab_lens_cycle(self): """This test makes sure that Ctrl+Tab cycles lenses.""" self.dash.ensure_visible() self.keyboard.press('Control') self.keyboard.press_and_release('Tab') self.keyboard.release('Control') lensbar = self.dash.view.get_lensbar() self.assertEqual(lensbar.active_lens, u'applications.lens') self.keyboard.press('Control') self.keyboard.press('Shift') self.keyboard.press_and_release('Tab') self.keyboard.release('Control') self.keyboard.release('Shift') self.assertThat(lensbar.active_lens, Eventually(Equals('home.lens'))) def test_tab_cycle_category_headers(self): """ Makes sure that pressing tab cycles through the category headers""" self.dash.ensure_visible() lens = self.dash.get_current_lens() # Test that tab cycles through the categories. # + 1 is to cycle back to first header for i in range(lens.get_num_visible_categories() + 1): self.keyboard.press_and_release('Tab') category = lens.get_focused_category() self.assertIsNot(category, None) def test_tab_with_filter_bar(self): """ This test makes sure that Tab works well with the filter bara.""" self.dash.reveal_application_lens() lens = self.dash.get_current_lens() # Tabs to last category for i in range(lens.get_num_visible_categories()): self.keyboard.press_and_release('Tab') self.keyboard.press_and_release('Tab') self.assertThat(self.dash.searchbar.expander_has_focus, Eventually(Equals(True))) filter_bar = lens.get_filterbar() if not self.dash.searchbar.showing_filters: self.keyboard.press_and_release('Enter') self.assertThat(self.dash.searchbar.showing_filters, Eventually(Equals(True))) self.addCleanup(filter_bar.ensure_collapsed) for i in range(filter_bar.get_num_filters()): self.keyboard.press_and_release('Tab') new_focused_filter = filter_bar.get_focused_filter() self.assertIsNotNone(new_focused_filter) # Ensure that tab cycles back to a category header self.keyboard.press_and_release('Tab') category = lens.get_focused_category() self.assertIsNot(category, None) def test_alt_f1_disabled(self): """This test that Alt+F1 is disabled when the dash is opened.""" self.dash.ensure_visible() # can't use launcher emulator since we'll fail to start keynav: self.keybinding("launcher/keynav") # can't use Eventually here - sleep long enough for the launcher controller # to react to the keypress (well, hopefully not) sleep(5) self.assertThat(self.launcher.key_nav_is_active, Equals(False)) class DashClipboardTests(DashTestCase): """Test the Unity clipboard""" def test_ctrl_a(self): """ This test if ctrl+a selects all text """ self.dash.ensure_visible() self.keyboard.type("SelectAll") self.assertThat(self.dash.search_string, Eventually(Equals("SelectAll"))) self.keyboard.press_and_release("Ctrl+a") self.keyboard.press_and_release("Delete") self.assertThat(self.dash.search_string, Eventually(Equals(''))) def test_ctrl_c(self): """ This test if ctrl+c copies text into the clipboard """ self.dash.ensure_visible() self.keyboard.type("Copy") self.assertThat(self.dash.search_string, Eventually(Equals("Copy"))) self.keyboard.press_and_release("Ctrl+a") self.keyboard.press_and_release("Ctrl+c") cb = Clipboard(selection="CLIPBOARD") self.assertThat(self.dash.search_string, Eventually(Equals(cb.wait_for_text()))) def test_ctrl_x(self): """ This test if ctrl+x deletes all text and copys it """ self.dash.ensure_visible() self.keyboard.type("Cut") self.assertThat(self.dash.search_string, Eventually(Equals("Cut"))) self.keyboard.press_and_release("Ctrl+a") self.keyboard.press_and_release("Ctrl+x") self.assertThat(self.dash.search_string, Eventually(Equals(""))) cb = Clipboard(selection="CLIPBOARD") self.assertEqual(cb.wait_for_text(), u'Cut') def test_ctrl_c_v(self): """ This test if ctrl+c and ctrl+v copies and pastes text""" self.dash.ensure_visible() self.keyboard.type("CopyPaste") self.assertThat(self.dash.search_string, Eventually(Equals("CopyPaste"))) self.keyboard.press_and_release("Ctrl+a") self.keyboard.press_and_release("Ctrl+c") self.keyboard.press_and_release("Ctrl+v") self.keyboard.press_and_release("Ctrl+v") self.assertThat(self.dash.search_string, Eventually(Equals('CopyPasteCopyPaste'))) def test_ctrl_x_v(self): """ This test if ctrl+x and ctrl+v cuts and pastes text""" self.dash.ensure_visible() self.keyboard.type("CutPaste") self.assertThat(self.dash.search_string, Eventually(Equals("CutPaste"))) self.keyboard.press_and_release("Ctrl+a") self.keyboard.press_and_release("Ctrl+x") self.keyboard.press_and_release("Ctrl+v") self.keyboard.press_and_release("Ctrl+v") self.assertThat(self.dash.search_string, Eventually(Equals('CutPasteCutPaste'))) class DashKeyboardFocusTests(DashTestCase): """Tests that keyboard focus works.""" def test_filterbar_expansion_leaves_kb_focus(self): """Expanding or collapsing the filterbar must keave keyboard focus in the search bar. """ self.dash.reveal_application_lens() filter_bar = self.dash.get_current_lens().get_filterbar() filter_bar.ensure_collapsed() self.keyboard.type("hello") filter_bar.ensure_expanded() self.addCleanup(filter_bar.ensure_collapsed) self.keyboard.type(" world") self.assertThat(self.dash.search_string, Eventually(Equals("hello world"))) class DashLensResultsTests(DashTestCase): """Tests results from the lens view.""" def test_results_message_empty_search(self): """This tests a message is not shown when there is no text.""" self.dash.reveal_application_lens() lens = self.dash.get_current_lens() self.assertThat(lens.no_results_active, Eventually(Equals(False))) def test_results_message(self): """This test no mesage will be shown when results are there.""" self.dash.reveal_application_lens() self.keyboard.type("Terminal") self.assertThat(self.dash.search_string, Eventually(Equals("Terminal"))) lens = self.dash.get_current_lens() self.assertThat(lens.no_results_active, Eventually(Equals(False))) def test_no_results_message(self): """This test shows a message will appear in the lens.""" self.dash.reveal_application_lens() self.keyboard.type("qwerlkjzvxc") self.assertThat(self.dash.search_string, Eventually(Equals("qwerlkjzvxc"))) lens = self.dash.get_current_lens() self.assertThat(lens.no_results_active, Eventually(Equals(True))) def test_results_update_on_filter_changed(self): """This test makes sure the results change when filters change.""" self.dash.reveal_application_lens() lens = self.dash.get_current_lens() self.keyboard.type(" ") self.assertThat(self.dash.search_string, Eventually(Equals(" "))) results_category = lens.get_category_by_name("Installed") old_results = results_category.get_results() # FIXME: This should be a method on the dash emulator perhaps, or # maybe a proper method of this class. It should NOT be an inline # function that is only called once! def activate_filter(add_cleanup = False): # Tabs to last category for i in range(lens.get_num_visible_categories()): self.keyboard.press_and_release('Tab') self.keyboard.press_and_release('Tab') self.assertThat(self.dash.searchbar.expander_has_focus, Eventually(Equals(True))) filter_bar = lens.get_filterbar() if not self.dash.searchbar.showing_filters: self.keyboard.press_and_release('Enter') self.assertThat(self.dash.searchbar.showing_filters, Eventually(Equals(True))) if add_cleanup: self.addCleanup(filter_bar.ensure_collapsed) # Tab to the "Type" filter in apps lens self.keyboard.press_and_release('Tab') new_focused_filter = filter_bar.get_focused_filter() self.assertIsNotNone(new_focused_filter) self.keyboard.press_and_release("Down") self.keyboard.press_and_release("Down") self.keyboard.press_and_release("Down") # We should be on the Education category self.keyboard.press_and_release('Enter') activate_filter(True) self.addCleanup(activate_filter) results_category = lens.get_category_by_name("Installed") results = results_category.get_results() self.assertIsNot(results, old_results) # so we can clean up properly self.keyboard.press_and_release('BackSpace') class DashVisualTests(DashTestCase): """Tests that the dash visual is correct.""" def test_see_more_result_alignment(self): """The see more results label should be baseline aligned with the category name label. """ self.dash.reveal_application_lens() lens = self.dash.get_current_lens() groups = lens.get_groups() for group in groups: if (group.is_visible and group.expand_label_is_visible): expand_label_y = group.expand_label_y + group.expand_label_baseline name_label_y = group.name_label_y + group.name_label_baseline self.assertThat(expand_label_y, Equals(name_label_y)) class DashLensBarTests(DashTestCase): """Tests that the lensbar works well.""" def setUp(self): super(DashLensBarTests, self).setUp() self.dash.ensure_visible() self.lensbar = self.dash.view.get_lensbar() def test_click_inside_highlight(self): """Lens selection should work when clicking in the rectangle outside of the icon. """ app_icon = self.lensbar.get_icon_by_name(u'applications.lens') self.mouse.move(app_icon.x + (app_icon.width / 2), app_icon.y + (app_icon.height / 2)) self.mouse.click() self.assertThat(self.lensbar.active_lens, Eventually(Equals('applications.lens'))) class DashBorderTests(DashTestCase): """Tests that the dash border works well. """ def setUp(self): super(DashBorderTests, self).setUp() self.dash.ensure_visible() def test_click_right_border(self): """Clicking on the right dash border should do nothing, *NOT* close the dash. """ if (self.dash.view.form_factor != "desktop"): self.skip("Not in desktop form-factor.") x = self.dash.view.x + self.dash.view.width + self.dash.view.right_border_width / 2; y = self.dash.view.y + self.dash.view.height / 2; self.mouse.move(x, y) self.mouse.click() self.assertThat(self.dash.visible, Eventually(Equals(True))) def test_click_bottom_border(self): """Clicking on the bottom dash border should do nothing, *NOT* close the dash. """ if (self.dash.view.form_factor != "desktop"): self.skip("Not in desktop form-factor.") x = self.dash.view.x + self.dash.view.width / 2; y = self.dash.view.y + self.dash.view.height + self.dash.view.bottom_border_height / 2; self.mouse.move(x, y) self.mouse.click() self.assertThat(self.dash.visible, Eventually(Equals(True))) #!/usr/bin/env python # -*- coding: utf-8 -*- # # funcext documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) import funcext # -- General configuration --------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'funcext' copyright = u"2017, Ariel De Ocampo" # 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 short X.Y version. version = funcext.__version__ # The full version, including alpha/beta/rc tags. release = funcext.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #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'] # 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 # -- 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 = 'default' # 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 = {} # 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 # " v 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'] # 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 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 # Output file base name for HTML help builder. htmlhelp_basename = 'funcextdoc' # -- 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': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', 'funcext.tex', u'funcext Documentation', u'Ariel De Ocampo', '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 references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'funcext', u'funcext Documentation', [u'Ariel De Ocampo'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ---------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'funcext', u'funcext Documentation', u'Ariel De Ocampo', 'funcext', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -*- coding: utf-8 -*- """ Written by Daniel M. Aukes. Email: danaukesseas.harvard.edu. Please see LICENSE.txt for full license. """ import PySide.QtCore as qc import PySide.QtGui as qg from . import modes from popupcad.graphics2d.graphicsitems import Common import popupcad class InteractiveVertexBase(qg.QGraphicsEllipseItem, Common): radius = 10 z_below = 100 z_above = 105 def __init__(self, symbol, *args, **kwargs): try: temppos = kwargs.pop('pos') except KeyError: temppos = None super(InteractiveVertexBase, self).__init__(*args, **kwargs) self.states = modes.EdgeVertexStates() self.modes = modes.EdgeVertexModes() self.defaultpen = qg.QPen( qg.QColor.fromRgbF( 0, 0, 0, 0), 0.0, qc.Qt.PenStyle.NoPen) self.setAcceptHoverEvents(True) self.setRect(- 1. * self.radius / 2, - 1. * self.radius / 2, self.radius, self.radius) self.setZValue(self.z_below) self.state = self.states.state_neutral self.updatemode(self.modes.mode_normal) self.updatestate(self.states.state_neutral) self.setFlag(self.ItemIsFocusable, True) self.changed_trigger = False if temppos is not None: self.setPos(temppos) self.setselectable(True) self.generic = symbol self.setFlag(self.ItemIsMovable, True) self.updateshape() # self.setFlag(self.ItemSendsGeometryChanges,True) def updatemode(self, mode): self.mode = getattr(self.modes, mode) self.setPen(self.querypen()) self.setBrush(self.querybrush()) self.update() def updatestate(self, state): self.state = getattr(self.states, state) self.setPen(self.querypen()) self.setBrush(self.querybrush()) self.update() def querypen(self): if self.mode == self.modes.mode_render: pen = self.defaultpen else: if self.state == self.states.state_hover: pen = qg.QPen( qg.QColor.fromRgbF( 0, 0, 0, 1), 1.0, qc.Qt.SolidLine, qc.Qt.RoundCap, qc.Qt.RoundJoin) if self.state == self.states.state_pressed: pen = qg.QPen( qg.QColor.fromRgbF( 0, 0, 0, 1), 1.0, qc.Qt.SolidLine, qc.Qt.RoundCap, qc.Qt.RoundJoin) if self.state == self.states.state_neutral: pen = qg.QPen( qg.QColor.fromRgbF( 0, 0, 0, 1), 1.0, qc.Qt.SolidLine, qc.Qt.RoundCap, qc.Qt.RoundJoin) pen.setCosmetic(True) return pen def querybrush(self): if self.mode == self.modes.mode_render: brush = qg.QBrush(qg.QColor.fromRgbF(0, 0, 0, 0), qc.Qt.NoBrush) else: if self.state == self.states.state_hover: brush = qg.QBrush( qg.QColor.fromRgbF( 1, .5, 0, 1), qc.Qt.SolidPattern) if self.state == self.states.state_pressed: brush = qg.QBrush( qg.QColor.fromRgbF( 1, 0, 0, 1), qc.Qt.SolidPattern) if self.state == self.states.state_neutral: brush = qg.QBrush( qg.QColor.fromRgbF( 0, 0, 0, 1), qc.Qt.SolidPattern) return brush def setselectable(self, test): self.setFlag(self.ItemIsSelectable, test) def hoverEnterEvent(self, event): super(InteractiveVertexBase, self).hoverEnterEvent(event) self.updatestate(self.states.state_hover) def hoverLeaveEvent(self, event): super(InteractiveVertexBase, self).hoverLeaveEvent(event) self.setZValue(self.z_below) self.updatestate(self.states.state_neutral) # def itemChange(self,change,value): # if change == self.GraphicsItemChange.ItemPositionHasChanged: # if self.changed_trigger: # self.changed_trigger = False # self.scene().savesnapshot.emit() # self.get_generic().setpos(self.pos().toTuple()) # # return super(InteractiveVertexBase,self).itemChange(change,value) def mousePressEvent(self, event): self.changed_trigger = True self.moved_trigger = False self.updatestate(self.states.state_pressed) self.scene().itemclicked.emit(self.get_generic()) super(InteractiveVertexBase, self).mousePressEvent(event) def mouseMoveEvent(self, event): import numpy if self.changed_trigger: self.changed_trigger = False self.moved_trigger = True self.scene().savesnapshot.emit() dp = event.scenePos() - event.lastScenePos() dp = tuple(numpy.array(dp.toTuple()) / popupcad.view_scaling) self.generic.constrained_shift(dp, self.constraintsystem()) self.scene().updateshape() def mouseReleaseEvent(self, event): super(InteractiveVertexBase, self).mouseReleaseEvent(event) self.updatestate(self.states.state_hover) self.changed_trigger = False if self.moved_trigger: self.moved_trigger = False self.scene().constraint_update_request.emit(self.generic) def setPos(self, pos): import numpy pos = tuple(numpy.array(pos.toTuple()) / popupcad.view_scaling) self.generic.setpos(pos) self.updateshape() def get_generic(self): try: return self.generic except AttributeError: self.generic = self.symbolic del self.symbolic return self.generic # def pos(self): # pos= super(InteractiveVertexBase,self).pos() # return pos def updateshape(self): postuple = self.get_generic().getpos(scaling=popupcad.view_scaling) pos = qc.QPointF(*postuple) super(InteractiveVertexBase, self).setPos(pos) def set_view_scale(self, view_scale): self._view_scale = view_scale self.setScale(view_scale) def get_view_scale(self): try: return self._view_scale except AttributeError: self._view_scale = 1 return self._view_scale view_scale = property(get_view_scale,set_view_scale) def updatescale(self): try: self.set_view_scale(1 / self.scene().views()[0].zoom()) except AttributeError: pass from django.conf.urls import url from django.contrib.auth.views import logout from emailconfirmation.views import confirm_email from ajax_validation.views import validate from account.forms import SignupForm from . import views from django.views.generic import TemplateView urlpatterns = [ url(r"^email/$", views.email, name="acct_email"), url(r"^signup/$", views.signup, name="acct_signup"), url(r"^login/$", views.login, name="acct_login"), url(r"^password_change/$", views.password_change, name="acct_passwd"), url(r"^password_set/$", views.password_set, name="acct_passwd_set"), url(r"^timezone/$", views.timezone_change, name="acct_timezone_change"), url(r"^language/$", views.language_change, name="acct_language_change"), url(r"^logout/$", logout, {"template_name": "account/logout.html"}, name="acct_logout"), url(r"^confirm_email/(\w+)/$", confirm_email, name="acct_confirm_email"), # password reset url(r"^password_reset/$", views.password_reset, name="acct_passwd_reset"), url(r"^password_reset/done/$", views.password_reset_done, name="acct_passwd_reset_done"), url(r"^password_reset_key/(?P[0-9A-Za-z]+)-(?P.+)/$", views.password_reset_from_key, name="acct_passwd_reset_key"), # ajax validation url(r"^validate/$", validate, {"form_class": SignupForm}, name="signup_form_validate"), ] #!/usr/bin/python # coding: utf-8 TEXTFILE_DIR = '/var/lib/prometheus/node-exporter' DEFAULT_HELP_TEXT = 'A metric' # - node_set_metric: # name: "location_dc" # content: "msk" # help_test: "a metric" # state: present # become_user: prometheus # - node_set_metric: # name: "obsolete" # state: absent # become_user: prometheus import os import filecmp from tempfile import mkstemp def metric_file_path(name): return os.path.join(TEXTFILE_DIR, "{}.prom".format(name)) def metric_remove(name): textfile = metric_file_path(name) try: if os.path.isfile(textfile): os.remove(textfile) return {"msg":"OK", "failed":False, "changed":True} except OSError as e: return {"msg":e, "failed":True, "changed":False} return {"msg":"OK", "failed":False, "changed":False} def metric_set(name, content, help_text): full_name = "node_{}".format(name) textfile = metric_file_path(name) try: fd, tmp_path = mkstemp(prefix=name, dir=TEXTFILE_DIR) os.write(fd, "# HELP {} {}\n".format(full_name, help_text)) os.write(fd, "# TYPE {} untyped\n".format(full_name)) os.write(fd, "{}{}{}=\"{}\"{} 1\n".format(full_name, '{', full_name, content, "}")) os.close(fd) except OSError as e: if os.path.isfile(tmp_path): os.remove(tmp_path) return {"msg":e, "failed":True, "changed":False} if os.path.isfile(textfile): if filecmp.cmp(tmp_path, textfile, False): os.remove(tmp_path) return {"msg":"OK", "failed":False, "changed":False} try: os.remove(textfile) except OSError as e: return {"msg":e, "failed":True, "changed":False} try: os.rename(tmp_path, textfile) except OSError as e: return {"msg":e, "failed":True, "changed":True} os.chmod(textfile, 0644) return {"msg":"OK", "failed":False, "changed":True} def main(): module = AnsibleModule( argument_spec = dict( name = dict(type='str', required=True), content = dict(type='str', required=False, default=None), help_text = dict(type='str', required=False, default=DEFAULT_HELP_TEXT), state = dict(choices=['present','absent'], required=False, default='present'), ) ) name = module.params['name'] content = module.params['content'] help_text = module.params['help_text'] state = module.params['state'] if state == 'absent': module.exit_json(**metric_remove(name)) if state == 'present' and content is None: module.exit_json(msg="content must be defined", failed=True) module.exit_json(**metric_set(name, content, help_text)) from ansible.module_utils.basic import * main() #!/usr/bin/env python # -*- encoding: utf-8 -*- import os import sys from subprocess import check_call as execute from types import ModuleType import django from django.utils.importlib import import_module os.environ["DJANGO_SETTINGS_MODULE"] = "settings.default_only_cassandra" test_dir = os.path.dirname(__file__) sys.path.insert(0, test_dir) def run_tests(foo, settings='settings', extra=(), test_builtin=False): if isinstance(foo, ModuleType): settings = foo.__name__ apps = list(foo.INSTALLED_APPS) else: apps = list(foo) if not test_builtin: apps = [ name for name in apps if not name.startswith('django.contrib.')] # pre-1.6 test runners don't understand full module names if django.VERSION < (1, 6): apps = [app.replace('django.contrib.', '') for app in apps] apps = [name for name in apps if not name.startswith('testproject.')] os.chdir(test_dir) print('\n============================\n' 'Running tests with settings: {}\n' '============================\n'.format(settings)) return execute( ['./manage.py', 'test', '--settings', settings] + list(extra) + apps) def main(): default_only_cass = import_module( 'settings.default_only_cassandra') secondary_cassandra = import_module( 'settings.secondary_cassandra') multi_cassandra = import_module( 'settings.multi_cassandra') if django.VERSION[0:2] >= (1, 7): django.setup() run_tests(default_only_cass) run_tests(secondary_cassandra) run_tests(multi_cassandra) sys.exit(0) if __name__ == "__main__": main() # # Author:: Matthew Kent () # Copyright:: Copyright 2009-2016, Matthew Kent # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # # yum-dump.py # Inspired by yumhelper.py by David Lutterkort # # Produce a list of installed, available and re-installable packages using yum # and dump the results to stdout. # # yum-dump invokes yum similarly to the command line interface which makes it # subject to most of the configuration parameters in yum.conf. yum-dump will # also load yum plugins in the same manor as yum - these can affect the output. # # Can be run as non root, but that won't update the cache. # # Intended to support yum 2.x and 3.x import os import sys import time import yum import re import errno from yum import Errors from optparse import OptionParser from distutils import version YUM_PID_FILE='/var/run/yum.pid' YUM_VER = version.StrictVersion(yum.__version__) YUM_MAJOR = YUM_VER.version[0] if YUM_MAJOR > 3 or YUM_MAJOR < 2: print >> sys.stderr, "yum-dump Error: Can't match supported yum version" \ " (%s)" % yum.__version__ sys.exit(1) # Required for Provides output if YUM_MAJOR == 2: import rpm import rpmUtils.miscutils def setup(yb, options): # Only want our output # if YUM_MAJOR == 3: try: if YUM_VER >= version.StrictVersion("3.2.22"): yb.preconf.errorlevel=0 yb.preconf.debuglevel=0 # initialize the config yb.conf else: yb.doConfigSetup(errorlevel=0, debuglevel=0) except yum.Errors.ConfigError, e: # suppresses an ignored exception at exit yb.preconf = None print >> sys.stderr, "yum-dump Config Error: %s" % e return 1 except ValueError, e: yb.preconf = None print >> sys.stderr, "yum-dump Options Error: %s" % e return 1 elif YUM_MAJOR == 2: yb.doConfigSetup() def __log(a,b): pass yb.log = __log yb.errorlog = __log # Give Chef every possible package version, it can decide what to do with them if YUM_MAJOR == 3: yb.conf.showdupesfromrepos = True elif YUM_MAJOR == 2: yb.conf.setConfigOption('showdupesfromrepos', True) # Optionally run only on cached repositories, but non root must use the cache if os.geteuid() != 0: if YUM_MAJOR == 3: yb.conf.cache = True elif YUM_MAJOR == 2: yb.conf.setConfigOption('cache', True) else: if YUM_MAJOR == 3: yb.conf.cache = options.cache elif YUM_MAJOR == 2: yb.conf.setConfigOption('cache', options.cache) # Handle repo toggle via id or glob exactly like yum for opt, repos in options.repo_control: for repo in repos: if opt == '--enablerepo': yb.repos.enableRepo(repo) elif opt == '--disablerepo': yb.repos.disableRepo(repo) return 0 def dump_packages(yb, list, output_provides): packages = {} if YUM_MAJOR == 2: yb.doTsSetup() yb.doRepoSetup() yb.doSackSetup() db = yb.doPackageLists(list) for pkg in db.installed: pkg.type = 'i' packages[str(pkg)] = pkg if YUM_VER >= version.StrictVersion("3.2.21"): for pkg in db.available: pkg.type = 'a' packages[str(pkg)] = pkg # These are both installed and available for pkg in db.reinstall_available: pkg.type = 'r' packages[str(pkg)] = pkg else: # Old style method - no reinstall list for pkg in yb.pkgSack.returnPackages(): if str(pkg) in packages: if packages[str(pkg)].type == "i": packages[str(pkg)].type = 'r' continue pkg.type = 'a' packages[str(pkg)] = pkg unique_packages = packages.values() unique_packages.sort(lambda x, y: cmp(x.name, y.name)) for pkg in unique_packages: if output_provides == "all" or \ (output_provides == "installed" and (pkg.type == "i" or pkg.type == "r")): # yum 2 doesn't have provides_print, implement it ourselves using methods # based on requires gathering in packages.py if YUM_MAJOR == 2: provlist = [] # Installed and available are gathered in different ways if pkg.type == 'i' or pkg.type == 'r': names = pkg.hdr[rpm.RPMTAG_PROVIDENAME] flags = pkg.hdr[rpm.RPMTAG_PROVIDEFLAGS] ver = pkg.hdr[rpm.RPMTAG_PROVIDEVERSION] if names is not None: tmplst = zip(names, flags, ver) for (n, f, v) in tmplst: prov = rpmUtils.miscutils.formatRequire(n, v, f) provlist.append(prov) # This is slow :( elif pkg.type == 'a': for prcoTuple in pkg.returnPrco('provides'): prcostr = pkg.prcoPrintable(prcoTuple) provlist.append(prcostr) provides = provlist else: provides = pkg.provides_print else: provides = "[]" print '%s %s %s %s %s %s %s %s' % ( pkg.name, pkg.epoch, pkg.version, pkg.release, pkg.arch, provides, pkg.type, pkg.repoid ) return 0 def yum_dump(options): lock_obtained = False yb = yum.YumBase() status = setup(yb, options) if status != 0: return status if options.output_options: print "[option installonlypkgs] %s" % " ".join(yb.conf.installonlypkgs) # Non root can't handle locking on rhel/centos 4 if os.geteuid() != 0: return dump_packages(yb, options.package_list, options.output_provides) # Wrap the collection and output of packages in yum's global lock to prevent # any inconsistencies. try: # Spin up to --yum-lock-timeout option countdown = options.yum_lock_timeout while True: try: yb.doLock(YUM_PID_FILE) lock_obtained = True except Errors.LockError, e: time.sleep(1) countdown -= 1 if countdown == 0: print >> sys.stderr, "yum-dump Locking Error! Couldn't obtain an " \ "exclusive yum lock in %d seconds. Giving up." % options.yum_lock_timeout return 200 else: break return dump_packages(yb, options.package_list, options.output_provides) # Ensure we clear the lock and cleanup any resources finally: try: yb.closeRpmDB() if lock_obtained == True: yb.doUnlock(YUM_PID_FILE) except Errors.LockError, e: print >> sys.stderr, "yum-dump Unlock Error: %s" % e return 200 # Preserve order of enable/disable repo args like yum does def gather_repo_opts(option, opt, value, parser): if getattr(parser.values, option.dest, None) is None: setattr(parser.values, option.dest, []) getattr(parser.values, option.dest).append((opt, value.split(','))) def main(): usage = "Usage: %prog [options]\n" + \ "Output a list of installed, available and re-installable packages via yum" parser = OptionParser(usage=usage) parser.add_option("-C", "--cache", action="store_true", dest="cache", default=False, help="run entirely from cache, don't update cache") parser.add_option("-o", "--options", action="store_true", dest="output_options", default=False, help="output select yum options useful to Chef") parser.add_option("-p", "--installed-provides", action="store_const", const="installed", dest="output_provides", default="none", help="output Provides for installed packages, big/wide output") parser.add_option("-P", "--all-provides", action="store_const", const="all", dest="output_provides", default="none", help="output Provides for all package, slow, big/wide output") parser.add_option("-i", "--installed", action="store_const", const="installed", dest="package_list", default="all", help="output only installed packages") parser.add_option("-a", "--available", action="store_const", const="available", dest="package_list", default="all", help="output only available and re-installable packages") parser.add_option("--enablerepo", action="callback", callback=gather_repo_opts, type="string", dest="repo_control", default=[], help="enable disabled repositories by id or glob") parser.add_option("--disablerepo", action="callback", callback=gather_repo_opts, type="string", dest="repo_control", default=[], help="disable repositories by id or glob") parser.add_option("--yum-lock-timeout", action="store", type="int", dest="yum_lock_timeout", default=30, help="Time in seconds to wait for yum process lock") (options, args) = parser.parse_args() try: return yum_dump(options) except yum.Errors.RepoError, e: print >> sys.stderr, "yum-dump Repository Error: %s" % e return 1 except yum.Errors.YumBaseError, e: print >> sys.stderr, "yum-dump General Error: %s" % e return 1 try: status = main() # Suppress a nasty broken pipe error when output is piped to utilities like 'head' except IOError, e: if e.errno == errno.EPIPE: sys.exit(1) else: raise sys.exit(status) # -*- coding: utf-8 -*- import os import sys try: from gluon import current except ImportError: print >> sys.stderr, """ The installed version of Web2py is too old -- it does not define current. Please upgrade Web2py to a more recent version. """ # Version of 000_config.py # Increment this if the user should update their running instance VERSION = 1 #def update_check(environment, template="default"): def update_check(settings): """ Check whether the dependencies are sufficient to run Eden @ToDo: Load deployment_settings so that we can configure the update_check - need to rework so that 000_config.py is parsed 1st @param settings: the deployment_settings """ # Get Web2py environment into our globals. #globals().update(**environment) request = current.request # Fatal errors errors = [] # Non-fatal warnings warnings = [] # ------------------------------------------------------------------------- # Check Python libraries # Get mandatory global dependencies app_path = request.folder gr_path = os.path.join(app_path, "requirements.txt") or_path = os.path.join(app_path, "optional_requirements.txt") global_dep = parse_requirements({}, gr_path) optional_dep = parse_requirements({}, or_path) templates = settings.get_template() location = settings.get_template_location() if not isinstance(templates, (tuple, list)): templates = (templates,) template_dep = {} template_optional_dep = {} for template in templates: tr_path = os.path.join(app_path, location, "templates", template, "requirements.txt") tor_path = os.path.join(app_path, location, "templates", template, "optional_requirements.txt") parse_requirements(template_dep, tr_path) parse_requirements(template_optional_dep, tor_path) # Remove optional dependencies which are already accounted for in template dependencies unique = set(optional_dep.keys()).difference(set(template_dep.keys())) for dependency in optional_dep.keys(): if dependency not in unique: del optional_dep[dependency] # Override optional dependency messages from template unique = set(optional_dep.keys()).difference(set(template_optional_dep.keys())) for dependency in optional_dep.keys(): if dependency not in unique: del optional_dep[dependency] errors, warnings = s3_check_python_lib(global_dep, template_dep, template_optional_dep, optional_dep) # @ToDo: Move these to Template # for now this is done in s3db.climate_first_run() if settings.has_module("climate"): if settings.get_database_type() != "postgres": errors.append("Climate unresolved dependency: PostgreSQL required") try: import rpy2 except ImportError: errors.append("Climate unresolved dependency: RPy2 required") try: from Scientific.IO import NetCDF except ImportError: warnings.append("Climate unresolved dependency: NetCDF required if you want to import readings") try: from scipy import stats except ImportError: warnings.append("Climate unresolved dependency: SciPy required if you want to generate graphs on the map") # ------------------------------------------------------------------------- # Check Web2Py version # # Currently, the minimum usable Web2py is determined by whether the # Scheduler is available web2py_minimum_version = "Version 2.4.7-stable+timestamp.2013.05.27.11.49.44" # Offset of datetime in return value of parse_version. datetime_index = 4 web2py_version_ok = True try: from gluon.fileutils import parse_version except ImportError: web2py_version_ok = False if web2py_version_ok: try: web2py_minimum_parsed = parse_version(web2py_minimum_version) web2py_minimum_datetime = web2py_minimum_parsed[datetime_index] web2py_installed_version = request.global_settings.web2py_version if isinstance(web2py_installed_version, str): # Post 2.4.2, request.global_settings.web2py_version is unparsed web2py_installed_parsed = parse_version(web2py_installed_version) web2py_installed_datetime = web2py_installed_parsed[datetime_index] else: # 2.4.2 & earlier style web2py_installed_datetime = web2py_installed_version[datetime_index] web2py_version_ok = web2py_installed_datetime >= web2py_minimum_datetime except: # Will get AttributeError if Web2py's parse_version is too old for # its current version format, which changed in 2.3.2. web2py_version_ok = False if not web2py_version_ok: warnings.append( "The installed version of Web2py is too old to support the current version of Sahana Eden." "\nPlease upgrade Web2py to at least version: %s" % \ web2py_minimum_version) # ------------------------------------------------------------------------- # Create required directories if needed databases_dir = os.path.join(app_path, "databases") try: os.stat(databases_dir) except OSError: # not found, create it os.mkdir(databases_dir) # ------------------------------------------------------------------------- # Copy in Templates # - 000_config.py (machine-specific settings) # - rest are run in-place # template_folder = os.path.join(app_path, "modules", "templates") template_files = { # source : destination "000_config.py" : os.path.join("models", "000_config.py"), } copied_from_template = [] for t in template_files: src_path = os.path.join(template_folder, t) dst_path = os.path.join(app_path, template_files[t]) try: os.stat(dst_path) except OSError: # Not found, copy from template if t == "000_config.py": input = open(src_path) output = open(dst_path, "w") for line in input: if "akeytochange" in line: # Generate a random hmac_key to secure the passwords in case # the database is compromised import uuid hmac_key = uuid.uuid4() line = 'settings.auth.hmac_key = "%s"' % hmac_key output.write(line) output.close() input.close() else: import shutil shutil.copy(src_path, dst_path) copied_from_template.append(template_files[t]) # @ToDo: WebSetup # http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/WebSetup #if not os.path.exists("%s/applications/websetup" % os.getcwd()): # # @ToDo: Check Permissions # # Copy files into this folder (@ToDo: Pythonise) # cp -r private/websetup "%s/applications" % os.getcwd() # Launch WebSetup #redirect(URL(a="websetup", c="default", f="index", # vars=dict(appname=request.application, # firstTime="True"))) else: # Found the file in the destination # Check if it has been edited import re edited_pattern = r"FINISHED_EDITING_\w*\s*=\s*(True|False)" edited_matcher = re.compile(edited_pattern).match has_edited = False with open(dst_path) as f: for line in f: edited_result = edited_matcher(line) if edited_result: has_edited = True edited = edited_result.group(1) break if has_edited and (edited != "True"): errors.append("Please edit %s before starting the system." % t) # Check if it's up to date (i.e. a critical update requirement) version_pattern = r"VERSION =\s*([0-9]+)" version_matcher = re.compile(version_pattern).match has_version = False with open(dst_path) as f: for line in f: version_result = version_matcher(line) if version_result: has_version = True version = version_result.group(1) break if not has_version: error = "Your %s is using settings from the old templates system. Please switch to the new templates system: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Templates" % t errors.append(error) elif int(version) != VERSION: error = "Your %s is using settings from template version %s. Please update with new settings from template version %s before starting the system." % \ (t, version, VERSION) errors.append(error) if copied_from_template: errors.append( "The following files were copied from templates and should be edited: %s" % ", ".join(copied_from_template)) return {"error_messages": errors, "warning_messages": warnings} # ------------------------------------------------------------------------- def parse_requirements(output, filepath): """ """ try: with open(filepath) as filehandle: dependencies = filehandle.read().splitlines() msg = "" for dependency in dependencies: if dependency[0] == "#": # either a normal comment or custom message if dependency[:9] == "# Warning" or dependency[7] == "# Error:": msg = dependency.split(":", 1)[1] else: import re # Check if the module name is different from the package name if "#" in dependency: dep = dependency.split("#", 1)[1] output[dep] = msg else: pattern = re.compile(r'([A-Za-z0-9_-]+)') try: dep = pattern.match(dependency).group(1) output[dep] = msg except AttributeError: # Invalid dependency syntax pass msg = "" except IOError: # No override for Template pass return output # ------------------------------------------------------------------------- def s3_check_python_lib(global_mandatory, template_mandatory, template_optional, global_optional): """ checks for optional as well as mandatory python libraries """ errors = [] warnings = [] for dependency, err in global_mandatory.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if err: errors.append(err) else: errors.append("S3 unresolved dependency: %s required for Sahana to run" % dependency) for dependency, err in template_mandatory.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if err: errors.append(err) else: errors.append("Unresolved template dependency: %s required" % dependency) for dependency, warn in template_optional.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if warn: warnings.append(warn) else: warnings.append("Unresolved optional dependency: %s required" % dependency) for dependency, warn in global_optional.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if warn: warnings.append(warn) else: warnings.append("Unresolved optional dependency: %s required" % dependency) return errors, warnings # END ========================================================================= # Copyright 2015-2016 Yelp 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 the License for the specific language governing permissions and # limitations under the License. import os import random import yaml def _get_smartstack_proxy_ports_from_file(root, file): """Given a root and file (as from os.walk), attempt to return the highest smartstack proxy port number (int) from that file. Returns 0 if there is no smartstack proxy_port. """ ports = set() with open(os.path.join(root, file)) as f: data = yaml.safe_load(f) if file.endswith("service.yaml") and "smartstack" in data: # Specifying this in service.yaml is old and deprecated and doesn't # support multiple namespaces. ports = {int(data["smartstack"].get("proxy_port", 0))} elif file.endswith("smartstack.yaml"): for namespace in data.keys(): ports.add(data[namespace].get("proxy_port", 0)) return ports def read_etc_services(): with open("/etc/services") as fd: return fd.readlines() def get_inuse_ports_from_etc_services(): ports = set() for line in read_etc_services(): if line.startswith("#"): continue try: p = line.split()[1] port = int(p.split("/")[0]) ports.add(port) except Exception: pass return ports def suggest_smartstack_proxy_port( yelpsoa_config_root, range_min=19000, range_max=21000 ): """Pick a random available port in the 19000-21000 block""" available_proxy_ports = set(range(range_min, range_max + 1)) for root, dirs, files in os.walk(yelpsoa_config_root): for f in files: if f.endswith("smartstack.yaml"): try: used_ports = _get_smartstack_proxy_ports_from_file(root, f) for used_port in used_ports: available_proxy_ports.discard(used_port) except Exception: pass available_proxy_ports.difference_update(get_inuse_ports_from_etc_services()) try: return random.choice(list(available_proxy_ports)) except IndexError: raise Exception( f"There are no more ports available in the range [{range_min}, {range_max}]" ) # vim: expandtab tabstop=4 sts=4 shiftwidth=4: # -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## from openerp.osv import fields, osv class res_partner(osv.osv): _name = 'res.partner' _inherit = 'res.partner' def _purchase_invoice_count(self, cr, uid, ids, field_name, arg, context=None): PurchaseOrder = self.pool['purchase.order'] Invoice = self.pool['account.invoice'] return { partner_id: { 'purchase_order_count': PurchaseOrder.search_count(cr,uid, [('partner_id', '=', partner_id)], context=context), 'supplier_invoice_count': Invoice.search_count(cr,uid, [('partner_id', '=', partner_id), ('type','=','in_invoice')], context=context) } for partner_id in ids } def _commercial_fields(self, cr, uid, context=None): return super(res_partner, self)._commercial_fields(cr, uid, context=context) + ['property_product_pricelist_purchase'] _columns = { 'property_product_pricelist_purchase': fields.property( type='many2one', relation='product.pricelist', domain=[('type','=','purchase')], string="Purchase Pricelist", help="This pricelist will be used, instead of the default one, for purchases from the current partner"), 'purchase_order_count': fields.function(_purchase_invoice_count, string='# of Purchase Order', type='integer', multi="count"), 'supplier_invoice_count': fields.function(_purchase_invoice_count, string='# Supplier Invoices', type='integer', multi="count"), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: #!/usr/bin/env python # # Copyright 2009 the V8 project authors. 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 Google Inc. 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. # This is an utility for converting V8 heap logs into .hp files that can # be further processed using 'hp2ps' tool (bundled with GHC and Valgrind) # to produce heap usage histograms. # Sample usage: # $ ./shell --log-gc script.js # $ tools/process-heap-prof.py v8.log | hp2ps -c > script-heap-graph.ps # ('-c' enables color, see hp2ps manual page for more options) # or # $ tools/process-heap-prof.py --js-cons-profile v8.log | hp2ps -c > script-heap-graph.ps # to get JS constructor profile import csv, sys, time, optparse def ProcessLogFile(filename, options): if options.js_cons_profile: itemname = 'heap-js-cons-item' else: itemname = 'heap-sample-item' first_call_time = None sample_time = 0.0 sampling = False try: logfile = open(filename, 'rb') try: logreader = csv.reader(logfile) print('JOB "v8"') print('DATE "%s"' % time.asctime(time.localtime())) print('SAMPLE_UNIT "seconds"') print('VALUE_UNIT "bytes"') for row in logreader: if row[0] == 'heap-sample-begin' and row[1] == 'Heap': sample_time = float(row[3])/1000.0 if first_call_time == None: first_call_time = sample_time sample_time -= first_call_time print('BEGIN_SAMPLE %.2f' % sample_time) sampling = True elif row[0] == 'heap-sample-end' and row[1] == 'Heap': print('END_SAMPLE %.2f' % sample_time) sampling = False elif row[0] == itemname and sampling: print(row[1]), if options.count: print('%d' % (int(row[2]))), if options.size: print('%d' % (int(row[3]))), print finally: logfile.close() except: sys.exit('can\'t open %s' % filename) def BuildOptions(): result = optparse.OptionParser() result.add_option("--js_cons_profile", help="Constructor profile", default=False, action="store_true") result.add_option("--size", help="Report object size", default=False, action="store_true") result.add_option("--count", help="Report object count", default=False, action="store_true") return result def ProcessOptions(options): if not options.size and not options.count: options.size = True return True def Main(): parser = BuildOptions() (options, args) = parser.parse_args() if not ProcessOptions(options): parser.print_help() sys.exit(); if not args: print "Missing logfile" sys.exit(); ProcessLogFile(args[0], options) if __name__ == '__main__': sys.exit(Main()) import matplotlib.pyplot as plt import numpy as np from sklearn.svm import SVC from sklearn.datasets import make_blobs from .plot_2d_separator import plot_2d_separator def make_handcrafted_dataset(): # a carefully hand-designed dataset lol X, y = make_blobs(centers=2, random_state=4, n_samples=30) y[np.array([7, 27])] = 0 mask = np.ones(len(X), dtype=np.bool) mask[np.array([0, 1, 5, 26])] = 0 X, y = X[mask], y[mask] return X, y def plot_rbf_svm_parameters(): X, y = make_handcrafted_dataset() fig, axes = plt.subplots(1, 3, figsize=(12, 4)) for ax, C in zip(axes, [1e0, 5, 10, 100]): ax.scatter(X[:, 0], X[:, 1], s=150, c=np.array(['red', 'blue'])[y]) svm = SVC(kernel='rbf', C=C).fit(X, y) plot_2d_separator(svm, X, ax=ax, eps=.5) ax.set_title("C = %f" % C) fig, axes = plt.subplots(1, 4, figsize=(15, 3)) for ax, gamma in zip(axes, [0.1, .5, 1, 10]): ax.scatter(X[:, 0], X[:, 1], s=150, c=np.array(['red', 'blue'])[y]) svm = SVC(gamma=gamma, kernel='rbf', C=1).fit(X, y) plot_2d_separator(svm, X, ax=ax, eps=.5) ax.set_title("gamma = %f" % gamma) def plot_svm(log_C, log_gamma): X, y = make_handcrafted_dataset() C = 10. ** log_C gamma = 10. ** log_gamma svm = SVC(kernel='rbf', C=C, gamma=gamma).fit(X, y) ax = plt.gca() plot_2d_separator(svm, X, ax=ax, eps=.5) # plot data ax.scatter(X[:, 0], X[:, 1], s=150, c=np.array(['red', 'blue'])[y]) # plot support vectors sv = svm.support_vectors_ ax.scatter(sv[:, 0], sv[:, 1], s=230, facecolors='none', zorder=10, linewidth=3) ax.set_title("C = %.4f gamma = %.4f" % (C, gamma)) def plot_svm_interactive(): from IPython.html.widgets import interactive, FloatSlider C_slider = FloatSlider(min=-3, max=3, step=.1, value=0, readout=False) gamma_slider = FloatSlider(min=-2, max=2, step=.1, value=0, readout=False) return interactive(plot_svm, log_C=C_slider, log_gamma=gamma_slider) # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not 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. # import datetime import unittest import mock from airflow import DAG from airflow.providers.microsoft.azure.operators.file_to_wasb import FileToWasbOperator class TestFileToWasbOperator(unittest.TestCase): _config = { 'file_path': 'file', 'container_name': 'container', 'blob_name': 'blob', 'wasb_conn_id': 'wasb_default', 'retries': 3, } def setUp(self): args = { 'owner': 'airflow', 'start_date': datetime.datetime(2017, 1, 1) } self.dag = DAG('test_dag_id', default_args=args) def test_init(self): operator = FileToWasbOperator( task_id='wasb_operator', dag=self.dag, **self._config ) self.assertEqual(operator.file_path, self._config['file_path']) self.assertEqual(operator.container_name, self._config['container_name']) self.assertEqual(operator.blob_name, self._config['blob_name']) self.assertEqual(operator.wasb_conn_id, self._config['wasb_conn_id']) self.assertEqual(operator.load_options, {}) self.assertEqual(operator.retries, self._config['retries']) operator = FileToWasbOperator( task_id='wasb_operator', dag=self.dag, load_options={'timeout': 2}, **self._config ) self.assertEqual(operator.load_options, {'timeout': 2}) @mock.patch('airflow.providers.microsoft.azure.operators.file_to_wasb.WasbHook', autospec=True) def test_execute(self, mock_hook): mock_instance = mock_hook.return_value operator = FileToWasbOperator( task_id='wasb_sensor', dag=self.dag, load_options={'timeout': 2}, **self._config ) operator.execute(None) mock_instance.load_file.assert_called_once_with( 'file', 'container', 'blob', timeout=2 ) if __name__ == '__main__': unittest.main() ''' Copyright (C) 2013-2015 xtr4nge [_AT_] gmail.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 . ''' import requests from requests import session from consoleMessages import ConsoleMessages requests.packages.urllib3.disable_warnings() # DISABLE SSL CHECK WARNINGS class Webclient: def __init__(self, config): self.consoleMessages = ConsoleMessages() self.server = config.get("api","server") self.token = config.get("api","token") self.global_webserver = self.server self.path = "/modules/api/includes/ws_action.php" self.s = requests.session() self.token = self.token try: self.login() self.loginCheck() self.consoleMessages.show_msg("Session established. Have fun ;)") except: self.consoleMessages.show_error("The session cannot be established. Check the connection details.") def login(self): payload = { 'action': 'login', 'token': self.token } self.s = requests.session() self.s.get(self.global_webserver, verify=False) # DISABLE SSL CHECK self.s.post(self.global_webserver + '/login.php', data=payload) def loginCheck(self): response = self.s.get(self.global_webserver + '/login_check.php') if response.text != "": self.login() if response.text != "": self.consoleMessages.show_error("Ah, Ah, Ah! You didn't say the magic word!") sys.exit() return True def submitPost(self, data): response = self.s.post(self.global_webserver + data) return response.json if response.text == "": return True else: return False def call_api(self, execute): out = self.submitGet("api=" + str(execute)) try: return out.json() except: pass def submitGet(self, data): response = self.s.get(self.global_webserver + self.path + "?" + data) return response from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( int_or_none, remove_end, unified_strdate, ) class NDTVIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?ndtv\.com/video/(?:[^/]+/)+[^/?^&]+-(?P\d+)' _TEST = { 'url': 'http://www.ndtv.com/video/news/news/ndtv-exclusive-don-t-need-character-certificate-from-rahul-gandhi-says-arvind-kejriwal-300710', 'md5': '39f992dbe5fb531c395d8bbedb1e5e88', 'info_dict': { 'id': '300710', 'ext': 'mp4', 'title': "NDTV exclusive: Don't need character certificate from Rahul Gandhi, says Arvind Kejriwal", 'description': 'md5:ab2d4b4a6056c5cb4caa6d729deabf02', 'upload_date': '20131208', 'duration': 1327, 'thumbnail': r're:https?://.*\.jpg', }, } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) title = remove_end(self._og_search_title(webpage), ' - NDTV') filename = self._search_regex( r"__filename='([^']+)'", webpage, 'video filename') video_url = 'http://bitcast-b.bitgravity.com/ndtvod/23372/ndtv/%s' % filename duration = int_or_none(self._search_regex( r"__duration='([^']+)'", webpage, 'duration', fatal=False)) upload_date = unified_strdate(self._html_search_meta( 'publish-date', webpage, 'upload date', fatal=False)) description = remove_end(self._og_search_description(webpage), ' (Read more)') return { 'id': video_id, 'url': video_url, 'title': title, 'description': description, 'thumbnail': self._og_search_thumbnail(webpage), 'duration': duration, 'upload_date': upload_date, } # -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## from openerp import SUPERUSER_ID from openerp.osv import fields, osv class document_page_create_menu(osv.osv_memory): """ Create Menu """ _name = "document.page.create.menu" _description = "Wizard Create Menu" _columns = { 'menu_name': fields.char('Menu Name', size=256, required=True), 'menu_parent_id': fields.many2one('ir.ui.menu', 'Parent Menu', required=True), } def default_get(self, cr, uid, fields, context=None): if context is None: context = {} res = super(document_page_create_menu,self).default_get(cr, uid, fields, context=context) page_id = context.get('active_id') obj_page = self.pool.get('document.page') page = obj_page.browse(cr, uid, page_id, context=context) res['menu_name'] = page.name return res def document_page_menu_create(self, cr, uid, ids, context=None): if context is None: context = {} obj_page = self.pool.get('document.page') obj_view = self.pool.get('ir.ui.view') obj_menu = self.pool.get('ir.ui.menu') obj_action = self.pool.get('ir.actions.act_window') page_id = context.get('active_id', False) page = obj_page.browse(cr, uid, page_id, context=context) datas = self.browse(cr, uid, ids, context=context) data = False if datas: data = datas[0] if not data: return {} value = { 'name': 'Document Page', 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'document.page', 'view_id': False, 'type': 'ir.actions.act_window', 'target': 'inlineview', } value['domain'] = "[('parent_id','=',%d)]" % (page.id) value['res_id'] = page.id action_id = obj_action.create(cr, uid, value) # only the super user is allowed to create menu due to security rules on ir.values menu_id = obj_menu.create(cr, SUPERUSER_ID, { 'name': data.menu_name, 'parent_id':data.menu_parent_id.id, 'icon': 'STOCK_DIALOG_QUESTION', 'action': 'ir.actions.act_window,'+ str(action_id), }, context) obj_page.write(cr, uid, [page_id], {'menu_id':menu_id}) return { 'type': 'ir.actions.client', 'tag': 'reload', } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: import os from shutil import copyfile import threading from sft.runner.Runner import Runner class Trainer(Runner): def run(self, experiment, threaded=False): world_config = self.get_world_config(experiment) scenarios = self.init_scenarios(world_config) nb_agent_runs = max(1, world_config.nb_agent_runs) self.copy_agent_configs(experiment, nb_agent_runs) agent_configs = self.get_agent_configs(experiment) # generate distinct seeds for every agent copy and repeat this list for every distinct agent seeds = self.gen_seeds(nb_agent_runs) * (len(agent_configs) / nb_agent_runs) self.run_agents(world_config, agent_configs, scenarios, seeds, threaded) self.reset_agent_configs(experiment) def get_agent_dir(self, exp_module): exp_path = exp_module.__file__ # check if running from .pyc file and change path to .py if exp_path.endswith("pyc"): exp_path = exp_path[:-1] return exp_path[:-len("__init__.py")] + "agents" def get_agent_files(self, exp_module): agent_dir = self.get_agent_dir(exp_module) return [agent_dir + "/" + a for a in os.listdir(agent_dir) if a != "__init__.py" and not a.endswith("pyc")] # [:-3] to remove ".py" def copy_agent_configs(self, exp_module, nb_action_runs): agent_files = self.get_agent_files(exp_module) # create nb_action_runs instances of every agent for agent_file in agent_files: # copy agent files for i in range(1, nb_action_runs): copyfile(agent_file, "%s_%d.py" % (agent_file[:-3], i)) # for the first instance just rename the original file os.rename(agent_file, agent_file[:-3] + "_0.py") def reset_agent_configs(self, exp_module): agent_files = self.get_agent_files(exp_module) for agent_file in agent_files: if agent_file.endswith("_0.py"): os.rename(agent_file, agent_file[:-5] + ".py") else: os.remove(agent_file) # also delete .pyc files agent_dir = self.get_agent_dir(exp_module) for f in os.listdir(agent_dir): if f.endswith("pyc"): os.remove(agent_dir + "/" + f) def run_agents(self, world_config, agent_configs, scenarios, seeds, threaded): if threaded: threads = [] for agent in agent_configs: thread = threading.Thread(target=self.run_agent, args=(agent, scenarios)) thread.daemon = False thread.start() threads.append(thread) for t in threads: t.join() else: for agent, seed in zip(agent_configs, seeds): self.run_agent(agent, scenarios, seed) world_config.world_logger.close_files() def init_scenarios(self, world_config): seed = self.set_seed() world_config.world_logger.log_message("Using seed %s for initializing scenarios" % str(seed)) scenarios = [] for n in range(world_config.epochs): scenario = world_config.world_gen.get_next() scenarios.append(scenario) world_config.sampler.next_epoch() world_config.world_logger.log_init_state_and_world(scenario.world, scenario.pos) world_config.world_logger.next_epoch() return scenarios def _get_eps(self, config, epoch): eps = config.epsilon_update.get_value(epoch) return eps def _incorp_agent_reward(self, agent, state, action, state2, reward_value): agent.incorporate_reward(state, action, state2, reward_value) #!/usr/bin/python # -*- coding: utf-8 -*- """ ======================================================================== Gaussian Processes regression: goodness-of-fit on the 'diabetes' dataset ======================================================================== In this example, we fit a Gaussian Process model onto the diabetes dataset. We determine the correlation parameters with maximum likelihood estimation (MLE). We use an anisotropic squared exponential correlation model with a constant regression model. We also use a nugget of 1e-2 to account for the (strong) noise in the targets. We compute a cross-validation estimate of the coefficient of determination (R2) without reperforming MLE, using the set of correlation parameters found on the whole dataset. """ print(__doc__) # Author: Vincent Dubourg # Licence: BSD 3 clause from sklearn import datasets from sklearn.gaussian_process import GaussianProcess from sklearn.cross_validation import cross_val_score, KFold # Load the dataset from scikit's data sets diabetes = datasets.load_diabetes() X, y = diabetes.data, diabetes.target # Instanciate a GP model gp = GaussianProcess(regr='constant', corr='absolute_exponential', theta0=[1e-4] * 10, thetaL=[1e-12] * 10, thetaU=[1e-2] * 10, nugget=1e-2, optimizer='Welch') # Fit the GP model to the data performing maximum likelihood estimation gp.fit(X, y) # Deactivate maximum likelihood estimation for the cross-validation loop gp.theta0 = gp.theta_ # Given correlation parameter = MLE gp.thetaL, gp.thetaU = None, None # None bounds deactivate MLE # Perform a cross-validation estimate of the coefficient of determination using # the cross_validation module using all CPUs available on the machine K = 20 # folds R2 = cross_val_score(gp, X, y=y, cv=KFold(y.size, K), n_jobs=1).mean() print("The %d-Folds estimate of the coefficient of determination is R2 = %s" % (K, R2)) # Copyright (C) 2007 Joe Gregorio # # Licensed under the MIT License """MIME-Type Parser This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents: - parse_mime_type(): Parses a mime-type into its component parts. - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter. - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges. - quality_parsed(): Just like quality() except the second parameter must be pre-parsed. - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates. """ __version__ = '0.1.3' __author__ = 'Joe Gregorio' __email__ = 'joe@bitworking.org' __license__ = 'MIT License' __credits__ = '' def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) """ parts = mime_type.split(';') params = dict([tuple([s.strip() for s in param.split('=', 1)])\ for param in parts[1:] ]) full_type = parts[0].strip() # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' (type, subtype) = full_type.split('/') return (type.strip(), subtype.strip(), params) def parse_media_range(range): """Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q', '0.5'}) In addition this function also guarantees that there is a value for 'q' in the params dictionary, filling it in with a proper default if necessary. """ (type, subtype, params) = parse_mime_type(range) if not params.has_key('q') or not params['q'] or \ not float(params['q']) or float(params['q']) > 1\ or float(params['q']) < 0: params['q'] = '1' return (type, subtype, params) def fitness_and_quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges. """ best_fitness = -1 best_fit_q = 0 (target_type, target_subtype, target_params) =\ parse_media_range(mime_type) for (type, subtype, params) in parsed_ranges: type_match = (type == target_type or\ type == '*' or\ target_type == '*') subtype_match = (subtype == target_subtype or\ subtype == '*' or\ target_subtype == '*') if type_match and subtype_match: param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \ target_params.iteritems() if key != 'q' and \ params.has_key(key) and value == params[key]], 0) fitness = (type == target_type) and 100 or 0 fitness += (subtype == target_subtype) and 10 or 0 fitness += param_matches if fitness > best_fitness: best_fitness = fitness best_fit_q = params['q'] return best_fitness, float(best_fit_q) def quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns the 'q' quality parameter of the best match, 0 if no match was found. This function bahaves the same as quality() except that 'parsed_ranges' must be a list of parsed media ranges. """ return fitness_and_quality_parsed(mime_type, parsed_ranges)[1] def quality(mime_type, ranges): """Return the quality ('q') of a mime-type against a list of media-ranges. Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7 """ parsed_ranges = [parse_media_range(r) for r in ranges.split(',')] return quality_parsed(mime_type, parsed_ranges) def best_match(supported, header): """Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. The list of supported mime-types should be sorted in order of increasing desirability, in case of a situation where there is a tie. >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1') 'text/xml' """ split_header = _filter_blank(header.split(',')) parsed_header = [parse_media_range(r) for r in split_header] weighted_matches = [] pos = 0 for mime_type in supported: weighted_matches.append((fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type)) pos += 1 weighted_matches.sort() return weighted_matches[-1][0][1] and weighted_matches[-1][2] or '' def _filter_blank(i): for s in i: if s.strip(): yield s # sql/functions.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """SQL function API, factories, and built-in functions. """ from . import sqltypes, schema from .base import Executable from .elements import ClauseList, Cast, Extract, _literal_as_binds, \ literal_column, _type_from_args, ColumnElement, _clone,\ Over, BindParameter from .selectable import FromClause, Select from . import operators from .visitors import VisitableType from .. import util from . import annotation _registry = util.defaultdict(dict) def register_function(identifier, fn, package="_default"): """Associate a callable with a particular func. name. This is normally called by _GenericMeta, but is also available by itself so that a non-Function construct can be associated with the :data:`.func` accessor (i.e. CAST, EXTRACT). """ reg = _registry[package] reg[identifier] = fn class FunctionElement(Executable, ColumnElement, FromClause): """Base for SQL function-oriented constructs. .. seealso:: :class:`.Function` - named SQL function. :data:`.func` - namespace which produces registered or ad-hoc :class:`.Function` instances. :class:`.GenericFunction` - allows creation of registered function types. """ packagenames = () def __init__(self, *clauses, **kwargs): """Construct a :class:`.FunctionElement`. """ args = [_literal_as_binds(c, self.name) for c in clauses] self.clause_expr = ClauseList( operator=operators.comma_op, group_contents=True, *args).\ self_group() def _execute_on_connection(self, connection, multiparams, params): return connection._execute_function(self, multiparams, params) @property def columns(self): """Fulfill the 'columns' contract of :class:`.ColumnElement`. Returns a single-element list consisting of this object. """ return [self] @util.memoized_property def clauses(self): """Return the underlying :class:`.ClauseList` which contains the arguments for this :class:`.FunctionElement`. """ return self.clause_expr.element def over(self, partition_by=None, order_by=None): """Produce an OVER clause against this function. Used against aggregate or so-called "window" functions, for database backends that support window functions. The expression:: func.row_number().over(order_by='x') is shorthand for:: from sqlalchemy import over over(func.row_number(), order_by='x') See :func:`~.expression.over` for a full description. .. versionadded:: 0.7 """ return Over(self, partition_by=partition_by, order_by=order_by) @property def _from_objects(self): return self.clauses._from_objects def get_children(self, **kwargs): return self.clause_expr, def _copy_internals(self, clone=_clone, **kw): self.clause_expr = clone(self.clause_expr, **kw) self._reset_exported() FunctionElement.clauses._reset(self) def select(self): """Produce a :func:`~.expression.select` construct against this :class:`.FunctionElement`. This is shorthand for:: s = select([function_element]) """ s = Select([self]) if self._execution_options: s = s.execution_options(**self._execution_options) return s def scalar(self): """Execute this :class:`.FunctionElement` against an embedded 'bind' and return a scalar value. This first calls :meth:`~.FunctionElement.select` to produce a SELECT construct. Note that :class:`.FunctionElement` can be passed to the :meth:`.Connectable.scalar` method of :class:`.Connection` or :class:`.Engine`. """ return self.select().execute().scalar() def execute(self): """Execute this :class:`.FunctionElement` against an embedded 'bind'. This first calls :meth:`~.FunctionElement.select` to produce a SELECT construct. Note that :class:`.FunctionElement` can be passed to the :meth:`.Connectable.execute` method of :class:`.Connection` or :class:`.Engine`. """ return self.select().execute() def _bind_param(self, operator, obj): return BindParameter(None, obj, _compared_to_operator=operator, _compared_to_type=self.type, unique=True) class _FunctionGenerator(object): """Generate :class:`.Function` objects based on getattr calls.""" def __init__(self, **opts): self.__names = [] self.opts = opts def __getattr__(self, name): # passthru __ attributes; fixes pydoc if name.startswith('__'): try: return self.__dict__[name] except KeyError: raise AttributeError(name) elif name.endswith('_'): name = name[0:-1] f = _FunctionGenerator(**self.opts) f.__names = list(self.__names) + [name] return f def __call__(self, *c, **kwargs): o = self.opts.copy() o.update(kwargs) tokens = len(self.__names) if tokens == 2: package, fname = self.__names elif tokens == 1: package, fname = "_default", self.__names[0] else: package = None if package is not None: func = _registry[package].get(fname) if func is not None: return func(*c, **o) return Function(self.__names[-1], packagenames=self.__names[0:-1], *c, **o) func = _FunctionGenerator() """Generate SQL function expressions. :data:`.func` is a special object instance which generates SQL functions based on name-based attributes, e.g.:: >>> print func.count(1) count(:param_1) The element is a column-oriented SQL element like any other, and is used in that way:: >>> print select([func.count(table.c.id)]) SELECT count(sometable.id) FROM sometable Any name can be given to :data:`.func`. If the function name is unknown to SQLAlchemy, it will be rendered exactly as is. For common SQL functions which SQLAlchemy is aware of, the name may be interpreted as a *generic function* which will be compiled appropriately to the target database:: >>> print func.current_timestamp() CURRENT_TIMESTAMP To call functions which are present in dot-separated packages, specify them in the same manner:: >>> print func.stats.yield_curve(5, 10) stats.yield_curve(:yield_curve_1, :yield_curve_2) SQLAlchemy can be made aware of the return type of functions to enable type-specific lexical and result-based behavior. For example, to ensure that a string-based function returns a Unicode value and is similarly treated as a string in expressions, specify :class:`~sqlalchemy.types.Unicode` as the type: >>> print func.my_string(u'hi', type_=Unicode) + ' ' + \ ... func.my_string(u'there', type_=Unicode) my_string(:my_string_1) || :my_string_2 || my_string(:my_string_3) The object returned by a :data:`.func` call is usually an instance of :class:`.Function`. This object meets the "column" interface, including comparison and labeling functions. The object can also be passed the :meth:`~.Connectable.execute` method of a :class:`.Connection` or :class:`.Engine`, where it will be wrapped inside of a SELECT statement first:: print connection.execute(func.current_timestamp()).scalar() In a few exception cases, the :data:`.func` accessor will redirect a name to a built-in expression such as :func:`.cast` or :func:`.extract`, as these names have well-known meaning but are not exactly the same as "functions" from a SQLAlchemy perspective. .. versionadded:: 0.8 :data:`.func` can return non-function expression constructs for common quasi-functional names like :func:`.cast` and :func:`.extract`. Functions which are interpreted as "generic" functions know how to calculate their return type automatically. For a listing of known generic functions, see :ref:`generic_functions`. """ modifier = _FunctionGenerator(group=False) class Function(FunctionElement): """Describe a named SQL function. See the superclass :class:`.FunctionElement` for a description of public methods. .. seealso:: :data:`.func` - namespace which produces registered or ad-hoc :class:`.Function` instances. :class:`.GenericFunction` - allows creation of registered function types. """ __visit_name__ = 'function' def __init__(self, name, *clauses, **kw): """Construct a :class:`.Function`. The :data:`.func` construct is normally used to construct new :class:`.Function` instances. """ self.packagenames = kw.pop('packagenames', None) or [] self.name = name self._bind = kw.get('bind', None) self.type = sqltypes.to_instance(kw.get('type_', None)) FunctionElement.__init__(self, *clauses, **kw) def _bind_param(self, operator, obj): return BindParameter(self.name, obj, _compared_to_operator=operator, _compared_to_type=self.type, unique=True) class _GenericMeta(VisitableType): def __init__(cls, clsname, bases, clsdict): if annotation.Annotated not in cls.__mro__: cls.name = name = clsdict.get('name', clsname) cls.identifier = identifier = clsdict.get('identifier', name) package = clsdict.pop('package', '_default') # legacy if '__return_type__' in clsdict: cls.type = clsdict['__return_type__'] register_function(identifier, cls, package) super(_GenericMeta, cls).__init__(clsname, bases, clsdict) class GenericFunction(util.with_metaclass(_GenericMeta, Function)): """Define a 'generic' function. A generic function is a pre-established :class:`.Function` class that is instantiated automatically when called by name from the :data:`.func` attribute. Note that calling any name from :data:`.func` has the effect that a new :class:`.Function` instance is created automatically, given that name. The primary use case for defining a :class:`.GenericFunction` class is so that a function of a particular name may be given a fixed return type. It can also include custom argument parsing schemes as well as additional methods. Subclasses of :class:`.GenericFunction` are automatically registered under the name of the class. For example, a user-defined function ``as_utc()`` would be available immediately:: from sqlalchemy.sql.functions import GenericFunction from sqlalchemy.types import DateTime class as_utc(GenericFunction): type = DateTime print select([func.as_utc()]) User-defined generic functions can be organized into packages by specifying the "package" attribute when defining :class:`.GenericFunction`. Third party libraries containing many functions may want to use this in order to avoid name conflicts with other systems. For example, if our ``as_utc()`` function were part of a package "time":: class as_utc(GenericFunction): type = DateTime package = "time" The above function would be available from :data:`.func` using the package name ``time``:: print select([func.time.as_utc()]) A final option is to allow the function to be accessed from one name in :data:`.func` but to render as a different name. The ``identifier`` attribute will override the name used to access the function as loaded from :data:`.func`, but will retain the usage of ``name`` as the rendered name:: class GeoBuffer(GenericFunction): type = Geometry package = "geo" name = "ST_Buffer" identifier = "buffer" The above function will render as follows:: >>> print func.geo.buffer() ST_Buffer() .. versionadded:: 0.8 :class:`.GenericFunction` now supports automatic registration of new functions as well as package and custom naming support. .. versionchanged:: 0.8 The attribute name ``type`` is used to specify the function's return type at the class level. Previously, the name ``__return_type__`` was used. This name is still recognized for backwards-compatibility. """ coerce_arguments = True def __init__(self, *args, **kwargs): parsed_args = kwargs.pop('_parsed_args', None) if parsed_args is None: parsed_args = [_literal_as_binds(c) for c in args] self.packagenames = [] self._bind = kwargs.get('bind', None) self.clause_expr = ClauseList( operator=operators.comma_op, group_contents=True, *parsed_args).self_group() self.type = sqltypes.to_instance( kwargs.pop("type_", None) or getattr(self, 'type', None)) register_function("cast", Cast) register_function("extract", Extract) class next_value(GenericFunction): """Represent the 'next value', given a :class:`.Sequence` as it's single argument. Compiles into the appropriate function on each backend, or will raise NotImplementedError if used on a backend that does not provide support for sequences. """ type = sqltypes.Integer() name = "next_value" def __init__(self, seq, **kw): assert isinstance(seq, schema.Sequence), \ "next_value() accepts a Sequence object as input." self._bind = kw.get('bind', None) self.sequence = seq @property def _from_objects(self): return [] class AnsiFunction(GenericFunction): def __init__(self, **kwargs): GenericFunction.__init__(self, **kwargs) class ReturnTypeFromArgs(GenericFunction): """Define a function whose return type is the same as its arguments.""" def __init__(self, *args, **kwargs): args = [_literal_as_binds(c) for c in args] kwargs.setdefault('type_', _type_from_args(args)) kwargs['_parsed_args'] = args GenericFunction.__init__(self, *args, **kwargs) class coalesce(ReturnTypeFromArgs): pass class max(ReturnTypeFromArgs): pass class min(ReturnTypeFromArgs): pass class sum(ReturnTypeFromArgs): pass class now(GenericFunction): type = sqltypes.DateTime class concat(GenericFunction): type = sqltypes.String class char_length(GenericFunction): type = sqltypes.Integer def __init__(self, arg, **kwargs): GenericFunction.__init__(self, arg, **kwargs) class random(GenericFunction): pass class count(GenericFunction): """The ANSI COUNT aggregate function. With no arguments, emits COUNT \*. """ type = sqltypes.Integer def __init__(self, expression=None, **kwargs): if expression is None: expression = literal_column('*') GenericFunction.__init__(self, expression, **kwargs) class current_date(AnsiFunction): type = sqltypes.Date class current_time(AnsiFunction): type = sqltypes.Time class current_timestamp(AnsiFunction): type = sqltypes.DateTime class current_user(AnsiFunction): type = sqltypes.String class localtime(AnsiFunction): type = sqltypes.DateTime class localtimestamp(AnsiFunction): type = sqltypes.DateTime class session_user(AnsiFunction): type = sqltypes.String class sysdate(AnsiFunction): type = sqltypes.DateTime class user(AnsiFunction): type = sqltypes.String # Copyright 2015 Cloudbase Solutions Srl # 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. import abc import six @six.add_metaclass(abc.ABCMeta) class BaseActionManager(object): """Get a Action Manager that can handle basic actions. :param client: A Windows client to send command to the instance. :param conf: Argus config options. """ def __init__(self, client, conf, os_type): self._client = client self._os_type = os_type self._conf = conf @abc.abstractmethod def download(self, uri, location): """Download the resource locatet at a specific uri in the location. :param uri: Remote url where the data is found. :param location: Path from the instance in which we should download the remote resouce. """ pass @abc.abstractmethod def get_installation_script(self): """Get instalation script for CloudbaseInit.""" pass @abc.abstractmethod def install_cbinit(self, service_type): """Install CloudBase-Init. :param service_type: The metadata service type. It can be: http, ec2, configdrive, opennebula, cloudstack and mass. This parameter will dictate what config option is put in cloubase-init.conf. """ pass @abc.abstractmethod def sysprep(self): """Run the sysprep.""" pass @abc.abstractmethod def wait_cbinit_service(self): """Wait if the CloudBase Init Service to stop.""" pass @abc.abstractmethod def check_cbinit_service(self, searched_paths=None): """Check if the CloudBase Init service started. :param searched_paths: Paths to files that should exist if the hearbeat patch is aplied. """ pass @abc.abstractmethod def git_clone(self, repo_url, location): """Clone from an remote repo to a specific location on the instance. :param repo_url: The remote repo url. :param location: Specific location on the instance. """ pass @abc.abstractmethod def wait_boot_completion(self): """Wait for the instance to be booted a resonable period.""" pass @abc.abstractmethod def specific_prepare(self): """Prepare some OS specific resources.""" pass from nose.plugins.attrib import attr from perfpoint import * import numpy as np sample_counters = [ (4, '00c0', 'instructions'), ] @docstring_name def check_data_shape(data, interval): '''Check that align produces any data at all''' assert len(data.shape)==2, 'Wrong dimensionality in data' assert data.shape[0]>5, 'Insufficient rows in data' assert data.shape[1]==len(sample_counters)+1, 'Insufficient columns in data' @docstring_name def check_data_values(data, interval): '''Check for ridiculous values in the data''' assert np.all(data>=0), 'Negative values found in data' for (c,counter_tuple) in enumerate(sample_counters):#xrange(1,data.shape[1]+1): assert np.count_nonzero(data[:,c+1])>5, 'Mostly zero data found in column '+str(c+1)+': '+str(counter_tuple) @attr('check','align') def test_alignment_checks(): interval = 1000000 align = Alignment(ipoint_interval=interval, argv=[compute]) for counter in sample_counters: align.add_counter(*counter) data = align.run() # Run several different diagnostics yield (check_data_shape, data, interval) yield (check_data_values, data, interval) @attr('check','align') @docstring_name def test_ragged_truncate(): '''Check that we can truncate ragged arrays''' data=[ np.vstack([ np.arange(1,100), np.arange(1,100) ]).T, np.vstack([ np.arange(1,200), np.arange(1,200) ]).T ] new = align.align_truncated(data,1) assert new.shape==(99,3), 'align_truncated didnt truncate correctly' assert np.all(new[:,1]==new[:,2]), 'align_truncated didnt align the data' @attr('check','align') @docstring_name def test_ragged_scaled(): '''Check that we can scale ragged arrays''' data=[ np.vstack([ np.arange(1,100), np.arange(1,100) ]).T, np.vstack([ np.arange(3,300), np.arange(3,300) ]).T ] new = align.align_scaled(data,2) assert new.shape==(99,3), 'align_scaled didnt scale correctly' assert np.all(new[:,1]==new[:,2]), 'align_scaled didnt align the data' @attr('check','align') @docstring_name def test_smoothing(): '''Check oversample smoothing''' trace = np.vstack([ np.arange(1,100), np.arange(1,100) ]).T overtrace = np.empty(trace.shape) overtrace[:,0] = trace[:,0] # "oversample" 8x for i in xrange(0,99): if i&7: overtrace[i,1] = trace[i&(~7),1] else: overtrace[i,1] = trace[i,1] # now correct it back overtrace = align.correct_for_oversampling(overtrace) recovered = trace[:-10]==overtrace[:-10] # the last bit isn't recovered assert np.all(recovered), 'Oversample smoothing didnt recover original samples:\n'+str(np.dstack([trace[~recovered],overtrace[~recovered]])) #@attr('stats') #def test_alignment_checks(): # interval = 1000000 # align = Alignment(ipoint_interval=interval, argv=[compute] # for counter in sample_counters: # align.add_counter(*counter) # data = align.run() # # Run several different diagnostics # yield (check_data, data, interval) # The MIT License (MIT) # # Copyright (c) 2014 Richard Moore # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # Why to_bufferable? # Python 3 is very different from Python 2.x when it comes to strings of text # and strings of bytes; in Python 3, strings of bytes do not exist, instead to # represent arbitrary binary data, we must use the "bytes" object. This method # ensures the object behaves as we need it to. def to_bufferable(binary): return binary def _get_byte(c): return ord(c) try: xrange except: def to_bufferable(binary): if isinstance(binary, bytes): return binary return bytes(ord(b) for b in binary) def _get_byte(c): return c def append_PKCS7_padding(data): pad = 16 - (len(data) % 16) return data + to_bufferable(chr(pad) * pad) def strip_PKCS7_padding(data): if len(data) % 16 != 0: raise ValueError("invalid length") pad = _get_byte(data[-1]) if pad > 16: raise ValueError("invalid padding byte") return data[:-pad] import os import unittest import sys sys.path.append('../') import ship import tempfile class shipTestCase(unittest.TestCase): def setUp(self): self.db_fd, ship.app.config['DATABASE'] = tempfile.mkstemp() ship.app.config['TESTING'] = True self.app = ship.app.test_client() ship.init_db() def tearDown(self): os.close(self.db_fd) os.unlink(ship.app.config['DATABASE']) def test_add_delivery(self): """ Test the delivery display """ body = self.app.post('/add', data={ 'tracking': '10001', 'carrier': 'UPS', 'street_address': 'John Doe, Beverly Hills, CA', 'zipcode': '90069' }, follow_redirects=True) assert 'Delivery added' in body.data body = self.app.post('/add', data={ 'tracking': '', 'carrier': 'UPS', 'street_address': 'John Doe, Beverly Hills, CA', 'zipcode': '90069' }, follow_redirects=True) assert 'Invalid tracking ID' in body.data body = self.app.post('/add', data={ 'tracking': '10001', 'carrier': 'UPS', 'street_address': '', 'zipcode': '90069' }, follow_redirects=True) assert 'Invalid street address' in body.data body = self.app.post('/add', data={ 'tracking': '10001', 'carrier': 'UPS', 'street_address': 'John Doe, Beverly Hills, CA', 'zipcode': '' }, follow_redirects=True) assert 'Invalid zipcode' in body.data body = self.app.post('/add', data={ 'tracking': '10001', 'carrier': 'UPS', 'street_address': 'John Doe, Beverly Hills, CA', 'zipcode': '9006' }, follow_redirects=True) assert 'Invalid zipcode' in body.data body = self.app.post('/add', data={ 'tracking': '', 'carrier': '', 'street_address': '', 'zipcode': '' }, follow_redirects=True) assert 'Invalid tracking ID, street address, zipcode, carrier' in body.data def test_show_deliveries(self): """ Test home page """ body = self.app.get('/') assert 'Shipping Time' in body.data self.app.post('/add', data={ 'tracking': '10001', 'carrier': 'UPS', 'street_address': 'John Doe, Beverly Hills, CA', 'zipcode': '90069' }, follow_redirects=True) self.app.post('/add', data={ 'tracking': '10002', 'carrier': 'FedEx', 'street_address': 'Jane Doe, West Hollywood, CA', 'zipcode': '90059' }, follow_redirects=True) body = self.app.get('/') assert '10001' in body.data assert 'UPS' in body.data assert 'John Doe' in body.data assert '90069' in body.data assert '10002' in body.data assert 'FedEx' in body.data assert 'Jane Doe' in body.data assert '90059' in body.data def test_assert_valid_entries(self): result = ship.assert_valid_entries('', 'abc', '90009', 'USPS') assert 'tracking ID' in result result = ship.assert_valid_entries('10001', '', '90009', 'USPS') assert 'street address' in result result = ship.assert_valid_entries('10001', 'abc', 'xyz', 'USPS') assert 'zipcode' in result result = ship.assert_valid_entries('10001', 'abc', '', 'USPS') assert 'zipcode' in result result = ship.assert_valid_entries('10001', 'abc', 'xyz', '') assert 'carrier' in result result = ship.assert_valid_entries('', 'abc', 'xyz', '') assert 'tracking ID, zipcode, carrier' in result result = ship.assert_valid_entries('', '', '', '') assert 'tracking ID, street address, zipcode, carrier' in result if __name__ == '__main__': unittest.main() # Copyright (c) 2012-2015 Netforce Co. Ltd. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE 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 SOFTWARE OR THE USE # OR OTHER DEALINGS IN THE SOFTWARE. from netforce.model import Model, fields class VariantValue(Model): _name = "product.variant.values" _transient = True _fields = { "popup_id": fields.Many2One("prod.create.variants", "Popup", required=True, on_delete="cascade"), "attribute_id": fields.Many2One("product.attribute", "Attribute", required=True), "values": fields.Many2Many("product.attribute.option", "Values", required=True), } VariantValue.register() # Copyright 2013 Intel Corp. # # 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 webob import exc from nova.api.openstack.compute import pci from nova.api.openstack import wsgi from nova import context from nova import exception from nova import objects from nova.objects import fields from nova.objects import pci_device_pool from nova import test from nova.tests.unit.api.openstack import fakes from nova.tests.unit.objects import test_pci_device from nova.tests import uuidsentinel as uuids pci_stats = [{"count": 3, "vendor_id": "8086", "product_id": "1520", "numa_node": 1}] fake_compute_node = objects.ComputeNode( pci_device_pools=pci_device_pool.from_pci_stats(pci_stats)) class FakeResponse(wsgi.ResponseObject): pass class PciServerControllerTestV21(test.NoDBTestCase): def setUp(self): super(PciServerControllerTestV21, self).setUp() self.controller = pci.PciServerController() self.fake_obj = {'server': {'addresses': {}, 'id': 'fb08', 'name': 'a3', 'status': 'ACTIVE', 'tenant_id': '9a3af784c', 'user_id': 'e992080ac0', }} self.fake_list = {'servers': [{'addresses': {}, 'id': 'fb08', 'name': 'a3', 'status': 'ACTIVE', 'tenant_id': '9a3af784c', 'user_id': 'e992080ac', }]} self._create_fake_instance() self._create_fake_pci_device() self.pci_device.claim(self.inst.uuid) self.pci_device.allocate(self.inst) def _create_fake_instance(self): self.inst = objects.Instance() self.inst.uuid = uuids.instance self.inst.pci_devices = objects.PciDeviceList() def _create_fake_pci_device(self): def fake_pci_device_get_by_addr(ctxt, id, addr): return test_pci_device.fake_db_dev ctxt = context.get_admin_context() self.stub_out('nova.db.pci_device_get_by_addr', fake_pci_device_get_by_addr) self.pci_device = objects.PciDevice.get_by_dev_addr(ctxt, 1, 'a') def test_show(self): def fake_get_db_instance(id): return self.inst resp = FakeResponse(self.fake_obj, '') req = fakes.HTTPRequest.blank('/os-pci/1', use_admin_context=True) self.stubs.Set(req, 'get_db_instance', fake_get_db_instance) self.controller.show(req, resp, '1') self.assertEqual([{'id': 1}], resp.obj['server']['os-pci:pci_devices']) def test_detail(self): def fake_get_db_instance(id): return self.inst resp = FakeResponse(self.fake_list, '') req = fakes.HTTPRequest.blank('/os-pci/detail', use_admin_context=True) self.stubs.Set(req, 'get_db_instance', fake_get_db_instance) self.controller.detail(req, resp) self.assertEqual([{'id': 1}], resp.obj['servers'][0]['os-pci:pci_devices']) class PciHypervisorControllerTestV21(test.NoDBTestCase): def setUp(self): super(PciHypervisorControllerTestV21, self).setUp() self.controller = pci.PciHypervisorController() self.fake_objs = dict(hypervisors=[ dict(id=1, service=dict(id=1, host="compute1"), hypervisor_type="xen", hypervisor_version=3, hypervisor_hostname="hyper1")]) self.fake_obj = dict(hypervisor=dict( id=1, service=dict(id=1, host="compute1"), hypervisor_type="xen", hypervisor_version=3, hypervisor_hostname="hyper1")) def test_show(self): def fake_get_db_compute_node(id): return fake_compute_node req = fakes.HTTPRequest.blank('/os-hypervisors/1', use_admin_context=True) resp = FakeResponse(self.fake_obj, '') self.stubs.Set(req, 'get_db_compute_node', fake_get_db_compute_node) self.controller.show(req, resp, '1') self.assertIn('os-pci:pci_stats', resp.obj['hypervisor']) self.assertEqual(pci_stats[0], resp.obj['hypervisor']['os-pci:pci_stats'][0]) def test_detail(self): def fake_get_db_compute_node(id): return fake_compute_node req = fakes.HTTPRequest.blank('/os-hypervisors/detail', use_admin_context=True) resp = FakeResponse(self.fake_objs, '') self.stubs.Set(req, 'get_db_compute_node', fake_get_db_compute_node) self.controller.detail(req, resp) self.assertIn('os-pci:pci_stats', resp.obj['hypervisors'][0]) self.assertEqual(pci_stats[0], resp.obj['hypervisors'][0]['os-pci:pci_stats'][0]) class PciControlletestV21(test.NoDBTestCase): def setUp(self): super(PciControlletestV21, self).setUp() self.controller = pci.PciController() def test_show(self): def fake_pci_device_get_by_id(context, id): return test_pci_device.fake_db_dev self.stub_out('nova.db.pci_device_get_by_id', fake_pci_device_get_by_id) req = fakes.HTTPRequest.blank('/os-pci/1', use_admin_context=True) result = self.controller.show(req, '1') dist = {'pci_device': {'address': 'a', 'compute_node_id': 1, 'dev_id': 'i', 'extra_info': {}, 'dev_type': fields.PciDeviceType.STANDARD, 'id': 1, 'server_uuid': None, 'label': 'l', 'product_id': 'p', 'status': 'available', 'vendor_id': 'v'}} self.assertEqual(dist, result) def test_show_error_id(self): def fake_pci_device_get_by_id(context, id): raise exception.PciDeviceNotFoundById(id=id) self.stub_out('nova.db.pci_device_get_by_id', fake_pci_device_get_by_id) req = fakes.HTTPRequest.blank('/os-pci/0', use_admin_context=True) self.assertRaises(exc.HTTPNotFound, self.controller.show, req, '0') def _fake_compute_node_get_all(self, context): return [objects.ComputeNode(id=1, service_id=1, host='fake', cpu_info='cpu_info', disk_available_least=100)] def _fake_pci_device_get_all_by_node(self, context, node): return [test_pci_device.fake_db_dev, test_pci_device.fake_db_dev_1] def test_index(self): self.stubs.Set(self.controller.host_api, 'compute_node_get_all', self._fake_compute_node_get_all) self.stub_out('nova.db.pci_device_get_all_by_node', self._fake_pci_device_get_all_by_node) req = fakes.HTTPRequest.blank('/os-pci', use_admin_context=True) result = self.controller.index(req) dist = {'pci_devices': [test_pci_device.fake_db_dev, test_pci_device.fake_db_dev_1]} for i in range(len(result['pci_devices'])): self.assertEqual(dist['pci_devices'][i]['vendor_id'], result['pci_devices'][i]['vendor_id']) self.assertEqual(dist['pci_devices'][i]['id'], result['pci_devices'][i]['id']) self.assertEqual(dist['pci_devices'][i]['status'], result['pci_devices'][i]['status']) self.assertEqual(dist['pci_devices'][i]['address'], result['pci_devices'][i]['address']) def test_detail(self): self.stubs.Set(self.controller.host_api, 'compute_node_get_all', self._fake_compute_node_get_all) self.stub_out('nova.db.pci_device_get_all_by_node', self._fake_pci_device_get_all_by_node) req = fakes.HTTPRequest.blank('/os-pci/detail', use_admin_context=True) result = self.controller.detail(req) dist = {'pci_devices': [test_pci_device.fake_db_dev, test_pci_device.fake_db_dev_1]} for i in range(len(result['pci_devices'])): self.assertEqual(dist['pci_devices'][i]['vendor_id'], result['pci_devices'][i]['vendor_id']) self.assertEqual(dist['pci_devices'][i]['id'], result['pci_devices'][i]['id']) self.assertEqual(dist['pci_devices'][i]['label'], result['pci_devices'][i]['label']) self.assertEqual(dist['pci_devices'][i]['dev_id'], result['pci_devices'][i]['dev_id']) class PciControllerPolicyEnforcementV21(test.NoDBTestCase): def setUp(self): super(PciControllerPolicyEnforcementV21, self).setUp() self.controller = pci.PciController() self.req = fakes.HTTPRequest.blank('') def _test_policy_failed(self, action, *args): rule_name = "os_compute_api:os-pci:%s" % action rule = {rule_name: "project:non_fake"} self.policy.set_rules(rule) exc = self.assertRaises( exception.PolicyNotAuthorized, getattr(self.controller, action), self.req, *args) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message()) def test_index_policy_failed(self): self._test_policy_failed('index') def test_detail_policy_failed(self): self._test_policy_failed('detail') def test_show_policy_failed(self): self._test_policy_failed('show', 1) # Copyright (c) 2012 Cloudera, 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. # # Tests for query expiration. import pytest import threading from tests.common.custom_cluster_test_suite import CustomClusterTestSuite from tests.common.custom_cluster_test_suite import NUM_SUBSCRIBERS, CLUSTER_SIZE from time import sleep, time from tests.beeswax.impala_beeswax import ImpalaBeeswaxException class TestSessionExpiration(CustomClusterTestSuite): """Tests query expiration logic""" @pytest.mark.execute_serially @CustomClusterTestSuite.with_args("--idle_session_timeout=6") def test_session_expiration(self, vector): impalad = self.cluster.get_any_impalad() # setup_class creates an Impala client to :21000 after the cluster starts. # The client expires at the same time as the client created below. Since we choose the # impalad to connect to randomly, the test becomes flaky, as the metric we expect to # be incremented by 1 gets incremented by 2 if both clients are connected to the same # Impalad. self.client.close() num_expired = impalad.service.get_metric_value("impala-server.num-sessions-expired") client = impalad.service.create_beeswax_client() # Sleep for half the expiration time to confirm that the session is not expired early # (see IMPALA-838) sleep(3) assert num_expired == impalad.service.get_metric_value( "impala-server.num-sessions-expired") # Wait for session expiration. Session timeout was set for 6 seconds, so Impala # will poll the session expiry queue every 3 seconds. So, as long as the sleep in # ImpalaSever::ExpireSessions() is not late, the session will expire in at most 9 # seconds. The test has already waited 3 seconds. impalad.service.wait_for_metric_value( "impala-server.num-sessions-expired", num_expired + 1, 20) from .common import * # Set Roundware API for internal calls to development environment API_URL = "http://127.0.0.1:8888/roundware/" # Change banned_timeout limit to better development testing value BANNED_TIMEOUT_LIMIT = 90 # Remove possibility of demo stream to avoid confusion while testing DEMO_STREAM_CPU_LIMIT = 0.0 INSTALLED_APPS += ( 'debug_toolbar', ) DEBUG = True for TEMPLATE_SETTINGS_BLOCK in TEMPLATES: TEMPLATE_SETTINGS_BLOCK['OPTIONS']['debug'] = DEBUG DEBUG_TOOLBAR_PATCH_SETTINGS = False CRISPY_FAIL_SILENTLY = not DEBUG MIDDLEWARE_CLASSES = ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) + MIDDLEWARE_CLASSES # Bypass the INTERNAL_IPS check for Debug Toolbar class internal_list(list): def __contains__(self, key): return True INTERNAL_IPS = internal_list() # PROFILING using django-profiler PROFILING_SQL_QUERIES = True LOGGING['handlers'] = { # The console handler will display in the manage.py runserver output 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/log/roundware', 'formatter': 'verbose', }, } LOGGING['loggers'] = { # The default logger. Enable to log everything. # '': { # 'level': 'DEBUG', # 'handlers': ['console'], # }, # The Django database logger. Enable to log all SQL queries. # 'django.db.backends': { # 'level': 'DEBUG', # 'handlers': ['console'], # }, # The django-profiler logger. https://github.com/CodeScaleInc/django-profiler # 'profiling': { # 'level': 'DEBUG', # 'handlers': ['console'], # }, # The roundware system logger. 'roundware': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, # The roundwared stream manager logger. 'roundwared': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, # The Roundware API2 logger. # 'roundware.api2': { # 'level': 'DEBUG', # 'handlers': ['console'], # }, # Example logger for single file. Disable parent logger to use. # 'roundwared.stream': { # 'level': 'DEBUG', # 'handlers': ['console'], # }, } try: from .local_settings import * except ImportError: pass # -*- coding: utf-8 -*- """ @author: Fabio Erculiani @contact: lxnay@sabayon.org @copyright: Fabio Erculiani @license: GPL-2 B{Entropy Package Manager Client Core Interface}. """ import os import shutil import threading from entropy.core import Singleton from entropy.locks import EntropyResourcesLock from entropy.fetchers import UrlFetcher, MultipleUrlFetcher from entropy.output import TextInterface, bold, red, darkred, blue from entropy.qa import QAInterface from entropy.security import System, Repository as RepositorySecurity from entropy.spm.plugins.factory import get_default_instance as get_spm, \ get_default_class as get_spm_default_class from entropy.client.interfaces.db import InstalledPackagesRepository from entropy.client.interfaces.dep import CalculatorsMixin from entropy.client.interfaces.methods import RepositoryMixin, MiscMixin, \ MatchMixin from entropy.client.interfaces.package import PackageActionFactory from entropy.client.interfaces.repository import Repository from entropy.client.interfaces.settings import ClientSystemSettingsPlugin from entropy.client.interfaces.sets import Sets from entropy.client.misc import sharedinstlock, ConfigurationUpdates from entropy.client.services.interfaces import \ ClientWebServiceFactory, RepositoryWebServiceFactory from entropy.const import etpConst, const_debug_write, \ const_convert_to_unicode, const_setup_perms from entropy.core.settings.base import SystemSettings from entropy.misc import LogFile from entropy.cache import EntropyCacher from entropy.i18n import _ import entropy.dump import entropy.dep import entropy.tools class Client(Singleton, TextInterface, CalculatorsMixin, RepositoryMixin, MiscMixin, MatchMixin): def init_singleton(self, indexing = True, installed_repo = None, xcache = True, user_xcache = False, repo_validation = True, url_fetcher = None, multiple_url_fetcher = None, **kwargs): """ Entropy Client Singleton interface. Your hitchhikers' guide to the Galaxy. @keyword indexing: enable metadata indexing (default is True) @type indexing: bool @keyword installed_repo: open installed packages repository? (default is True). Accepted values: True = open, False = open but consider it not available, -1 = do not even try to open @type installed_repo: bool or int @keyword xcache: enable on-disk cache (default is True) @type xcache: bool @keyword user_xcache: enable on-disk cache even for users not in the entropy group (default is False). Dangerous, could lead to cache inconsistencies. @type user_xcache: bool @keyword repo_validation: validate all the available repositories and automatically exclude the faulty ones @type repo_validation: bool @keyword url_fetcher: override default entropy.fetchers.UrlFetcher class usage. Provide your own implementation of UrlFetcher using this argument. @type url_fetcher: class or None @keyword multiple_url_fetcher: override default entropy.fetchers.MultipleUrlFetcher class usage. Provide your own implementation of MultipleUrlFetcher using this argument. """ self.__post_acquire_hook_idx = None self.__instance_destroyed = False self._repo_error_messages_cache = set() self._repodb_cache = {} self._repodb_cache_mutex = threading.RLock() self._memory_db_instances = {} self._real_installed_repository = None self._real_installed_repository_lock = threading.RLock() self._treeupdates_repos = set() self._can_run_sys_set_hooks = False const_debug_write(__name__, "debug enabled") self.safe_mode = 0 self._indexing = indexing self._repo_validation = repo_validation self._real_cacher = None self._real_cacher_lock = threading.RLock() # setup package settings (masking and other stuff) self._real_settings = None self._real_settings_lock = threading.RLock() self._real_settings_client_plg = None self._real_settings_client_plg_lock = threading.RLock() self._real_logger = None self._real_logger_lock = threading.RLock() self._real_enabled_repos = None self._real_enabled_repos_lock = threading.RLock() self._multiple_url_fetcher = multiple_url_fetcher self._url_fetcher = url_fetcher if url_fetcher is None: self._url_fetcher = UrlFetcher if multiple_url_fetcher is None: self._multiple_url_fetcher = MultipleUrlFetcher self._do_open_installed_repo = True self._installed_repo_enable = True if installed_repo in (True, None, 1): self._installed_repo_enable = True elif installed_repo in (False, 0): self._installed_repo_enable = False elif installed_repo == -1: self._installed_repo_enable = False self._do_open_installed_repo = False self.xcache = xcache shell_xcache = os.getenv("ETP_NOCACHE") if shell_xcache: self.xcache = False # now if we are on live, we should disable it # are we running on a livecd? (/proc/cmdline has "cdroot") if entropy.tools.islive(): self.xcache = False elif (not entropy.tools.is_user_in_entropy_group()) and not user_xcache: self.xcache = False # Add Entropy Resources Lock post-acquire hook that cleans # repository caches. hook_ref = EntropyResourcesLock.add_post_acquire_hook( self._resources_post_hook) self.__post_acquire_hook_idx = hook_ref # enable System Settings hooks self._can_run_sys_set_hooks = True const_debug_write(__name__, "singleton loaded") @property def _settings(self): """ Return a SystemSettings object instance. """ with self._real_settings_lock: if self._real_settings is None: self._real_settings = SystemSettings() const_debug_write(__name__, "SystemSettings loaded") # add our SystemSettings plugin # Make sure we connect Entropy Client plugin # AFTER client db init self._real_settings.add_plugin( self._settings_client_plugin) return self._real_settings @property def _settings_client_plugin(self): """ Return the SystemSettings Entropy Client plugin. """ with self._real_settings_client_plg_lock: if self._real_settings_client_plg is None: plugin = ClientSystemSettingsPlugin(self) self._real_settings_client_plg = plugin return self._real_settings_client_plg @property def _cacher(self): """ Return an EntropyCacher object instance. """ with self._real_cacher_lock: if self._real_cacher is None: real_cacher = EntropyCacher() const_debug_write(__name__, "EntropyCacher loaded") # needs to be started here otherwise repository # cache will be always dropped if self.xcache: real_cacher.start() else: # disable STASHING_CACHE or we leak EntropyCacher.STASHING_CACHE = False self._real_cacher = real_cacher return self._real_cacher @property def logger(self): """ Return the Entropy Client Logger instance. """ with self._real_logger_lock: if self._real_logger is None: real_logger = LogFile( level = self._settings['system']['log_level'], filename = etpConst['entropylogfile'], header = "[client]") const_debug_write(__name__, "Logger loaded") self._real_logger = real_logger return self._real_logger @property def _enabled_repos(self): with self._real_enabled_repos_lock: if self._real_enabled_repos is None: real_enabled_repos = [] if self._repo_validation: self._validate_repositories( enabled_repos = real_enabled_repos) else: real_enabled_repos.extend( self._settings['repositories']['order']) self._real_enabled_repos = real_enabled_repos return self._real_enabled_repos def _resources_post_hook(self): """ Hook running after Entropy Resources Lock acquisition. This method takes care of the repository memory caches, by invalidating it. """ with self._real_installed_repository_lock: if self._real_installed_repository is not None: self._real_installed_repository.clearCache() with self._repodb_cache_mutex: for repo in self._repodb_cache.values(): repo.clearCache() def destroy(self, _from_shutdown = False): """ Destroy this Singleton instance, closing repositories, removing SystemSettings plugins added during instance initialization. This method should be always called when instance is not used anymore. """ self.__instance_destroyed = True if self.__post_acquire_hook_idx is not None: EntropyResourcesLock.remove_post_acquire_hook( self.__post_acquire_hook_idx) self.__post_acquire_hook_idx = None if hasattr(self, '_installed_repository'): inst_repo = self.installed_repository() if inst_repo is not None: inst_repo.close(_token = InstalledPackagesRepository.NAME) if hasattr(self, '_real_logger_lock'): with self._real_logger_lock: if self._real_logger is not None: self._real_logger.close() if not _from_shutdown: if hasattr(self, '_real_settings') and \ hasattr(self._real_settings, 'remove_plugin'): # shutdown() will terminate the whole process # so there is no need to remove plugins from # SystemSettings, it wouldn't make any diff. if self._real_settings is not None: try: self._real_settings.remove_plugin( ClientSystemSettingsPlugin.ID) except KeyError: pass self.close_repositories(mask_clear = False) def shutdown(self): """ This method should be called when the whole process is going to be killed. It calls destroy() and stops any running thread """ self._cacher.sync() # enforce, destroy() may kill the current content self.destroy(_from_shutdown = True) self._cacher.stop() entropy.tools.kill_threads() @sharedinstlock def repository_packages_spm_sync(self, repository_identifier, repo_db, force = False): """ Service method used to sync package names with Source Package Manager via metadata stored in Repository dbs collected at server-time. Source Package Manager can change package names, categories or slot and Entropy repositories must be kept in sync. In other words, it checks for /usr/portage/profiles/updates changes, of course indirectly, since there is no way entropy.client can directly depend on Portage. @param repository_identifier: repository identifier which repo_db parameter is bound @type repository_identifier: string @param repo_db: repository database instance @type repo_db: entropy.db.EntropyRepository @return: bool stating if changes have been made @rtype: bool """ inst_repo = self.installed_repository() if not inst_repo: # nothing to do if client db is not availabe return False self._treeupdates_repos.add(repository_identifier) do_rescan = False shell_rescan = os.getenv("ETP_TREEUPDATES_RESCAN") if shell_rescan: do_rescan = True # check database digest stored_digest = repo_db.retrieveRepositoryUpdatesDigest( repository_identifier) if stored_digest == -1: do_rescan = True # check stored value in client database client_digest = "0" if not do_rescan: client_digest = \ inst_repo.retrieveRepositoryUpdatesDigest( repository_identifier) if do_rescan or (str(stored_digest) != str(client_digest)) or force: # reset database tables inst_repo.clearTreeupdatesEntries( repository_identifier) # load updates update_actions = repo_db.retrieveTreeUpdatesActions( repository_identifier) # now filter the required actions update_actions = inst_repo.filterTreeUpdatesActions( update_actions) if update_actions: mytxt = "%s: %s." % ( bold(_("ATTENTION")), red(_("forcing packages metadata update")), ) self.output( mytxt, importance = 1, level = "info", header = darkred(" * ") ) mytxt = "%s %s." % ( red(_("Updating system database using repository")), blue(repository_identifier), ) self.output( mytxt, importance = 1, level = "info", header = darkred(" * ") ) # run stuff inst_repo.runTreeUpdatesActions( update_actions) # store new digest into database inst_repo.setRepositoryUpdatesDigest( repository_identifier, stored_digest) # store new actions inst_repo.addRepositoryUpdatesActions( InstalledPackagesRepository.NAME, update_actions, self._settings['repositories']['branch']) inst_repo.commit() # clear client cache inst_repo.clearCache() return True def is_destroyed(self): return self.__instance_destroyed def clear_cache(self): """ Clear all the Entropy default cache directory. This function is fault tolerant and will never return any exception. """ with self._cacher: # no data is written while holding self._cacher by the balls # drop all the buffers then remove on-disk data self._cacher.discard() # clear repositories live cache inst_repo = self.installed_repository() if inst_repo is not None: inst_repo.clearCache() with self._repodb_cache_mutex: for repo in self._repodb_cache.values(): repo.clearCache() cache_dir = self._cacher.current_directory() try: shutil.rmtree(cache_dir, True) except (shutil.Error, IOError, OSError): return try: os.makedirs(cache_dir, 0o775) except (IOError, OSError): return try: const_setup_perms(cache_dir, etpConst['entropygid']) except (IOError, OSError): return def QA(self): """ Load Entropy QA interface object @rtype: entropy.qa.QAInterface """ qa_intf = QAInterface() qa_intf.output = self.output qa_intf.ask_question = self.ask_question qa_intf.input_box = self.input_box qa_intf.set_title = self.set_title return qa_intf def Settings(self): """ Return SystemSettings instance object """ return self._settings def ClientSettings(self): """ Return SystemSettings Entropy Client plugin metadata dictionary """ p_id = ClientSystemSettingsPlugin.ID return self._settings[p_id] def Cacher(self): """ Return EntropyCacher instance object @return: EntropyCacher instance object @rtype: entropy.cache.EntropyCacher """ return self._cacher def PackageActionFactory(self): """ Load Entropy PackageActionFactory instance object """ return PackageActionFactory(self) def ConfigurationUpdates(self): """ Return Entropy Configuration File Updates management object. """ return ConfigurationUpdates(self) def Spm(self): """ Load Source Package Manager instance object """ return get_spm(self) def Spm_class(self): """ Load Source Package Manager default plugin class """ return get_spm_default_class() def Repositories(self, *args, **kwargs): """ Load Entropy Repositories manager instance object @return: Repository instance object @rtype: entropy.client.interfaces.repository.Repository """ client_data = self.ClientSettings()['misc'] kwargs['gpg'] = client_data['gpg'] return Repository(self, *args, **kwargs) def Security(self, *args, **kwargs): """ Load Entropy Security Advisories interface object @return: Repository Security instance object @rtype: entropy.security.System """ return System(self, *args, **kwargs) def RepositorySecurity(self, keystore_dir = None): """ Load Entropy Repository Security interface object @return: Repository Repository Security instance object @rtype: entropy.security.Repository @raise RepositorySecurity.GPGError: GPGError based instances in case of problems. """ if keystore_dir is None: keystore_dir = etpConst['etpclientgpgdir'] return RepositorySecurity(keystore_dir = keystore_dir) def Sets(self): """ Load Package Sets interface object @return: Sets instance object @rtype: entropy.client.interfaces.sets.Sets """ return Sets(self) def WebServices(self): """ Load the Entropy Web Services Factory interface, that can be used to obtain a WebService object that is able to communicate with repository remote services, if available. @return: WebServicesFactory instance object @rtype: entropy.client.services.interfaces.WebServicesFactory """ return ClientWebServiceFactory(self) def RepositoryWebServices(self): """ Load the Repository Entropy Web Services Factory interface, that can be used to obtain a RepositoryWebService object that is able to communicate with repository remote services, querying for package metadata and general repository status. @return: RepositoryWebServiceFactory instance object @rtype: entropy.client.services.interfaces.RepositoryWebServiceFactory """ return RepositoryWebServiceFactory(self) from hpp.corbaserver.rbprm.rbprmbuilder import Builder from hpp.corbaserver.rbprm.rbprmfullbody import FullBody from hpp.gepetto import Viewer import stair_bauzil_hrp2_path as tp import time packageName = "hrp2_14_description" meshPackageName = "hrp2_14_description" rootJointType = "freeflyer" ## # Information to retrieve urdf and srdf files. urdfName = "hrp2_14" urdfSuffix = "_reduced" srdfSuffix = "" fullBody = FullBody () fullBody.loadFullBodyModel(urdfName, rootJointType, meshPackageName, packageName, urdfSuffix, srdfSuffix) fullBody.setJointBounds ("base_joint_xyz", [-0.135,2, -1, 1, 0, 2.2]) ps = tp.ProblemSolver( fullBody ) r = tp.Viewer (ps) #~ AFTER loading obstacles rLegId = '0rLeg' rLeg = 'RLEG_JOINT0' rLegOffset = [0,-0.105,0,] rLegNormal = [0,1,0] rLegx = 0.09; rLegy = 0.05 fullBody.addLimb(rLegId,rLeg,'',rLegOffset,rLegNormal, rLegx, rLegy, 10000, "manipulability", 0.1) lLegId = '1lLeg' lLeg = 'LLEG_JOINT0' lLegOffset = [0,-0.105,0] lLegNormal = [0,1,0] lLegx = 0.09; lLegy = 0.05 fullBody.addLimb(lLegId,lLeg,'',lLegOffset,rLegNormal, lLegx, lLegy, 10000, "manipulability", 0.1) rarmId = '3Rarm' rarm = 'RARM_JOINT0' rHand = 'RARM_JOINT5' rArmOffset = [0,0,-0.1] rArmNormal = [0,0,1] rArmx = 0.024; rArmy = 0.024 #disabling collision for hook fullBody.addLimb(rarmId,rarm,rHand,rArmOffset,rArmNormal, rArmx, rArmy, 10000, "manipulability", 0.05, "_6_DOF", True) #~ AFTER loading obstacles larmId = '4Larm' larm = 'LARM_JOINT0' lHand = 'LARM_JOINT5' lArmOffset = [-0.05,-0.050,-0.050] lArmNormal = [1,0,0] lArmx = 0.024; lArmy = 0.024 #~ fullBody.addLimb(larmId,larm,lHand,lArmOffset,lArmNormal, lArmx, lArmy, 10000, 0.05) rKneeId = '0RKnee' rLeg = 'RLEG_JOINT0' rKnee = 'RLEG_JOINT3' rLegOffset = [0.105,0.055,0.017] rLegNormal = [-1,0,0] rLegx = 0.05; rLegy = 0.05 #~ fullBody.addLimb(rKneeId, rLeg,rKnee,rLegOffset,rLegNormal, rLegx, rLegy, 10000, 0.01) #~ lKneeId = '1LKnee' lLeg = 'LLEG_JOINT0' lKnee = 'LLEG_JOINT3' lLegOffset = [0.105,0.055,0.017] lLegNormal = [-1,0,0] lLegx = 0.05; lLegy = 0.05 #~ fullBody.addLimb(lKneeId,lLeg,lKnee,lLegOffset,lLegNormal, lLegx, lLegy, 10000, 0.01) #~ #~ fullBody.runLimbSampleAnalysis(rLegId, "jointLimitsDistance", True) #~ fullBody.runLimbSampleAnalysis(lLegId, "jointLimitsDistance", True) #~ fullBody.client.basic.robot.setJointConfig('LARM_JOINT0',[1]) #~ fullBody.client.basic.robot.setJointConfig('RARM_JOINT0',[-1]) q_0 = fullBody.getCurrentConfig(); #~ fullBody.createOctreeBoxes(r.client.gui, 1, rarmId, q_0,) q_init = fullBody.getCurrentConfig(); q_init[0:7] = tp.q_init[0:7] q_goal = fullBody.getCurrentConfig(); q_goal[0:7] = tp.q_goal[0:7] fullBody.setCurrentConfig (q_init) q_init = [ 0.1, -0.82, 0.648702, 1.0, 0.0 , 0.0, 0.0, # Free flyer 0-6 0.0, 0.0, 0.0, 0.0, # CHEST HEAD 7-10 0.261799388, 0.174532925, 0.0, -0.523598776, 0.0, 0.0, 0.17, # LARM 11-17 0.261799388, -0.174532925, 0.0, -0.523598776, 0.0, 0.0, 0.17, # RARM 18-24 0.0, 0.0, -0.453785606, 0.872664626, -0.41887902, 0.0, # LLEG 25-30 0.0, 0.0, -0.453785606, 0.872664626, -0.41887902, 0.0, # RLEG 31-36 ]; r (q_init) fullBody.setCurrentConfig (q_goal) #~ r(q_goal) q_goal = fullBody.generateContacts(q_goal, [0,0,1]) #~ r(q_goal) fullBody.setStartState(q_init,[rLegId,lLegId]) #,rarmId,larmId]) fullBody.setEndState(q_goal,[rLegId,lLegId])#,rarmId,larmId]) #~ #~ configs = fullBody.interpolate(0.1) configs = fullBody.interpolate(0.1) #~ configs = fullBody.interpolate(0.15) i = 0; fullBody.draw(configs[i],r); i=i+1; i-1 r.loadObstacleModel ('hpp-rbprm-corba', "stair_bauzil", "contact") #~ fullBody.exportAll(r, configs, 'stair_bauzil_hrp2_robust_2'); #~ fullBody.client.basic.robot.setJointConfig('LLEG_JOINT0',[-1]) #~ q_0 = fullBody.getCurrentConfig(); #~ fullBody.draw(q_0,r); #~ print(fullBody.client.rbprm.rbprm.getOctreeTransform(rarmId, q_0)) #~ #~ #~ fullBody.client.basic.robot.setJointConfig('LLEG_JOINT0',[1]) #~ q_0 = fullBody.getCurrentConfig(); #~ fullBody.draw(q_0,r); #~ print(fullBody.client.rbprm.rbprm.getOctreeTransform(rarmId, q_0)) #~ q_init = fullBody.generateContacts(q_init, [0,0,-1]); r (q_init) #~ f1 = open("secondchoice","w+") #~ f1 = open("hrp2_stair_not_robust_configs","w+") #~ f1.write(str(configs)) #~ f1.close() limbsCOMConstraints = { rLegId : {'file': "hrp2/RL_com.ineq", 'effector' : 'RLEG_JOINT5'}, lLegId : {'file': "hrp2/LL_com.ineq", 'effector' : 'LLEG_JOINT5'}, rarmId : {'file': "hrp2/RA_com.ineq", 'effector' : rHand} } #~ larmId : {'file': "hrp2/LA_com.ineq", 'effector' : lHand} } #~ fullBody.limbRRTFromRootPath(0,len(configs)-1,0,2) from hpp.corbaserver.rbprm.tools.cwc_trajectory_helper import step, clean,stats, saveAllData, play_traj from hpp.gepetto import PathPlayer pp = PathPlayer (fullBody.client.basic, r) def act(i, numOptim = 0, use_window = 0, friction = 0.5, optim_effectors = True, verbose = False, draw = False): return step(fullBody, configs, i, numOptim, pp, limbsCOMConstraints, 0.4, optim_effectors = optim_effectors, time_scale = 20., useCOMConstraints = True, use_window = use_window, verbose = verbose, draw = draw) def play(frame_rate = 1./24.): play_traj(fullBody,pp,frame_rate) def saveAll(name): saveAllData(fullBody, r, name) def initConfig(): r.client.gui.setVisibility("hrp2_14", "ON") tp.cl.problem.selectProblem("default") tp.r.client.gui.setVisibility("toto", "OFF") tp.r.client.gui.setVisibility("hrp2_trunk_flexible", "OFF") r(q_init) def endConfig(): r.client.gui.setVisibility("hrp2_14", "ON") tp.cl.problem.selectProblem("default") tp.r.client.gui.setVisibility("toto", "OFF") tp.r.client.gui.setVisibility("hrp2_trunk_flexible", "OFF") r(q_goal) def rootPath(): tp.cl.problem.selectProblem("rbprm_path") r.client.gui.setVisibility("hrp2_14", "OFF") tp.r.client.gui.setVisibility("toto", "OFF") r.client.gui.setVisibility("hyq", "OFF") r.client.gui.setVisibility("hrp2_trunk_flexible", "ON") tp.pp(0) r.client.gui.setVisibility("hrp2_trunk_flexible", "OFF") r.client.gui.setVisibility("hyq", "ON") tp.cl.problem.selectProblem("default") def genPlan(): r.client.gui.setVisibility("hrp2_14", "ON") tp.cl.problem.selectProblem("default") tp.r.client.gui.setVisibility("toto", "OFF") tp.r.client.gui.setVisibility("hrp2_trunk_flexible", "OFF") global configs start = time.clock() configs = configs = fullBody.interpolate(0.1, True) end = time.clock() print "Contact plan generated in " + str(end-start) + "seconds" def contactPlan(): tp.cl.problem.selectProblem("default") r.client.gui.setVisibility("hrp2_14", "ON") tp.r.client.gui.setVisibility("toto", "OFF") tp.r.client.gui.setVisibility("hrp2_trunk_flexible", "OFF") for i in range(1,len(configs)): r(configs[i]); time.sleep(0.5) def interpolate(): tp.cl.problem.selectProblem("default") r.client.gui.setVisibility("hrp2_14", "ON") tp.r.client.gui.setVisibility("toto", "OFF") tp.r.client.gui.setVisibility("hrp2_trunk_flexible", "OFF") for i in range(7,20): act(i,1,optim_effectors=True) def play(frame_rate = 1./24.): play_traj(fullBody,pp,frame_rate) def a(): print "initial configuration" initConfig() def b(): print "end configuration" endConfig() def c(): print "displaying root path" rootPath() def d(): print "computing contact plan" genPlan() def e(): print "displaying contact plan" contactPlan() def f(): print "computing feasible com trajectory" interpolate() def g(): print "playing feasible trajectory" play() print "Root path generated in " + str(tp.t) + " ms." #!/usr/bin/python # # Copyright 2008 Google Inc. All Rights Reserved. """Test for the rpc proxy class.""" import unittest, os try: import autotest.common as common except ImportError: import common from autotest_lib.cli import rpc from autotest_lib.client.common_lib import global_config from autotest_lib.frontend.afe import rpc_client_lib from autotest_lib.frontend.afe.json_rpc import proxy GLOBAL_CONFIG = global_config.global_config class rpc_unittest(unittest.TestCase): def setUp(self): self.old_environ = os.environ.copy() if 'AUTOTEST_WEB' in os.environ: del os.environ['AUTOTEST_WEB'] def tearDown(self): os.environ.clear() os.environ.update(self.old_environ) def test_get_autotest_server_specific(self): self.assertEqual('http://foo', rpc.get_autotest_server('foo')) def test_get_autotest_server_none(self): GLOBAL_CONFIG.override_config_value('SERVER', 'hostname', 'Prince') self.assertEqual('http://Prince', rpc.get_autotest_server(None)) def test_get_autotest_server_environ(self): os.environ['AUTOTEST_WEB'] = 'foo-dev' self.assertEqual('http://foo-dev', rpc.get_autotest_server(None)) del os.environ['AUTOTEST_WEB'] def test_get_autotest_server_environ_precedence(self): os.environ['AUTOTEST_WEB'] = 'foo-dev' self.assertEqual('http://foo', rpc.get_autotest_server('foo')) del os.environ['AUTOTEST_WEB'] if __name__ == '__main__': unittest.main() # -*- coding: utf-8 -*- """ Boolean Nodes ================================= Commonly used boolean node functions. """ # Copyright (C) 2021 by # Alex Gates # Rion Brattig Correia # All rights reserved. # MIT license. from .. boolean_network import BooleanNode def AND(): """AND boolean node. .. code:: 00 : 0 01 : 0 10 : 0 11 : 1 """ return BooleanNode.from_output_list(outputs=[0, 0, 0, 1], name="AND") def OR(): """OR boolean node. .. code:: 00 : 0 01 : 1 10 : 1 11 : 1 """ return BooleanNode.from_output_list(outputs=[0, 1, 1, 1], name="OR") def XOR(): """XOR boolean node. .. code:: 00 : 0 01 : 1 10 : 1 11 : 0 """ return BooleanNode.from_output_list(outputs=[0, 1, 1, 0], name="XOR") def COPYx1(): """COPY :math:`x_1` boolean node. .. code:: 00 : 0 01 : 0 10 : 1 11 : 1 """ return BooleanNode.from_output_list(outputs=[0, 0, 1, 1], name="COPY x_1") def CONTRADICTION(): """Contradiction boolean node. .. code:: 00 : 0 01 : 0 10 : 0 11 : 0 """ return BooleanNode.from_output_list(outputs=[0, 0, 0, 0], name="CONTRADICTION") def RULE90(): """RULE 90 celular automata node. .. code:: 000 : 0 001 : 1 010 : 0 011 : 1 100 : 1 101 : 0 110 : 1 111 : 0 """ return BooleanNode.from_output_list(outputs=[0, 1, 0, 1, 1, 0, 1, 0], name="RULE 90") def RULE110(): """RULE 110 celular automata node. .. code:: 000 : 0 001 : 1 010 : 1 011 : 1 100 : 0 101 : 1 110 : 1 111 : 0 """ return BooleanNode.from_output_list(outputs=[0, 1, 1, 1, 0, 1, 1, 0], name="RULE 110") # Author: Nicolas VERDIER # This file is part of memorpy. # # memorpy 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. # # memorpy 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 memorpy. If not, see . import binascii import logging import re import struct from LoLVRSpectate.memorpy import utils from LoLVRSpectate.memorpy.Address import Address from LoLVRSpectate.memorpy.structures import * from LoLVRSpectate.memorpy import Process logger = logging.getLogger('memorpy') class MemWorker(object): def __init__(self, process_name, end_offset = None, start_offset = None): logger.info('opening process %s ...' % process_name) self.process = Process() self.process.open_debug_from_name(process_name) si = self.process.GetSystemInfo() if end_offset: self.end_offset = end_offset else: self.end_offset = si.lpMaximumApplicationAddress if start_offset: self.start_offset = start_offset else: self.start_offset = si.lpMinimumApplicationAddress def Address(self, value, default_type = 'uint'): """ wrapper to instanciate an Address class for the memworker.process""" return Address(value, process=self.process, default_type=default_type) def search_address(self, address): address = int(address) for m in self.process.list_modules(): for addr in self.mem_search(address, ftype='ulong', start_offset=m.modBaseAddr, end_offset=m.modBaseSize): logger.debug('found module %s => addr %s' % (m.szModule, addr)) def umem_replace(self, regex, replace): """ like search_replace_mem but works with unicode strings """ regex = utils.re_to_unicode(regex) replace = replace.encode('utf-16-le') return self.mem_replace(re.compile(regex, re.UNICODE), replace) def mem_replace(self, regex, replace): """ search memory for a pattern and replace all found occurrences """ allWritesSucceed = True for start_offset in self.mem_search(regex, ftype='re'): if self.process.write_bytes(start_offset, replace) == 1: logger.debug('Write at offset %s succeeded !' % start_offset) else: allWritesSucceed = False logger.debug('Write at offset %s failed !' % start_offset) return allWritesSucceed def umem_search(self, regex): """ like mem_search but works with unicode strings """ regex = utils.re_to_unicode(regex) for i in self.mem_search(str(regex), ftype='re'): yield i def group_search(self, group, start_offset = None, end_offset = None): regex = '' for value, type in group: if type == 'f' or type == 'float': f = struct.pack('= end_offset: break totalread = 0 mbi = self.process.VirtualQueryEx(offset) offset = mbi.BaseAddress chunk = mbi.RegionSize protect = mbi.Protect state = mbi.State if state & MEM_FREE or state & MEM_RESERVE: offset += chunk continue if protec: if not protect & protec or protect & PAGE_NOCACHE or protect & PAGE_WRITECOMBINE or protect & PAGE_GUARD: offset += chunk continue b = '' try: b = self.process.read_bytes(offset, chunk) totalread = len(b) except Exception as e: logger.warning(e) offset += chunk continue if b: if ftype == 're': duplicates_cache = set() for res in regex.findall(b): index = b.find(res) while index != -1: soffset = offset + index if soffset not in duplicates_cache: duplicates_cache.add(soffset) yield self.Address(soffset, 'bytes') index = b.find(res, index + len(res)) elif ftype == 'float': for index in range(0, len(b)): try: tmpval = struct.unpack(structtype, b[index:index + 4])[0] if int(value) == int(tmpval): soffset = offset + index yield self.Address(soffset, 'float') except Exception as e: pass else: index = b.find(value) while index != -1: soffset = offset + index yield self.Address(soffset, 'bytes') index = b.find(value, index + 1) offset += totalread # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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 __future__ import print_function import op_test import unittest import numpy def create_test_class(op_type, typename, callback): class Cls(op_test.OpTest): def setUp(self): a = numpy.random.random(size=(10, 7)).astype(typename) b = numpy.random.random(size=(10, 7)).astype(typename) c = callback(a, b) self.inputs = {'X': a, 'Y': b} self.outputs = {'Out': c} self.op_type = op_type def test_output(self): self.check_output() cls_name = "{0}_{1}".format(op_type, typename) Cls.__name__ = cls_name globals()[cls_name] = Cls for _type_name in {'float32', 'float64', 'int32', 'int64'}: create_test_class('less_than', _type_name, lambda _a, _b: _a < _b) create_test_class('less_equal', _type_name, lambda _a, _b: _a <= _b) create_test_class('greater_than', _type_name, lambda _a, _b: _a > _b) create_test_class('greater_equal', _type_name, lambda _a, _b: _a >= _b) create_test_class('equal', _type_name, lambda _a, _b: _a == _b) create_test_class('not_equal', _type_name, lambda _a, _b: _a != _b) if __name__ == '__main__': unittest.main() #-*- coding:utf-8 -*- """ This file is part of openexp. openexp 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. openexp 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 openexp. If not, see . """ from libopensesame.sketchpad_elements._base_element import base_element class arrow(base_element): """ desc: An arrow element for the sketchpad. """ def __init__(self, sketchpad, string): """ desc: Constructor. arguments: sketchpad: A sketchpad object. string: A definition string. """ defaults = [ (u'x1' , None), (u'y1' , None), (u'x2' , None), (u'y2' , None), (u'arrow_size' , 20), (u'color' , sketchpad.get(u'foreground')), (u'penwidth' , 1), ] super(arrow, self).__init__(sketchpad, string, defaults=defaults) def draw(self): """ desc: Draws the element to the canvas of the sketchpad. """ properties = self.eval_properties() return self.canvas.arrow(properties[u'x1'], properties[u'y1'], properties[u'x2'], properties[u'y2'], color=properties[u'color'], penwidth=properties[u'penwidth'], arrow_size=properties[u'arrow_size']) # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not 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 typing import List, Optional, Union from airflow.models import BaseOperator from airflow.providers.dingding.hooks.dingding import DingdingHook from airflow.utils.decorators import apply_defaults class DingdingOperator(BaseOperator): """ This operator allows you send Dingding message using Dingding custom bot. Get Dingding token from conn_id.password. And prefer set domain to conn_id.host, if not will use default ``https://oapi.dingtalk.com``. For more detail message in `Dingding custom bot `_ :param dingding_conn_id: The name of the Dingding connection to use :type dingding_conn_id: str :param message_type: Message type you want to send to Dingding, support five type so far including text, link, markdown, actionCard, feedCard :type message_type: str :param message: The message send to Dingding chat group :type message: str or dict :param at_mobiles: Remind specific users with this message :type at_mobiles: list[str] :param at_all: Remind all people in group or not. If True, will overwrite ``at_mobiles`` :type at_all: bool """ template_fields = ('message',) ui_color = '#4ea4d4' # Dingding icon color @apply_defaults def __init__( self, *, dingding_conn_id: str = 'dingding_default', message_type: str = 'text', message: Union[str, dict, None] = None, at_mobiles: Optional[List[str]] = None, at_all: bool = False, **kwargs, ) -> None: super().__init__(**kwargs) self.dingding_conn_id = dingding_conn_id self.message_type = message_type self.message = message self.at_mobiles = at_mobiles self.at_all = at_all def execute(self, context) -> None: self.log.info('Sending Dingding message.') hook = DingdingHook( self.dingding_conn_id, self.message_type, self.message, self.at_mobiles, self.at_all ) hook.send() # ***** BEGIN GPL LICENSE BLOCK ***** # # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # 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, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ***** END GPL LICENCE BLOCK ***** import bpy from bpy.props import * from bpy.types import Operator, AddonPreferences import math # import mifth_tools_cloning # bpy.mifthTools = dict() class MFTSceneRender2X(bpy.types.Operator): bl_idname = "mft.render_scene_2x" bl_label = "Render2X" bl_description = "Render2X..." bl_options = {'REGISTER', 'UNDO'} scale_value : FloatProperty( default=2.0, min=0.001, max=500.0 ) def execute(self, context): scene = context.scene nodes = scene.node_tree.nodes mifthTools = context.scene.mifthTools crop_nodes_2x(nodes, self.scale_value) return {'FINISHED'} def crop_nodes_2x(nodes, scale_value): for node in nodes: if node.type == 'GROUP': crop_nodes_2x(node.node_tree.nodes, scale_value) elif node.type == 'CROP': node.min_x *= scale_value node.max_x *= scale_value node.min_y *= scale_value node.max_y *= scale_value class MFTCropNodeRegion(bpy.types.Operator): bl_idname = "mft.cropnoderegion" bl_label = "Crop Node Region" bl_description = "Crop Node Region" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): scene = context.scene nodes = scene.node_tree.nodes cropNode = nodes.active crop_percentage = context.scene.render.resolution_percentage / 100.0 if cropNode != None: if cropNode.type == 'CROP': cropNode.min_x = scene.render.border_min_x * scene.render.resolution_x * crop_percentage cropNode.max_x = scene.render.border_max_x * scene.render.resolution_x * crop_percentage cropNode.min_y = scene.render.border_max_y * scene.render.resolution_y * crop_percentage cropNode.max_y = scene.render.border_min_y * scene.render.resolution_y * crop_percentage elif cropNode.type == 'GROUP': cropGroupNode = cropNode.node_tree.nodes.active if cropGroupNode != None and cropGroupNode.type == 'CROP': cropGroupNode.min_x = scene.render.border_min_x * scene.render.resolution_x * crop_percentage cropGroupNode.max_x = scene.render.border_max_x * scene.render.resolution_x * crop_percentage cropGroupNode.min_y = scene.render.border_max_y * scene.render.resolution_y * crop_percentage cropGroupNode.max_y = scene.render.border_min_y * scene.render.resolution_y * crop_percentage else: self.report({'INFO'}, "Select Crop Node!") return {'FINISHED'} class MFTCropToViewport(bpy.types.Operator): bl_idname = "mft.crop_to_viewport" bl_label = "Crop To Viewport" bl_description = "Crop To Viewport..." bl_options = {'REGISTER', 'UNDO'} def execute(self, context): scene = context.scene nodes = scene.node_tree.nodes cropNode = nodes.active if cropNode != None: if cropNode.type == 'CROP': scene.render.border_min_x = float(cropNode.min_x / scene.render.resolution_x) / (float(scene.render.resolution_percentage) / 100.0) scene.render.border_max_x = float(cropNode.max_x / scene.render.resolution_x) / (float(scene.render.resolution_percentage) / 100.0) scene.render.border_max_y = float(cropNode.min_y / scene.render.resolution_y) / (float(scene.render.resolution_percentage) / 100.0) scene.render.border_min_y = float(cropNode.max_y / scene.render.resolution_y) / (float(scene.render.resolution_percentage) / 100.0) elif cropNode.type == 'GROUP': cropGroupNode = cropNode.node_tree.nodes.active if cropGroupNode != None and cropGroupNode.type == 'CROP': scene.render.border_min_x = float(cropGroupNode.min_x / scene.render.resolution_x) / (float(scene.render.resolution_percentage) / 100.0) scene.render.border_max_x = float(cropGroupNode.max_x / scene.render.resolution_x) / (float(scene.render.resolution_percentage) / 100.0) scene.render.border_max_y = float(cropGroupNode.min_y / scene.render.resolution_y) / (float(scene.render.resolution_percentage) / 100.0) scene.render.border_min_y = float(cropGroupNode.max_y / scene.render.resolution_y) / (float(scene.render.resolution_percentage) / 100.0) else: self.report({'INFO'}, "Select Crop Node!") return {'FINISHED'} class MFTOutputCreator(bpy.types.Operator): bl_idname = "mft.outputcreator" bl_label = "Create Output" bl_description = "Output Creator" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): scene = context.scene nodes = scene.node_tree.nodes mifthTools = context.scene.mifthTools output_file = nodes.new("CompositorNodeOutputFile") output_file.base_path = "//" + mifthTools.outputFolder + "/" output_file.file_slots.remove(output_file.inputs[0]) for i in range(mifthTools.outputSequenceSize): idx = str(i + 1) if i < 9: idx = "0" + idx outFile = "" if mifthTools.doOutputSubFolder is True: outFile = mifthTools.outputSubFolder + "_" + idx + "/" outFile += mifthTools.outputSequence + "_" + idx + "_" output_file.file_slots.new(outFile) return {'FINISHED'} class MFTCurveAnimator(bpy.types.Operator): bl_idname = "mft.curveanimator" bl_label = "Curve Animator" bl_description = "Curve Animator" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): mifthTools = context.scene.mifthTools startFrame = context.scene.frame_start if mifthTools.doUseSceneFrames is False: startFrame = mifthTools.curveAniStartFrame endFrame = context.scene.frame_end if mifthTools.doUseSceneFrames is False: endFrame = mifthTools.curveAniEndFrame totalFrames = endFrame - startFrame frameSteps = mifthTools.curveAniStepFrame - 1 for curve in context.selected_objects: if curve.type == 'CURVE': for frStep in range(frameSteps + 1): aniPos = 1.0 - (float(frStep) / float(frameSteps)) goToFrame = int(aniPos * float(totalFrames)) goToFrame += startFrame context.scene.frame_current = goToFrame print(goToFrame) for spline in curve.data.splines: # print(spline.points) # if len(spline.bezier_points) >= 2: spline.use_bezier_u = False spline.use_endpoint_u = True # spline.use_cyclic_u = False aniInterpolation = mifthTools.curveAniInterpolation allPoints = None if spline.type == 'BEZIER': allPoints = spline.bezier_points else: allPoints = spline.points splineSize = len(allPoints) iInterpolation = aniPos - aniInterpolation for i in range(splineSize): point = allPoints[i] iPlace = float(i + 1) / float(splineSize) if iPlace >= aniPos and goToFrame != endFrame: point.radius = 0.0 elif iPlace < aniPos and iPlace > iInterpolation and goToFrame != endFrame and goToFrame != startFrame: additionalInterpolation = 1.0 - \ ((iPlace - iInterpolation) / aniInterpolation) point.radius *= additionalInterpolation # print(additionalInterpolation) point.keyframe_insert( data_path="radius", frame=goToFrame) return {'FINISHED'} class MFTMorfCreator(bpy.types.Operator): bl_idname = "mft.morfcreator" bl_label = "Morfing Creator" bl_description = "Morfing Creator from different objects" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): scene = bpy.context.scene mifthTools = scene.mifthTools if len(context.selected_objects): objAct = context.active_object morfIndex = 1 # print(objAct.data.shape_keys) if objAct.data.shape_keys is None: basisKey = objAct.shape_key_add(from_mix=False) basisKey.name = 'Basis' for obj in context.selected_objects: if len(context.selected_objects) > 1 and obj == objAct: pass else: if len(obj.data.vertices) == len(objAct.data.vertices): shapeKey = objAct.shape_key_add(from_mix=False) if mifthTools.morfCreatorNames != '': shapeKey.name = mifthTools.morfCreatorNames if len(context.selected_objects) > 2: shapeKey.name += "_" + str(morfIndex) morfIndex += 1 else: shapeKey.name = obj.name modifiedMesh = obj.data if mifthTools.morfApplyModifiers is True: #modifiedMesh = obj.to_mesh() depsgraph = bpy.context.evaluated_depsgraph_get() object_eval = obj.evaluated_get(depsgraph) modifiedMesh = bpy.data.meshes.new_from_object(object_eval) for vert in modifiedMesh.vertices: if mifthTools.morfUseWorldMatrix: shapeKey.data[vert.index].co = obj.matrix_world @ vert.co else: shapeKey.data[vert.index].co = vert.co # print(vert.co) # this is a vertex coord of the # mesh else: self.report( {'INFO'}, "Model " + obj.name + " has different points count") return {'FINISHED'} class MFTCopyBonesTransform(bpy.types.Operator): bl_idname = "mft.copy_bones_transform" bl_label = "Copy Bones Transform" bl_description = "Copy Bones Transform" bl_options = {'REGISTER', 'UNDO'} bones_transform = [] mode : EnumProperty( items=(('Copy', 'Copy', ''), ('Paste', 'Paste', '') ), default = 'Copy' ) def execute(self, context): scene = context.scene mifthTools = scene.mifthTools obj_act = context.active_object all_bones = obj_act.data.bones sel_bones = context.selected_pose_bones if sel_bones: if self.mode == 'Copy': del self.bones_transform[:] for bone in sel_bones: self.bones_transform.append(bone.matrix.copy()) #print(bone.matrix) elif self.mode == 'Paste': for i in range(len(sel_bones)): sel_bones[i].matrix = self.bones_transform[i].copy() #print(self.bones_transform[i]) return {'FINISHED'} # -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2011 OpenERP S.A (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) UID_ROOT = 1 SHARED_DOCS_MENU = "Documents" SHARED_DOCS_CHILD_MENU = "Shared Documents" class share_wizard_portal(osv.TransientModel): """Inherited share wizard to automatically create appropriate menus in the selected portal upon sharing with a portal group.""" _inherit = "share.wizard" def _user_type_selection(self, cr, uid, context=None): selection = super(share_wizard_portal, self)._user_type_selection(cr, uid, context=context) selection.extend([('existing',_('Users you already shared with')), ('groups',_('Existing Groups (e.g Portal Groups)'))]) return selection _columns = { 'user_ids': fields.many2many('res.users', 'share_wizard_res_user_rel', 'share_id', 'user_id', 'Existing users', domain=[('share', '=', True)]), 'group_ids': fields.many2many('res.groups', 'share_wizard_res_group_rel', 'share_id', 'group_id', 'Existing groups', domain=[('share', '=', False)]), } def _check_preconditions(self, cr, uid, wizard_data, context=None): if wizard_data.user_type == 'existing': self._assert(wizard_data.user_ids, _('Please select at least one user to share with'), context=context) elif wizard_data.user_type == 'groups': self._assert(wizard_data.group_ids, _('Please select at least one group to share with'), context=context) return super(share_wizard_portal, self)._check_preconditions(cr, uid, wizard_data, context=context) def _create_or_get_submenu_named(self, cr, uid, parent_menu_id, menu_name, context=None): if not parent_menu_id: return Menus = self.pool.get('ir.ui.menu') parent_menu = Menus.browse(cr, uid, parent_menu_id) # No context menu_id = None max_seq = 10 for child_menu in parent_menu.child_id: max_seq = max(max_seq, child_menu.sequence) if child_menu.name == menu_name: menu_id = child_menu.id break if not menu_id: # not found, create it menu_id = Menus.create(cr, UID_ROOT, {'name': menu_name, 'parent_id': parent_menu.id, 'sequence': max_seq + 10, # at the bottom }) return menu_id def _sharing_root_menu_id(self, cr, uid, portal, context=None): """Create or retrieve root ID of sharing menu in portal menu :param portal: browse_record of portal, constructed with a context WITHOUT language """ parent_menu_id = self._create_or_get_submenu_named(cr, uid, portal.parent_menu_id.id, SHARED_DOCS_MENU, context=context) if parent_menu_id: child_menu_id = self._create_or_get_submenu_named(cr, uid, parent_menu_id, SHARED_DOCS_CHILD_MENU, context=context) return child_menu_id def _create_shared_data_menu(self, cr, uid, wizard_data, portal, context=None): """Create sharing menus in portal menu according to share wizard options. :param wizard_data: browse_record of share.wizard :param portal: browse_record of portal, constructed with a context WITHOUT language """ root_menu_id = self._sharing_root_menu_id(cr, uid, portal, context=context) if not root_menu_id: # no specific parent menu, cannot create the sharing menu at all. return # Create the shared action and menu action_def = self._shared_action_def(cr, uid, wizard_data, context=None) action_id = self.pool.get('ir.actions.act_window').create(cr, UID_ROOT, action_def) menu_data = {'name': action_def['name'], 'sequence': 10, 'action': 'ir.actions.act_window,'+str(action_id), 'parent_id': root_menu_id, 'icon': 'STOCK_JUSTIFY_FILL'} menu_id = self.pool.get('ir.ui.menu').create(cr, UID_ROOT, menu_data) return menu_id def _create_share_users_group(self, cr, uid, wizard_data, context=None): # Override of super() to handle the possibly selected "existing users" # and "existing groups". # In both cases, we call super() to create the share group, but when # sharing with existing groups, we will later delete it, and copy its # access rights and rules to the selected groups. super_result = super(share_wizard_portal,self)._create_share_users_group(cr, uid, wizard_data, context=context) # For sharing with existing groups, we don't create a share group, instead we'll # alter the rules of the groups so they can see the shared data if wizard_data.group_ids: # get the list of portals and the related groups to install their menus. res_groups = self.pool.get('res.groups') all_portal_group_ids = res_groups.search(cr, UID_ROOT, [('is_portal', '=', True)]) # populate result lines with the users of each group and # setup the menu for portal groups for group in wizard_data.group_ids: if group.id in all_portal_group_ids: self._create_shared_data_menu(cr, uid, wizard_data, group.id, context=context) for user in group.users: new_line = {'user_id': user.id, 'newly_created': False} wizard_data.write({'result_line_ids': [(0,0,new_line)]}) elif wizard_data.user_ids: # must take care of existing users, by adding them to the new group, which is super_result[0], # and adding the shortcut selected_user_ids = [x.id for x in wizard_data.user_ids] self.pool.get('res.users').write(cr, UID_ROOT, selected_user_ids, {'groups_id': [(4, super_result[0])]}) self._setup_action_and_shortcut(cr, uid, wizard_data, selected_user_ids, make_home=False, context=context) # populate the result lines for existing users too for user in wizard_data.user_ids: new_line = { 'user_id': user.id, 'newly_created': False} wizard_data.write({'result_line_ids': [(0,0,new_line)]}) return super_result def copy_share_group_access_and_delete(self, cr, wizard_data, share_group_id, context=None): # In the case of sharing with existing groups, the strategy is to copy # access rights and rules from the share group, so that we can if not wizard_data.group_ids: return Groups = self.pool.get('res.groups') Rules = self.pool.get('ir.rule') Rights = self.pool.get('ir.model.access') share_group = Groups.browse(cr, UID_ROOT, share_group_id) share_rule_ids = [r.id for r in share_group.rule_groups] for target_group in wizard_data.group_ids: # Link the rules to the group. This is appropriate because as of # v6.1, the algorithm for combining them will OR the rules, hence # extending the visible data. Rules.write(cr, UID_ROOT, share_rule_ids, {'groups': [(4,target_group.id)]}) _logger.debug("Linked sharing rules from temporary sharing group to group %s", target_group) # Copy the access rights. This is appropriate too because # groups have the UNION of all permissions granted by their # access right lines. for access_line in share_group.model_access: Rights.copy(cr, UID_ROOT, access_line.id, default={'group_id': target_group.id}) _logger.debug("Copied access rights from temporary sharing group to group %s", target_group) # finally, delete it after removing its users Groups.write(cr, UID_ROOT, [share_group_id], {'users': [(6,0,[])]}) Groups.unlink(cr, UID_ROOT, [share_group_id]) _logger.debug("Deleted temporary sharing group %s", share_group_id) def _finish_result_lines(self, cr, uid, wizard_data, share_group_id, context=None): super(share_wizard_portal,self)._finish_result_lines(cr, uid, wizard_data, share_group_id, context=context) self.copy_share_group_access_and_delete(cr, wizard_data, share_group_id, context=context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: # -*- coding: utf-8 -*- import collections from typing import ( Tuple, List, Sequence, Any, Dict, Union) __all__ = [ 'RouteError', 'Routes', 'RouteResolved'] # This is a nested structure similar to a linked-list VariablePartsType = Tuple[tuple, Tuple[str, str]] class RouteError(Exception): """Base error for any exception raised by Kua""" def depth_of(parts: Sequence[str]) -> int: """ Calculate the depth of URL parts :param parts: A list of URL parts :return: Depth of the list :private: """ return len(parts) - 1 def normalize_url(url: str) -> str: """ Remove leading and trailing slashes from a URL :param url: URL :return: URL with no leading and trailing slashes :private: """ if url.startswith('/'): url = url[1:] if url.endswith('/'): url = url[:-1] return url def _unwrap(variable_parts: VariablePartsType): """ Yield URL parts. The given parts are usually in reverse order. """ curr_parts = variable_parts var_any = [] while curr_parts: curr_parts, (var_type, part) = curr_parts if var_type == Routes._VAR_ANY_NODE: var_any.append(part) continue if var_type == Routes._VAR_ANY_BREAK: if var_any: yield tuple(reversed(var_any)) var_any.clear() var_any.append(part) continue if var_any: yield tuple(reversed(var_any)) var_any.clear() yield part continue yield part if var_any: yield tuple(reversed(var_any)) def make_params( key_parts: Sequence[str], variable_parts: VariablePartsType) -> Dict[str, Union[str, Tuple[str]]]: """ Map keys to variables. This map\ URL-pattern variables to\ a URL related parts :param key_parts: A list of URL parts :param variable_parts: A linked-list\ (ala nested tuples) of URL parts :return: The param dict with the values\ assigned to the keys :private: """ # The unwrapped variable parts are in reverse order. # Instead of reversing those we reverse the key parts # and avoid the O(n) space required for reversing the vars return dict(zip(reversed(key_parts), _unwrap(variable_parts))) _Route = collections.namedtuple( '_Route', ['key_parts', 'anything']) RouteResolved = collections.namedtuple( 'RouteResolved', ['params', 'anything']) RouteResolved.__doc__ = ( """ Resolved route :param dict params: Pattern variables\ to URL parts :param object anything: Literally anything.\ This is attached to the URL pattern when\ registering it """) class Routes: """ Route URLs to registered URL patterns. Thread safety: adding routes is not thread-safe,\ it should be done on import time, everything else is. URL matcher supports ``:var`` for matching dynamic\ path parts and ``:*var`` for matching one or more parts. Path parts are matched in the following order: ``static > var > any-var``. Usage:: routes = kua.Routes() routes.add('api/:foo', {'GET': my_get_controller}) route = routes.match('api/hello-world') route.params # {'foo': 'hello-world'} route.anything # {'GET': my_get_controller} # Matching any path routes.add('assets/:*foo', {}) route = routes.match('assets/user/profile/avatar.jpg') route.params # {'foo': ('user', 'profile', 'avatar.jpg')} # Error handling try: route = routes.match('bad-url/some') except kua.RouteError: raise ValueError('Not found 404') else: # Do something useful here pass :ivar max_depth: The maximum URL depth\ (number of parts) willing to match. This only\ takes effect when one or more URLs matcher\ make use of any-var (i.e: ``:*var``), otherwise the\ depth of the deepest URL is taken. """ _VAR_NODE = ':var' _VAR_ANY_NODE = ':*var' _ROUTE_NODE = ':route' _VAR_ANY_BREAK = ':*break' def __init__(self, max_depth: int=40) -> None: """ :ivar _routes: \ Contain a graph with the parts of\ each URL pattern. This is referred as\ "partial route" later in the docs. :vartype _routes: dict :ivar _max_depth: Depth of the deepest\ registered pattern :vartype _max_depth: int :private-vars: """ self._max_depth_custom = max_depth # Routes graph format for 'foo/:foobar/bar': # { # 'foo': { # ':var': { # 'bar': { # ':route': _Route(), # ... # }, # ... # } # ... # }, # ... # } self._routes = {} self._max_depth = 0 def _deconstruct_url(self, url: str) -> List[str]: """ Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.RouteError: \ If the depth of the URL exceeds\ the max depth of the deepest\ registered pattern :private: """ parts = url.split('/', self._max_depth + 1) if depth_of(parts) > self._max_depth: raise RouteError('No match') return parts def _match(self, parts: Sequence[str]) -> RouteResolved: """ Match URL parts to a registered pattern. This function is basically where all\ the CPU-heavy work is done. :param parts: URL parts :return: Matched route :raises kua.routes.RouteError: If there is no match :private: """ route_match = None # type: RouteResolved route_variable_parts = tuple() # type: VariablePartsType # (route_partial, variable_parts, depth) to_visit = [(self._routes, tuple(), 0)] # type: List[Tuple[dict, tuple, int]] # Walk through the graph, # keep track of all possible # matching branches and do # backtracking if needed while to_visit: curr, curr_variable_parts, depth = to_visit.pop() try: part = parts[depth] except IndexError: if self._ROUTE_NODE in curr: route_match = curr[self._ROUTE_NODE] route_variable_parts = curr_variable_parts break else: continue if self._VAR_ANY_NODE in curr: to_visit.append(( {self._VAR_ANY_NODE: curr[self._VAR_ANY_NODE]}, (curr_variable_parts, (self._VAR_ANY_NODE, part)), depth + 1)) to_visit.append(( curr[self._VAR_ANY_NODE], (curr_variable_parts, (self._VAR_ANY_BREAK, part)), depth + 1)) if self._VAR_NODE in curr: to_visit.append(( curr[self._VAR_NODE], (curr_variable_parts, (self._VAR_NODE, part)), depth + 1)) if part in curr: to_visit.append(( curr[part], curr_variable_parts, depth + 1)) if not route_match: raise RouteError('No match') return RouteResolved( params=make_params( key_parts=route_match.key_parts, variable_parts=route_variable_parts), anything=route_match.anything) def match(self, url: str) -> RouteResolved: """ Match a URL to a registered pattern. :param url: URL :return: Matched route :raises kua.RouteError: If there is no match """ url = normalize_url(url) parts = self._deconstruct_url(url) return self._match(parts) def add(self, url: str, anything: Any) -> None: """ Register a URL pattern into\ the routes for later matching. It's possible to attach any kind of\ object to the pattern for later\ retrieving. A dict with methods and callbacks,\ for example. Anything really. Registration order does not matter.\ Adding a URL first or last makes no difference. :param url: URL :param anything: Literally anything. """ url = normalize_url(url) parts = url.split('/') curr_partial_routes = self._routes curr_key_parts = [] for part in parts: if part.startswith(':*'): curr_key_parts.append(part[2:]) part = self._VAR_ANY_NODE self._max_depth = self._max_depth_custom elif part.startswith(':'): curr_key_parts.append(part[1:]) part = self._VAR_NODE curr_partial_routes = (curr_partial_routes .setdefault(part, {})) curr_partial_routes[self._ROUTE_NODE] = _Route( key_parts=curr_key_parts, anything=anything) self._max_depth = max(self._max_depth, depth_of(parts)) from __future__ import unicode_literals import re from .subtitles import SubtitlesInfoExtractor from ..utils import ( parse_duration, unified_strdate, compat_urllib_parse, ) class RaiIE(SubtitlesInfoExtractor): _VALID_URL = r'(?Phttp://(?:.+?\.)?(?:rai\.it|rai\.tv|rainews\.it)/dl/.+?-(?P[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})(?:-.+?)?\.html)' _TESTS = [ { 'url': 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-cb27157f-9dd0-4aee-b788-b1f67643a391.html', 'md5': 'c064c0b2d09c278fb293116ef5d0a32d', 'info_dict': { 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391', 'ext': 'mp4', 'title': 'Report del 07/04/2014', 'description': 'md5:f27c544694cacb46a078db84ec35d2d9', 'upload_date': '20140407', 'duration': 6160, } }, { 'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html', 'md5': '8bb9c151924ce241b74dd52ef29ceafa', 'info_dict': { 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9', 'ext': 'mp4', 'title': 'TG PRIMO TEMPO', 'description': '', 'upload_date': '20140612', 'duration': 1758, }, 'skip': 'Error 404', }, { 'url': 'http://www.rainews.it/dl/rainews/media/state-of-the-net-Antonella-La-Carpia-regole-virali-7aafdea9-0e5d-49d5-88a6-7e65da67ae13.html', 'md5': '35cf7c229f22eeef43e48b5cf923bef0', 'info_dict': { 'id': '7aafdea9-0e5d-49d5-88a6-7e65da67ae13', 'ext': 'mp4', 'title': 'State of the Net, Antonella La Carpia: regole virali', 'description': 'md5:b0ba04a324126903e3da7763272ae63c', 'upload_date': '20140613', }, 'skip': 'Error 404', }, { 'url': 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-b4a49761-e0cc-4b14-8736-2729f6f73132-tg2.html', 'md5': '35694f062977fe6619943f08ed935730', 'info_dict': { 'id': 'b4a49761-e0cc-4b14-8736-2729f6f73132', 'ext': 'mp4', 'title': 'Alluvione in Sardegna e dissesto idrogeologico', 'description': 'Edizione delle ore 20:30 ', } }, ] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') media = self._download_json('%s?json' % mobj.group('url'), video_id, 'Downloading video JSON') title = media.get('name') description = media.get('desc') thumbnail = media.get('image_300') or media.get('image_medium') or media.get('image') duration = parse_duration(media.get('length')) uploader = media.get('author') upload_date = unified_strdate(media.get('date')) formats = [] for format_id in ['wmv', 'm3u8', 'mediaUri', 'h264']: media_url = media.get(format_id) if not media_url: continue formats.append({ 'url': media_url, 'format_id': format_id, 'ext': 'mp4', }) if self._downloader.params.get('listsubtitles', False): page = self._download_webpage(url, video_id) self._list_available_subtitles(video_id, page) return subtitles = {} if self._have_to_download_any_subtitles: page = self._download_webpage(url, video_id) subtitles = self.extract_subtitles(video_id, page) return { 'id': video_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'uploader': uploader, 'upload_date': upload_date, 'duration': duration, 'formats': formats, 'subtitles': subtitles, } def _get_available_subtitles(self, video_id, webpage): subtitles = {} m = re.search(r' 0: self.current_size -= 1 #!/usr/bin/env python # Renders a video. # To generate a 360 panoramic video: # blender -b photo_360.blend --python odm_video.py -- import sys import subprocess import os import bpy from common import loadMesh def main(): if len(sys.argv) < 7 or sys.argv[-4] != '--': sys.exit('Please provide the ODM project path, camera waypoints (xyz format), and number of frames.') projectHome = sys.argv[-3] waypointFile = sys.argv[-2] numFrames = int(sys.argv[-1]) loadMesh(projectHome + '/odm_texturing/odm_textured_model_geo.obj') waypoints = loadWaypoints(waypointFile) numWaypoints = len(waypoints) scene = bpy.data.scenes['Scene'] # create path thru waypoints curve = bpy.data.curves.new(name='CameraPath', type='CURVE') curve.dimensions = '3D' curve.twist_mode = 'Z_UP' nurbs = curve.splines.new('NURBS') nurbs.points.add(numWaypoints-1) weight = 1 for i in range(numWaypoints): nurbs.points[i].co[0] = waypoints[i][0] nurbs.points[i].co[1] = waypoints[i][1] nurbs.points[i].co[2] = waypoints[i][2] nurbs.points[i].co[3] = weight nurbs.use_endpoint_u = True path = bpy.data.objects.new(name='CameraPath', object_data=curve) scene.objects.link(path) camera = bpy.data.objects['Camera'] camera.location[0] = 0 camera.location[1] = 0 camera.location[2] = 0 followPath = camera.constraints.new(type='FOLLOW_PATH') followPath.name = 'CameraFollowPath' followPath.target = path followPath.use_curve_follow = True animateContext = bpy.context.copy() animateContext['constraint'] = followPath bpy.ops.constraint.followpath_path_animate(animateContext, constraint='CameraFollowPath', frame_start=0, length=numFrames) blendName = bpy.path.display_name_from_filepath(bpy.data.filepath) fileName = projectHome + '/odm_video/odm_' + blendName.replace('photo', 'video') scene.frame_start = 0 scene.frame_end = numFrames render = scene.render render.filepath = fileName + '.mp4' render.image_settings.file_format = 'FFMPEG' if(render.use_multiview): render.image_settings.stereo_3d_format.display_mode = 'TOPBOTTOM' render.image_settings.views_format = 'STEREO_3D' render.views[0].file_suffix = '' format3d = 'top-bottom' else: width = render.resolution_x height = render.resolution_y format3d = 'none' render.resolution_x = 4096 render.resolution_y = 2048 render.ffmpeg.audio_codec = 'AAC' render.ffmpeg.codec = 'H264' render.ffmpeg.format = 'MPEG4' render.ffmpeg.video_bitrate = 45000 bpy.ops.render.render(animation=True) writeMetadata(fileName+'.mp4', format3d) def loadWaypoints(filename): waypoints = [] with open(filename) as f: for line in f: xyz = line.split() waypoints.append((float(xyz[0]), float(xyz[1]), float(xyz[2]))) return waypoints def writeMetadata(filename, format3d): subprocess.run(['python', 'spatialmedia', '-i', '--stereo='+format3d, filename, filename+'.injected']) # check metadata injector was succesful if os.path.exists(filename+'.injected'): os.remove(filename) os.rename(filename+'.injected', filename) if __name__ == '__main__': main() # Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. # ============================================================================== """Tests for tf.bitcast.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.platform import test class BitcastTest(test.TestCase): def _testBitcast(self, x, datatype, shape): with self.test_session(use_gpu=True): tf_ans = array_ops.bitcast(x, datatype) out = tf_ans.eval() buff_after = memoryview(out).tobytes() buff_before = memoryview(x).tobytes() self.assertEqual(buff_before, buff_after) self.assertEqual(tf_ans.get_shape(), shape) self.assertEqual(tf_ans.dtype, datatype) def testSmaller(self): x = np.random.rand(3, 2) datatype = dtypes.int8 shape = [3, 2, 8] self._testBitcast(x, datatype, shape) def testLarger(self): x = np.arange(16, dtype=np.int8).reshape([4, 4]) datatype = dtypes.int32 shape = [4] self._testBitcast(x, datatype, shape) def testSameDtype(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, x.dtype, shape) def testSameSize(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, dtypes.int64, shape) def testErrors(self): x = np.zeros([1, 1], np.int8) datatype = dtypes.int32 with self.assertRaisesRegexp(ValueError, "Cannot bitcast due to shape"): array_ops.bitcast(x, datatype, None) def testEmpty(self): x = np.ones([], np.int32) datatype = dtypes.int8 shape = [4] self._testBitcast(x, datatype, shape) def testUnknown(self): x = array_ops.placeholder(dtypes.float32) datatype = dtypes.int8 array_ops.bitcast(x, datatype, None) def testQuantizeType(self): shape = [3, 4] x = np.zeros(shape, np.uint16) datatype = dtypes.quint16 self._testBitcast(x, datatype, shape) if __name__ == "__main__": test.main() #!/usr/bin/env python # -*- coding: utf-8 -*- # winapi.py: Windows API-Python interface (removes dependency on pywin32) # # Copyright (C) 2007 Thomas Heller # Copyright (C) 2010 Will McGugan # Copyright (C) 2010 Ryan Kelly # Copyright (C) 2010 Yesudeep Mangalapilly # Copyright (C) 2014 Thomas Amland # 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 organization 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 HOLDER 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. # # Portions of this code were taken from pyfilesystem, which uses the above # new BSD license. from __future__ import with_statement import ctypes.wintypes import struct from functools import reduce try: LPVOID = ctypes.wintypes.LPVOID except AttributeError: # LPVOID wasn't defined in Py2.5, guess it was introduced in Py2.6 LPVOID = ctypes.c_void_p # Invalid handle value. INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value # File notification contants. FILE_NOTIFY_CHANGE_FILE_NAME = 0x01 FILE_NOTIFY_CHANGE_DIR_NAME = 0x02 FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x04 FILE_NOTIFY_CHANGE_SIZE = 0x08 FILE_NOTIFY_CHANGE_LAST_WRITE = 0x010 FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x020 FILE_NOTIFY_CHANGE_CREATION = 0x040 FILE_NOTIFY_CHANGE_SECURITY = 0x0100 FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 FILE_FLAG_OVERLAPPED = 0x40000000 FILE_LIST_DIRECTORY = 0x01 FILE_SHARE_READ = 0x01 FILE_SHARE_WRITE = 0x02 FILE_SHARE_DELETE = 0x04 OPEN_EXISTING = 3 # File action constants. FILE_ACTION_CREATED = 1 FILE_ACTION_DELETED = 2 FILE_ACTION_MODIFIED = 3 FILE_ACTION_RENAMED_OLD_NAME = 4 FILE_ACTION_RENAMED_NEW_NAME = 5 FILE_ACTION_OVERFLOW = 0xFFFF # Aliases FILE_ACTION_ADDED = FILE_ACTION_CREATED FILE_ACTION_REMOVED = FILE_ACTION_DELETED THREAD_TERMINATE = 0x0001 # IO waiting constants. WAIT_ABANDONED = 0x00000080 WAIT_IO_COMPLETION = 0x000000C0 WAIT_OBJECT_0 = 0x00000000 WAIT_TIMEOUT = 0x00000102 # Error codes ERROR_OPERATION_ABORTED = 995 class OVERLAPPED(ctypes.Structure): _fields_ = [('Internal', LPVOID), ('InternalHigh', LPVOID), ('Offset', ctypes.wintypes.DWORD), ('OffsetHigh', ctypes.wintypes.DWORD), ('Pointer', LPVOID), ('hEvent', ctypes.wintypes.HANDLE), ] def _errcheck_bool(value, func, args): if not value: raise ctypes.WinError() return args def _errcheck_handle(value, func, args): if not value: raise ctypes.WinError() if value == INVALID_HANDLE_VALUE: raise ctypes.WinError() return args def _errcheck_dword(value, func, args): if value == 0xFFFFFFFF: raise ctypes.WinError() return args ReadDirectoryChangesW = ctypes.windll.kernel32.ReadDirectoryChangesW ReadDirectoryChangesW.restype = ctypes.wintypes.BOOL ReadDirectoryChangesW.errcheck = _errcheck_bool ReadDirectoryChangesW.argtypes = ( ctypes.wintypes.HANDLE, # hDirectory LPVOID, # lpBuffer ctypes.wintypes.DWORD, # nBufferLength ctypes.wintypes.BOOL, # bWatchSubtree ctypes.wintypes.DWORD, # dwNotifyFilter ctypes.POINTER(ctypes.wintypes.DWORD), # lpBytesReturned ctypes.POINTER(OVERLAPPED), # lpOverlapped LPVOID # FileIOCompletionRoutine # lpCompletionRoutine ) CreateFileW = ctypes.windll.kernel32.CreateFileW CreateFileW.restype = ctypes.wintypes.HANDLE CreateFileW.errcheck = _errcheck_handle CreateFileW.argtypes = ( ctypes.wintypes.LPCWSTR, # lpFileName ctypes.wintypes.DWORD, # dwDesiredAccess ctypes.wintypes.DWORD, # dwShareMode LPVOID, # lpSecurityAttributes ctypes.wintypes.DWORD, # dwCreationDisposition ctypes.wintypes.DWORD, # dwFlagsAndAttributes ctypes.wintypes.HANDLE # hTemplateFile ) CloseHandle = ctypes.windll.kernel32.CloseHandle CloseHandle.restype = ctypes.wintypes.BOOL CloseHandle.argtypes = ( ctypes.wintypes.HANDLE, # hObject ) CancelIoEx = ctypes.windll.kernel32.CancelIoEx CancelIoEx.restype = ctypes.wintypes.BOOL CancelIoEx.errcheck = _errcheck_bool CancelIoEx.argtypes = ( ctypes.wintypes.HANDLE, # hObject ctypes.POINTER(OVERLAPPED) # lpOverlapped ) CreateEvent = ctypes.windll.kernel32.CreateEventW CreateEvent.restype = ctypes.wintypes.HANDLE CreateEvent.errcheck = _errcheck_handle CreateEvent.argtypes = ( LPVOID, # lpEventAttributes ctypes.wintypes.BOOL, # bManualReset ctypes.wintypes.BOOL, # bInitialState ctypes.wintypes.LPCWSTR, # lpName ) SetEvent = ctypes.windll.kernel32.SetEvent SetEvent.restype = ctypes.wintypes.BOOL SetEvent.errcheck = _errcheck_bool SetEvent.argtypes = ( ctypes.wintypes.HANDLE, # hEvent ) WaitForSingleObjectEx = ctypes.windll.kernel32.WaitForSingleObjectEx WaitForSingleObjectEx.restype = ctypes.wintypes.DWORD WaitForSingleObjectEx.errcheck = _errcheck_dword WaitForSingleObjectEx.argtypes = ( ctypes.wintypes.HANDLE, # hObject ctypes.wintypes.DWORD, # dwMilliseconds ctypes.wintypes.BOOL, # bAlertable ) CreateIoCompletionPort = ctypes.windll.kernel32.CreateIoCompletionPort CreateIoCompletionPort.restype = ctypes.wintypes.HANDLE CreateIoCompletionPort.errcheck = _errcheck_handle CreateIoCompletionPort.argtypes = ( ctypes.wintypes.HANDLE, # FileHandle ctypes.wintypes.HANDLE, # ExistingCompletionPort LPVOID, # CompletionKey ctypes.wintypes.DWORD, # NumberOfConcurrentThreads ) GetQueuedCompletionStatus = ctypes.windll.kernel32.GetQueuedCompletionStatus GetQueuedCompletionStatus.restype = ctypes.wintypes.BOOL GetQueuedCompletionStatus.errcheck = _errcheck_bool GetQueuedCompletionStatus.argtypes = ( ctypes.wintypes.HANDLE, # CompletionPort LPVOID, # lpNumberOfBytesTransferred LPVOID, # lpCompletionKey ctypes.POINTER(OVERLAPPED), # lpOverlapped ctypes.wintypes.DWORD, # dwMilliseconds ) PostQueuedCompletionStatus = ctypes.windll.kernel32.PostQueuedCompletionStatus PostQueuedCompletionStatus.restype = ctypes.wintypes.BOOL PostQueuedCompletionStatus.errcheck = _errcheck_bool PostQueuedCompletionStatus.argtypes = ( ctypes.wintypes.HANDLE, # CompletionPort ctypes.wintypes.DWORD, # lpNumberOfBytesTransferred ctypes.wintypes.DWORD, # lpCompletionKey ctypes.POINTER(OVERLAPPED), # lpOverlapped ) class FILE_NOTIFY_INFORMATION(ctypes.Structure): _fields_ = [("NextEntryOffset", ctypes.wintypes.DWORD), ("Action", ctypes.wintypes.DWORD), ("FileNameLength", ctypes.wintypes.DWORD), #("FileName", (ctypes.wintypes.WCHAR * 1))] ("FileName", (ctypes.c_char * 1))] LPFNI = ctypes.POINTER(FILE_NOTIFY_INFORMATION) # We don't need to recalculate these flags every time a call is made to # the win32 API functions. WATCHDOG_FILE_FLAGS = FILE_FLAG_BACKUP_SEMANTICS WATCHDOG_FILE_SHARE_FLAGS = reduce( lambda x, y: x | y, [ FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_DELETE, ]) WATCHDOG_FILE_NOTIFY_FLAGS = reduce( lambda x, y: x | y, [ FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_DIR_NAME, FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SECURITY, FILE_NOTIFY_CHANGE_LAST_ACCESS, FILE_NOTIFY_CHANGE_CREATION, ]) BUFFER_SIZE = 2048 def _parse_event_buffer(readBuffer, nBytes): results = [] while nBytes > 0: fni = ctypes.cast(readBuffer, LPFNI)[0] ptr = ctypes.addressof(fni) + FILE_NOTIFY_INFORMATION.FileName.offset #filename = ctypes.wstring_at(ptr, fni.FileNameLength) filename = ctypes.string_at(ptr, fni.FileNameLength) results.append((fni.Action, filename.decode('utf-16'))) numToSkip = fni.NextEntryOffset if numToSkip <= 0: break readBuffer = readBuffer[numToSkip:] nBytes -= numToSkip # numToSkip is long. nBytes should be long too. return results def get_directory_handle(path): """Returns a Windows handle to the specified directory path.""" return CreateFileW(path, FILE_LIST_DIRECTORY, WATCHDOG_FILE_SHARE_FLAGS, None, OPEN_EXISTING, WATCHDOG_FILE_FLAGS, None) def close_directory_handle(handle): try: CancelIoEx(handle, None) # force ReadDirectoryChangesW to return CloseHandle(handle) # close directory handle except WindowsError: try: CloseHandle(handle) # close directory handle except: return def read_directory_changes(handle, recursive): """Read changes to the directory using the specified directory handle. http://timgolden.me.uk/pywin32-docs/win32file__ReadDirectoryChangesW_meth.html """ event_buffer = ctypes.create_string_buffer(BUFFER_SIZE) nbytes = ctypes.wintypes.DWORD() try: ReadDirectoryChangesW(handle, ctypes.byref(event_buffer), len(event_buffer), recursive, WATCHDOG_FILE_NOTIFY_FLAGS, ctypes.byref(nbytes), None, None) except WindowsError as e: if e.winerror == ERROR_OPERATION_ABORTED: return [], 0 raise e # Python 2/3 compat try: int_class = long except NameError: int_class = int return event_buffer.raw, int_class(nbytes.value) class WinAPINativeEvent(object): def __init__(self, action, src_path): self.action = action self.src_path = src_path @property def is_added(self): return self.action == FILE_ACTION_CREATED @property def is_removed(self): return self.action == FILE_ACTION_REMOVED @property def is_modified(self): return self.action == FILE_ACTION_MODIFIED @property def is_renamed_old(self): return self.action == FILE_ACTION_RENAMED_OLD_NAME @property def is_renamed_new(self): return self.action == FILE_ACTION_RENAMED_NEW_NAME def __repr__(self): return ("" % (self.action, self.src_path)) def read_events(handle, recursive): buf, nbytes = read_directory_changes(handle, recursive) events = _parse_event_buffer(buf, nbytes) return [WinAPINativeEvent(action, path) for action, path in events] """Support for non-delivered packages recorded in AfterShip.""" from __future__ import annotations import logging from typing import Any, Final from pyaftership.tracker import Tracking import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA as BASE_PLATFORM_SCHEMA, SensorEntity, ) from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_NAME, HTTP_OK from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.service import ServiceCall from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.util import Throttle from .const import ( ADD_TRACKING_SERVICE_SCHEMA, ATTR_TRACKINGS, ATTRIBUTION, BASE, CONF_SLUG, CONF_TITLE, CONF_TRACKING_NUMBER, DEFAULT_NAME, DOMAIN, ICON, MIN_TIME_BETWEEN_UPDATES, REMOVE_TRACKING_SERVICE_SCHEMA, SERVICE_ADD_TRACKING, SERVICE_REMOVE_TRACKING, UPDATE_TOPIC, ) _LOGGER: Final = logging.getLogger(__name__) PLATFORM_SCHEMA: Final = BASE_PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the AfterShip sensor platform.""" apikey = config[CONF_API_KEY] name = config[CONF_NAME] session = async_get_clientsession(hass) aftership = Tracking(hass.loop, session, apikey) await aftership.get_trackings() if not aftership.meta or aftership.meta["code"] != HTTP_OK: _LOGGER.error( "No tracking data found. Check API key is correct: %s", aftership.meta ) return instance = AfterShipSensor(aftership, name) async_add_entities([instance], True) async def handle_add_tracking(call: ServiceCall) -> None: """Call when a user adds a new Aftership tracking from Home Assistant.""" title = call.data.get(CONF_TITLE) slug = call.data.get(CONF_SLUG) tracking_number = call.data[CONF_TRACKING_NUMBER] await aftership.add_package_tracking(tracking_number, title, slug) async_dispatcher_send(hass, UPDATE_TOPIC) hass.services.async_register( DOMAIN, SERVICE_ADD_TRACKING, handle_add_tracking, schema=ADD_TRACKING_SERVICE_SCHEMA, ) async def handle_remove_tracking(call: ServiceCall) -> None: """Call when a user removes an Aftership tracking from Home Assistant.""" slug = call.data[CONF_SLUG] tracking_number = call.data[CONF_TRACKING_NUMBER] await aftership.remove_package_tracking(slug, tracking_number) async_dispatcher_send(hass, UPDATE_TOPIC) hass.services.async_register( DOMAIN, SERVICE_REMOVE_TRACKING, handle_remove_tracking, schema=REMOVE_TRACKING_SERVICE_SCHEMA, ) class AfterShipSensor(SensorEntity): """Representation of a AfterShip sensor.""" def __init__(self, aftership: Tracking, name: str) -> None: """Initialize the sensor.""" self._attributes: dict[str, Any] = {} self._name: str = name self._state: int | None = None self.aftership = aftership @property def name(self) -> str: """Return the name of the sensor.""" return self._name @property def state(self) -> int | None: """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self) -> str: """Return the unit of measurement of this entity, if any.""" return "packages" @property def extra_state_attributes(self) -> dict[str, str]: """Return attributes for the sensor.""" return self._attributes @property def icon(self) -> str: """Icon to use in the frontend.""" return ICON async def async_added_to_hass(self) -> None: """Register callbacks.""" self.async_on_remove( self.hass.helpers.dispatcher.async_dispatcher_connect( UPDATE_TOPIC, self._force_update ) ) async def _force_update(self) -> None: """Force update of data.""" await self.async_update(no_throttle=True) self.async_write_ha_state() @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self, **kwargs: Any) -> None: """Get the latest data from the AfterShip API.""" await self.aftership.get_trackings() if not self.aftership.meta: _LOGGER.error("Unknown errors when querying") return if self.aftership.meta["code"] != HTTP_OK: _LOGGER.error( "Errors when querying AfterShip. %s", str(self.aftership.meta) ) return status_to_ignore = {"delivered"} status_counts: dict[str, int] = {} trackings = [] not_delivered_count = 0 for track in self.aftership.trackings["trackings"]: status = track["tag"].lower() name = ( track["tracking_number"] if track["title"] is None else track["title"] ) last_checkpoint = ( f"Shipment {track['tag'].lower()}" if not track["checkpoints"] else track["checkpoints"][-1] ) status_counts[status] = status_counts.get(status, 0) + 1 trackings.append( { "name": name, "tracking_number": track["tracking_number"], "slug": track["slug"], "link": f"{BASE}{track['slug']}/{track['tracking_number']}", "last_update": track["updated_at"], "expected_delivery": track["expected_delivery"], "status": track["tag"], "last_checkpoint": last_checkpoint, } ) if status not in status_to_ignore: not_delivered_count += 1 else: _LOGGER.debug("Ignoring %s as it has status: %s", name, status) self._attributes = { ATTR_ATTRIBUTION: ATTRIBUTION, **status_counts, ATTR_TRACKINGS: trackings, } self._state = not_delivered_count # pylint:disable=missing-docstring,no-member import datetime import json import uuid # pylint:disable=unused-import from django.contrib.auth.models import User import factory from factory.fuzzy import FuzzyText import pytz from openedx.core.djangoapps.credit.models import CreditProvider, CreditEligibility, CreditCourse, CreditRequest from util.date_utils import to_timestamp class CreditCourseFactory(factory.DjangoModelFactory): class Meta(object): model = CreditCourse course_key = FuzzyText(prefix='fake.org/', suffix='/fake.run') enabled = True class CreditProviderFactory(factory.DjangoModelFactory): class Meta(object): model = CreditProvider provider_id = FuzzyText(length=5) provider_url = FuzzyText(prefix='http://') class CreditEligibilityFactory(factory.DjangoModelFactory): class Meta(object): model = CreditEligibility course = factory.SubFactory(CreditCourseFactory) class CreditRequestFactory(factory.DjangoModelFactory): class Meta(object): model = CreditRequest uuid = factory.LazyAttribute(lambda o: uuid.uuid4().hex) # pylint: disable=undefined-variable # pylint: disable=access-member-before-definition,attribute-defined-outside-init,no-self-argument,unused-argument @factory.post_generation def post(obj, create, extracted, **kwargs): """ Post-generation handler. Sets up parameters field. """ if not obj.parameters: course_key = obj.course.course_key user = User.objects.get(username=obj.username) user_profile = user.profile # pylint:disable=access-member-before-definition obj.parameters = json.dumps({ "request_uuid": obj.uuid, "timestamp": to_timestamp(datetime.datetime.now(pytz.UTC)), "course_org": course_key.org, "course_num": course_key.course, "course_run": course_key.run, "final_grade": '0.96', "user_username": user.username, "user_email": user.email, "user_full_name": user_profile.name, "user_mailing_address": "", "user_country": user_profile.country.code or "", }) obj.save() # -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import logging from eve.versioning import versioned_id_field from flask import g, current_app as app from eve.utils import config, ParsedRequest from .resource import LEGAL_ARCHIVE_NAME from superdesk import Service, get_resource_privileges from superdesk.errors import SuperdeskApiError from superdesk.metadata.item import ITEM_TYPE, GUID_FIELD, CONTENT_TYPE from superdesk.metadata.packages import GROUPS, RESIDREF, REFS from superdesk.utils import ListCursor logger = logging.getLogger(__name__) class LegalService(Service): """ Base Service Class for Legal Archive related services """ def on_create(self, docs): """ Overriding to replace the location of each item in the package to legal archive instead of archive, if doc is a pacakge. """ super().on_create(docs) for doc in docs: if ITEM_TYPE in doc: doc.setdefault(config.ID_FIELD, doc[GUID_FIELD]) if doc[ITEM_TYPE] == CONTENT_TYPE.COMPOSITE: self._change_location_of_items_in_package(doc) def on_replace(self, document, original): """ Overriding to replace the location of each item in the package to legal archive instead of archive, if doc is a pacakge. """ super().on_replace(document, original) if document.get(ITEM_TYPE) == CONTENT_TYPE.COMPOSITE: self._change_location_of_items_in_package(document) def get(self, req, lookup): """ Overriding to check if user is authorized to perform get operation on Legal Archive resources. If authorized then request is forwarded otherwise throws forbidden error. :return: list of docs matching query in req and lookup :raises: SuperdeskApiError.forbiddenError() if user is unauthorized to access the Legal Archive resources. """ self.check_get_access_privilege() return super().get(req, lookup) def find_one(self, req, **lookup): """ Overriding to check if user is authorized to perform get operation on Legal Archive resources. If authorized then request is forwarded otherwise throws forbidden error. :return: doc if there is one matching the query in req and lookup :raises: SuperdeskApiError.forbiddenError() if user is unauthorized to access the Legal Archive resources. """ self.check_get_access_privilege() return super().find_one(req, **lookup) def check_get_access_privilege(self): """ Checks if user is authorized to perform get operation on Legal Archive resources. If authorized then request is forwarded otherwise throws forbidden error. :raises: SuperdeskApiError.forbiddenError() if user is unauthorized to access the Legal Archive resources. """ if not hasattr(g, 'user'): return privileges = g.user.get('active_privileges', {}) resource_privileges = get_resource_privileges(self.datasource).get('GET', None) if privileges.get(resource_privileges, 0) == 0: raise SuperdeskApiError.forbiddenError() def enhance(self, legal_archive_docs): """ Enhances the item in Legal Archive Service :param legal_archive_docs: """ if isinstance(legal_archive_docs, list): for legal_archive_doc in legal_archive_docs: legal_archive_doc['_type'] = LEGAL_ARCHIVE_NAME else: legal_archive_docs['_type'] = LEGAL_ARCHIVE_NAME def _change_location_of_items_in_package(self, package): """ Changes location of each item in the package to legal archive instead of archive. """ for group in package.get(GROUPS, []): for ref in group.get(REFS, []): if RESIDREF in ref: ref['location'] = LEGAL_ARCHIVE_NAME class LegalArchiveService(LegalService): def on_fetched(self, docs): """ Overriding this to enhance the published article with the one in archive collection """ self.enhance(docs[config.ITEMS]) def on_fetched_item(self, doc): """ Overriding this to enhance the published article with the one in archive collection """ self.enhance(doc) class LegalPublishQueueService(LegalService): def create(self, docs, **kwargs): """ Overriding this from preventing the transmission details again. This happens when an item in a package expires at later point of time. In this case, the call to insert transmission details happens twice once when the package expires and once when the item expires. """ ids = [] for doc in docs: doc_if_exists = self.find_one(req=None, _id=doc['_id']) if doc_if_exists is None: ids.extend(super().create([doc])) return ids class LegalArchiveVersionsService(LegalService): def create(self, docs, **kwargs): """ Overriding this from preventing the same version again. This happens when an item is published more than once. """ ids = [] for doc in docs: doc_if_exists = None if config.ID_FIELD in doc: # This happens when inserting docs from pre-populate command doc_if_exists = self.find_one(req=None, _id=doc['_id']) if doc_if_exists is None: ids.extend(super().create([doc])) return ids def get(self, req, lookup): """ Version of an article in Legal Archive isn't maintained by Eve. Overriding this to fetch the version history. """ resource_def = app.config['DOMAIN'][LEGAL_ARCHIVE_NAME] id_field = versioned_id_field(resource_def) if req and req.args and req.args.get(config.ID_FIELD): version_history = list(super().get_from_mongo(req=ParsedRequest(), lookup={id_field: req.args.get(config.ID_FIELD)})) else: version_history = list(super().get_from_mongo(req=req, lookup=lookup)) for doc in version_history: doc[config.ID_FIELD] = doc[id_field] self.enhance(doc) return ListCursor(version_history) from django import forms from django.utils.translation import ugettext_lazy as _ # While this couples the geographic forms to the GEOS library, # it decouples from database (by not importing SpatialBackend). from django.contrib.gis.geos import GEOSGeometry class GeometryField(forms.Field): """ This is the basic form field for a Geometry. Any textual input that is accepted by GEOSGeometry is accepted by this form. By default, this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON. """ widget = forms.Textarea default_error_messages = { 'no_geom' : _(u'No geometry value provided.'), 'invalid_geom' : _(u'Invalid geometry value.'), 'invalid_geom_type' : _(u'Invalid geometry type.'), 'transform_error' : _(u'An error occurred when transforming the geometry ' 'to the SRID of the geometry form field.'), } def __init__(self, **kwargs): # Pop out attributes from the database field, or use sensible # defaults (e.g., allow None). self.srid = kwargs.pop('srid', None) self.geom_type = kwargs.pop('geom_type', 'GEOMETRY') self.null = kwargs.pop('null', True) super(GeometryField, self).__init__(**kwargs) def clean(self, value): """ Validates that the input value can be converted to a Geometry object (which is returned). A ValidationError is raised if the value cannot be instantiated as a Geometry. """ if not value: if self.null and not self.required: # The geometry column allows NULL and is not required. return None else: raise forms.ValidationError(self.error_messages['no_geom']) # Trying to create a Geometry object from the form value. try: geom = GEOSGeometry(value) except: raise forms.ValidationError(self.error_messages['invalid_geom']) # Ensuring that the geometry is of the correct type (indicated # using the OGC string label). if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY': raise forms.ValidationError(self.error_messages['invalid_geom_type']) # Transforming the geometry if the SRID was set. if self.srid: if not geom.srid: # Should match that of the field if not given. geom.srid = self.srid elif self.srid != -1 and self.srid != geom.srid: try: geom.transform(self.srid) except: raise forms.ValidationError(self.error_messages['transform_error']) return geom """ South Africa-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField from django.utils.checksums import luhn from django.utils.translation import gettext as _ import re from datetime import date id_re = re.compile(r'^(?P\d\d)(?P\d\d)(?P
\d\d)(?P\d{4})(?P\d{3})') class ZAIDField(Field): """A form field for South African ID numbers -- the checksum is validated using the Luhn checksum, and uses a simlistic (read: not entirely accurate) check for the birthdate """ default_error_messages = { 'invalid': _(u'Enter a valid South African ID number'), } def clean(self, value): super(ZAIDField, self).clean(value) if value in EMPTY_VALUES: return u'' # strip spaces and dashes value = value.strip().replace(' ', '').replace('-', '') match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) g = match.groupdict() try: # The year 2000 is conveniently a leapyear. # This algorithm will break in xx00 years which aren't leap years # There is no way to guess the century of a ZA ID number d = date(int(g['yy']) + 2000, int(g['mm']), int(g['dd'])) except ValueError: raise ValidationError(self.error_messages['invalid']) if not luhn(value): raise ValidationError(self.error_messages['invalid']) return value class ZAPostCodeField(RegexField): default_error_messages = { 'invalid': _(u'Enter a valid South African postal code'), } def __init__(self, *args, **kwargs): super(ZAPostCodeField, self).__init__(r'^\d{4}$', max_length=None, min_length=None, *args, **kwargs) # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not 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. # coding: utf-8 # pylint: disable= arguments-differ """Alexnet, implemented in Gluon.""" __all__ = ['AlexNet', 'alexnet'] import os from ....context import cpu from ...block import HybridBlock from ... import nn from .... import base # Net class AlexNet(HybridBlock): r"""AlexNet model from the `"One weird trick..." `_ paper. Parameters ---------- classes : int, default 1000 Number of classes for the output layer. """ def __init__(self, classes=1000, **kwargs): super(AlexNet, self).__init__(**kwargs) with self.name_scope(): self.features = nn.HybridSequential(prefix='') with self.features.name_scope(): self.features.add(nn.Conv2D(64, kernel_size=11, strides=4, padding=2, activation='relu')) self.features.add(nn.MaxPool2D(pool_size=3, strides=2)) self.features.add(nn.Conv2D(192, kernel_size=5, padding=2, activation='relu')) self.features.add(nn.MaxPool2D(pool_size=3, strides=2)) self.features.add(nn.Conv2D(384, kernel_size=3, padding=1, activation='relu')) self.features.add(nn.Conv2D(256, kernel_size=3, padding=1, activation='relu')) self.features.add(nn.Conv2D(256, kernel_size=3, padding=1, activation='relu')) self.features.add(nn.MaxPool2D(pool_size=3, strides=2)) self.features.add(nn.Flatten()) self.features.add(nn.Dense(4096, activation='relu')) self.features.add(nn.Dropout(0.5)) self.features.add(nn.Dense(4096, activation='relu')) self.features.add(nn.Dropout(0.5)) self.output = nn.Dense(classes) def hybrid_forward(self, F, x): x = self.features(x) x = self.output(x) return x # Constructor def alexnet(pretrained=False, ctx=cpu(), root=os.path.join(base.data_dir(), 'models'), **kwargs): r"""AlexNet model from the `"One weird trick..." `_ paper. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default $MXNET_HOME/models Location for keeping the model parameters. """ net = AlexNet(**kwargs) if pretrained: from ..model_store import get_model_file net.load_parameters(get_model_file('alexnet', root=root), ctx=ctx) return net #!/usr/bin/env python # -*- coding: UTF-8 -*- """ Copyright (c) 2016, Kersten Doering """ # import modules # to connect to Xapian import xappy # debug: sys.exit(0) import sys # path options import os # runtime import time # to connect to PostgreSQL import psycopg2 from psycopg2 import extras # log start time start = time.asctime() # set options verbose, output and whether PostgreSQL should be used to display results output = True verbose = True debug = False use_psql = True # get path to this script root = os.getcwd() # search connection to Xapian full text index xapianPath = os.path.join( root, "xapian_PMC_complete" ) searchConn = xappy.SearchConnection(xapianPath) searchConn.reopen() # get PMC texts from PostgreSQL def get_text(pmcid): stmt = """ SELECT text FROM public.tbl_pmcid_text WHERE pmcid = %s ; """ cursor.execute(stmt, (pmcid,)) output = cursor.fetchone() return output[0] # settings PostgreSQL connection with user parser postgres_user = "parser" postgres_password = "parser" postgres_host = "localhost" postgres_port = "5432" postgres_db = "pancreatic_cancer_db" connection = psycopg2.connect("dbname='"+postgres_db+"' user='"+postgres_user+"' host='"+postgres_host+"' password='"+postgres_password+"' port='"+postgres_port+"'") cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) # get search terms (synonyms) synonyms = [] infile = open("synonyms/synonyms.txt","r") for line in infile: synonyms.append(line.strip()) infile.close() # write results to file with PMC ID and identified synonym if option output if output: outfile = open("results/results.csv","w") # search synonyms for term in synonyms: # use exact search with quotations text = '"'+term + '"' # build query query = searchConn.query_field('text', text ) # show query syntax if option verbose: if verbose: print query # search and get results results=searchConn.search(query, 0, searchConn.get_doccount()) # iterate over results for r in results: # write to file if option output: if output: outfile.write(r.id + "\t" + term + "\n") # option verbose: if verbose and not use_psql: print "################" print r.id print r.data['text'][0][0:90] + "..." print "################" if verbose and use_psql: print "################" print r.id print get_text(r.id)[0:90] + "..." print "################" # terminate here to have a look at the first result if option debug: if debug: sys.exit(0) # show number of results if option verbose if verbose: print "#results: ", len(results) # close file if option output if output: outfile.close() # log end time end = time.asctime() # show runtime print "programme started - " + start print "programme ended - " + end ''' Challenge 3.2 Queue To Do =========== You're almost ready to make your move to destroy the LAMBCHOP doomsday device, but the security checkpoints that guard the underlying systems of the LAMBCHOP are going to be a problem. You were able to take one down without tripping any alarms, which is great! Except that as Commander Lambda's assistant, you've learned that the checkpoints are about to come under automated review, which means that your sabotage will be discovered and your cover blown - unless you can trick the automated review system. To trick the system, you'll need to write a program to return the same security checksum that the guards would have after they would have checked all the workers through. Fortunately, Commander Lambda's desire for efficiency won't allow for hours-long lines, so the checkpoint guards have found ways to quicken the pass-through rate. Instead of checking each and every worker coming through, the guards instead go over everyone in line while noting their security IDs, then allow the line to fill back up. Once they've done that they go over the line again, this time leaving off the last worker. They continue doing this, leaving off one more worker from the line each time but recording the security IDs of those they do check, until they skip the entire line, at which point they XOR the IDs of all the workers they noted into a checksum and then take off for lunch. Fortunately, the workers' orderly nature causes them to always line up in numerical order without any gaps. For example, if the first worker in line has ID 0 and the security checkpoint line holds three workers, the process would look like this: 0 1 2 / 3 4 / 5 6 / 7 8 where the guards' XOR (^) checksum is 0^1^2^3^4^6 == 2. Likewise, if the first worker has ID 17 and the checkpoint holds four workers, the process would look like: 17 18 19 20 / 21 22 23 / 24 25 26 / 27 28 29 / 30 31 32 which produces the checksum 17^18^19^20^21^22^23^25^26^29 == 14. All worker IDs (including the first worker) are between 0 and 2000000000 inclusive, and the checkpoint line will always be at least 1 worker long. With this information, write a function answer(start, length) that will cover for the missing security checkpoint by outputting the same checksum the guards would normally submit before lunch. You have just enough time to find out the ID of the first worker to be checked (start) and the length of the line (length) before the automatic review occurs, so your program must generate the proper checksum with just those two values. Languages ========= To provide a Python solution, edit solution.py To provide a Java solution, edit solution.java Test cases ========== Inputs: (int) start = 0 (int) length = 3 Output: (int) 2 Inputs: (int) start = 17 (int) length = 4 Output: (int) 14 ''' def getXOR(start, end): if (end - start) == 0: return 0 if (end - start) == 1: return start if (end - start) <= 4: return reduce(lambda x, y: x ^ y, range(start, end)) else: begin_range = (start, start / 4 * 4 + 4) end_range = (end / 4 * 4, end) return getXOR(*begin_range) ^ getXOR(*end_range) def answer(start, length): worker_list = [(start + (length - l) * length, start + (length - l) * length + l) for l in range(length, 0, -1)] new_xor = [getXOR(start, end) for start, end in worker_list] return reduce(lambda x, y: x ^ y, new_xor) #print(answer(0, 3)) print(answer(17, 4)) #print(answer(200000, 25000)) # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt """Python source expertise for coverage.py""" import os.path import types import zipimport from coverage import env, files from coverage.misc import contract, expensive, isolate_module, join_regex from coverage.misc import CoverageException, NoSource from coverage.parser import PythonParser from coverage.phystokens import source_token_lines, source_encoding from coverage.plugin import FileReporter os = isolate_module(os) @contract(returns='bytes') def read_python_source(filename): """Read the Python source text from `filename`. Returns bytes. """ with open(filename, "rb") as f: source = f.read() if env.IRONPYTHON: # IronPython reads Unicode strings even for "rb" files. source = bytes(source) return source.replace(b"\r\n", b"\n").replace(b"\r", b"\n") @contract(returns='unicode') def get_python_source(filename): """Return the source code, as unicode.""" base, ext = os.path.splitext(filename) if ext == ".py" and env.WINDOWS: exts = [".py", ".pyw"] else: exts = [ext] for ext in exts: try_filename = base + ext if os.path.exists(try_filename): # A regular text file: open it. source = read_python_source(try_filename) break # Maybe it's in a zip file? source = get_zip_bytes(try_filename) if source is not None: break else: # Couldn't find source. exc_msg = "No source for code: '%s'.\n" % (filename,) exc_msg += "Aborting report output, consider using -i." raise NoSource(exc_msg) # Replace \f because of http://bugs.python.org/issue19035 source = source.replace(b'\f', b' ') source = source.decode(source_encoding(source), "replace") # Python code should always end with a line with a newline. if source and source[-1] != '\n': source += '\n' return source @contract(returns='bytes|None') def get_zip_bytes(filename): """Get data from `filename` if it is a zip file path. Returns the bytestring data read from the zip file, or None if no zip file could be found or `filename` isn't in it. The data returned will be an empty string if the file is empty. """ markers = ['.zip'+os.sep, '.egg'+os.sep, '.pex'+os.sep] for marker in markers: if marker in filename: parts = filename.split(marker) try: zi = zipimport.zipimporter(parts[0]+marker[:-1]) except zipimport.ZipImportError: continue try: data = zi.get_data(parts[1]) except IOError: continue return data return None def source_for_file(filename): """Return the source file for `filename`. Given a file name being traced, return the best guess as to the source file to attribute it to. """ if filename.endswith(".py"): # .py files are themselves source files. return filename elif filename.endswith((".pyc", ".pyo")): # Bytecode files probably have source files near them. py_filename = filename[:-1] if os.path.exists(py_filename): # Found a .py file, use that. return py_filename if env.WINDOWS: # On Windows, it could be a .pyw file. pyw_filename = py_filename + "w" if os.path.exists(pyw_filename): return pyw_filename # Didn't find source, but it's probably the .py file we want. return py_filename elif filename.endswith("$py.class"): # Jython is easy to guess. return filename[:-9] + ".py" # No idea, just use the file name as-is. return filename class PythonFileReporter(FileReporter): """Report support for a Python file.""" def __init__(self, morf, coverage=None): self.coverage = coverage if hasattr(morf, '__file__'): filename = morf.__file__ elif isinstance(morf, types.ModuleType): # A module should have had .__file__, otherwise we can't use it. # This could be a PEP-420 namespace package. raise CoverageException("Module {0} has no file".format(morf)) else: filename = morf filename = source_for_file(files.unicode_filename(filename)) super(PythonFileReporter, self).__init__(files.canonical_filename(filename)) if hasattr(morf, '__name__'): name = morf.__name__.replace(".", os.sep) if os.path.basename(filename).startswith('__init__.'): name += os.sep + "__init__" name += ".py" name = files.unicode_filename(name) else: name = files.relative_filename(filename) self.relname = name self._source = None self._parser = None self._statements = None self._excluded = None def __repr__(self): return "".format(self.filename) @contract(returns='unicode') def relative_filename(self): return self.relname @property def parser(self): """Lazily create a :class:`PythonParser`.""" if self._parser is None: self._parser = PythonParser( filename=self.filename, exclude=self.coverage._exclude_regex('exclude'), ) self._parser.parse_source() return self._parser def lines(self): """Return the line numbers of statements in the file.""" return self.parser.statements def excluded_lines(self): """Return the line numbers of statements in the file.""" return self.parser.excluded def translate_lines(self, lines): return self.parser.translate_lines(lines) def translate_arcs(self, arcs): return self.parser.translate_arcs(arcs) @expensive def no_branch_lines(self): no_branch = self.parser.lines_matching( join_regex(self.coverage.config.partial_list), join_regex(self.coverage.config.partial_always_list) ) return no_branch @expensive def arcs(self): return self.parser.arcs() @expensive def exit_counts(self): return self.parser.exit_counts() def missing_arc_description(self, start, end, executed_arcs=None): return self.parser.missing_arc_description(start, end, executed_arcs) @contract(returns='unicode') def source(self): if self._source is None: self._source = get_python_source(self.filename) return self._source def should_be_python(self): """Does it seem like this file should contain Python? This is used to decide if a file reported as part of the execution of a program was really likely to have contained Python in the first place. """ # Get the file extension. _, ext = os.path.splitext(self.filename) # Anything named *.py* should be Python. if ext.startswith('.py'): return True # A file with no extension should be Python. if not ext: return True # Everything else is probably not Python. return False def source_token_lines(self): return source_token_lines(self.source()) #!/usr/bin/python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not 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. import zookeeper, zktestbase, unittest, threading ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"} class GetSetTest(zktestbase.TestBase): def setUp( self ): zktestbase.TestBase.setUp(self) try: zookeeper.create(self.handle, "/zk-python-getsettest", "on",[ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL) zookeeper.create(self.handle, "/zk-python-agetsettest", "on",[ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL) except: pass def test_sync_getset(self): self.assertEqual(self.connected, True, "Not connected!") (data,stat) = zookeeper.get(self.handle, "/zk-python-getsettest", None) self.assertEqual(data, "on", "Data is not 'on' as expected: " + data) ret = zookeeper.set(self.handle, "/zk-python-getsettest", "off", stat["version"]) (data,stat) = zookeeper.get(self.handle, "/zk-python-getsettest", None) self.assertEqual(data, "off", "Data is not 'off' as expected: " + data) self.assertRaises(zookeeper.BadVersionException, zookeeper.set, self.handle, "/zk-python-getsettest", "test", stat["version"]+1) def test_stat_deleted_node(self): """ Test for a bug that surfaced when trying to build a stat object from a non-existant node. """ self.ensureDeleted("/zk-python-test-deleteme") self.assertRaises(zookeeper.NoNodeException, zookeeper.get, self.handle, "/zk-python-test-deleteme") self.cv = threading.Condition() def callback(handle, rc, value, stat): self.cv.acquire() self.stat = stat self.rc = rc self.value = value self.callback_flag = True self.cv.notify() self.cv.release() self.cv.acquire() zookeeper.aget(self.handle, "/zk-python-test-deleteme", None, callback) self.cv.wait(15) self.assertEqual(self.callback_flag, True, "aget timed out!") self.assertEqual(self.stat, None, "Stat should be none!") self.assertEqual(self.value, None, "Value should be none!") def test_sync_get_large_datanode(self): """ Test that we can retrieve datanode sizes up to 1Mb with default parameters (depends on ZooKeeper server). """ data = ''.join(["A" for x in xrange(1024*1023)]) self.ensureDeleted("/zk-python-test-large-datanode") zookeeper.create(self.handle, "/zk-python-test-large-datanode", data, [{"perms":0x1f, "scheme":"world", "id" :"anyone"}]) (ret,stat) = zookeeper.get(self.handle, "/zk-python-test-large-datanode") self.assertEqual(len(ret), 1024*1023, "Should have got 1Mb returned, instead got %s" % len(ret)) (ret,stat) = zookeeper.get(self.handle, "/zk-python-test-large-datanode",None,500) self.assertEqual(len(ret), 500, "Should have got 500 bytes returned, instead got %s" % len(ret)) def test_async_getset(self): self.cv = threading.Condition() def get_callback(handle, rc, value, stat): self.cv.acquire() self.callback_flag = True self.rc = rc self.value = (value,stat) self.cv.notify() self.cv.release() def set_callback(handle, rc, stat): self.cv.acquire() self.callback_flag = True self.rc = rc self.value = stat self.cv.notify() self.cv.release() self.assertEqual(self.connected, True, "Not connected!") self.cv.acquire() self.callback_flag = False ret = zookeeper.aset(self.handle, "/zk-python-agetsettest", "off", -1, set_callback) self.assertEqual(ret, zookeeper.OK, "aset failed") while not self.callback_flag: self.cv.wait(15) self.cv.release() self.assertEqual(self.callback_flag, True, "aset timed out") self.cv.acquire() self.callback_flag = False ret = zookeeper.aget(self.handle, "/zk-python-agetsettest", None, get_callback) self.assertEqual(ret, zookeeper.OK, "aget failed") self.cv.wait(15) self.cv.release() self.assertEqual(self.callback_flag, True, "aget timed out") self.assertEqual(self.value[0], "off", "Data is not 'off' as expected: " + self.value[0]) def test_sync_getchildren(self): self.ensureCreated("/zk-python-getchildrentest", flags=0) self.ensureCreated("/zk-python-getchildrentest/child") children = zookeeper.get_children(self.handle, "/zk-python-getchildrentest") self.assertEqual(len(children), 1, "Expected to find 1 child, got " + str(len(children))) def test_async_getchildren(self): self.ensureCreated("/zk-python-getchildrentest", flags=0) self.ensureCreated("/zk-python-getchildrentest/child") def gc_callback(handle, rc, children): self.cv.acquire() self.rc = rc self.children = children self.callback_flag = True self.cv.notify() self.cv.release() self.cv.acquire() self.callback_flag = False zookeeper.aget_children(self.handle, "/zk-python-getchildrentest", None, gc_callback) self.cv.wait(15) self.assertEqual(self.callback_flag, True, "aget_children timed out") self.assertEqual(self.rc, zookeeper.OK, "Return code for aget_children was not OK - %s" % zookeeper.zerror(self.rc)) self.assertEqual(len(self.children), 1, "Expected to find 1 child, got " + str(len(self.children))) def test_async_getchildren_with_watcher(self): self.ensureCreated("/zk-python-getchildrentest", flags=0) self.ensureCreated("/zk-python-getchildrentest/child") watched = [] def watcher(*args): self.cv.acquire() watched.append(args) self.cv.notify() self.cv.release() def children_callback(*args): self.cv.acquire() self.cv.notify() self.cv.release() zookeeper.aget_children( self.handle, "/zk-python-getchildrentest", watcher, children_callback) self.cv.acquire() self.cv.wait() self.cv.release() self.cv.acquire() self.ensureCreated("/zk-python-getchildrentest/child2") self.cv.wait(15) self.assertTrue(watched) if __name__ == '__main__': unittest.main() import os import unittest import torch import torchvision from torch.utils.data import Subset from src.datasets.load_cifar10 import CIFAR10_TRAIN_MEAN, CIFAR10_TRAIN_STD, DATA_DIRPATH, SPLIT_DIRPATH from src.misc.utils import read_lines class TestCifar10(unittest.TestCase): def setUp(self) -> None: transform = torchvision.transforms.ToTensor() dataset = torchvision.datasets.CIFAR10(DATA_DIRPATH, train=True, transform=transform, download=True) train_indices = read_lines(os.path.join(SPLIT_DIRPATH, "train.txt"), int) self.train_dataset = Subset(dataset, train_indices) self.images = torch.stack([image for image, label in self.train_dataset], dim=0) def test_mean(self) -> None: expected_mean = torch.mean(self.images, dim=(0, 2, 3)) for c in range(3): self.assertAlmostEqual(expected_mean[c].item(), CIFAR10_TRAIN_MEAN[c], 4) def test_std(self) -> None: expected_std = torch.std(self.images, dim=(0, 2, 3)) for c in range(3): self.assertAlmostEqual(expected_std[c].item(), CIFAR10_TRAIN_STD[c], 4) # Copyright 2008-2015 Nokia Solutions and Networks # # 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 collections import Mapping from UserDict import UserDict from UserString import UserString try: from java.lang import String except ImportError: String = () def is_integer(item): return isinstance(item, (int, long)) def is_number(item): return isinstance(item, (int, long, float)) def is_bytes(item): return isinstance(item, str) def is_string(item): return isinstance(item, basestring) def is_unicode(item): return isinstance(item, unicode) def is_list_like(item): if isinstance(item, (basestring, UserString, String)): return False try: iter(item) except TypeError: return False else: return True def is_dict_like(item): return isinstance(item, (Mapping, UserDict)) def is_truthy(item): if isinstance(item, basestring): return item.upper() not in ('FALSE', 'NO', '') return bool(item) def is_falsy(item): return not is_truthy(item) def type_name(item): cls = item.__class__ if hasattr(item, '__class__') else type(item) named_types = {str: 'string', unicode: 'string', bool: 'boolean', int: 'integer', long: 'integer', type(None): 'None', dict: 'dictionary'} return named_types.get(cls, cls.__name__) ## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi ## This program is published under a GPLv2 license """ PPP (Point to Point Protocol) [RFC 1661] """ import struct from scapy.packet import Packet, bind_layers from scapy.layers.l2 import Ether, CookedLinux from scapy.layers.inet import IP from scapy.layers.inet6 import IPv6 from scapy.fields import BitField, ByteEnumField, ByteField, \ ConditionalField, FieldLenField, IPField, PacketListField, \ ShortEnumField, ShortField, StrFixedLenField, StrLenField, XByteField, \ XShortField class PPPoE(Packet): name = "PPP over Ethernet" fields_desc = [ BitField("version", 1, 4), BitField("type", 1, 4), ByteEnumField("code", 0, {0:"Session"}), XShortField("sessionid", 0x0), ShortField("len", None) ] def post_build(self, p, pay): p += pay if self.len is None: l = len(p)-6 p = p[:4]+struct.pack("!H", l)+p[6:] return p class PPPoED(PPPoE): name = "PPP over Ethernet Discovery" fields_desc = [ BitField("version", 1, 4), BitField("type", 1, 4), ByteEnumField("code", 0x09, {0x09:"PADI",0x07:"PADO",0x19:"PADR",0x65:"PADS",0xa7:"PADT"}), XShortField("sessionid", 0x0), ShortField("len", None) ] _PPP_proto = { 0x0001: "Padding Protocol", 0x0003: "ROHC small-CID [RFC3095]", 0x0005: "ROHC large-CID [RFC3095]", 0x0021: "Internet Protocol version 4", 0x0023: "OSI Network Layer", 0x0025: "Xerox NS IDP", 0x0027: "DECnet Phase IV", 0x0029: "Appletalk", 0x002b: "Novell IPX", 0x002d: "Van Jacobson Compressed TCP/IP", 0x002f: "Van Jacobson Uncompressed TCP/IP", 0x0031: "Bridging PDU", 0x0033: "Stream Protocol (ST-II)", 0x0035: "Banyan Vines", 0x0037: "reserved (until 1993) [Typo in RFC1172]", 0x0039: "AppleTalk EDDP", 0x003b: "AppleTalk SmartBuffered", 0x003d: "Multi-Link [RFC1717]", 0x003f: "NETBIOS Framing", 0x0041: "Cisco Systems", 0x0043: "Ascom Timeplex", 0x0045: "Fujitsu Link Backup and Load Balancing (LBLB)", 0x0047: "DCA Remote Lan", 0x0049: "Serial Data Transport Protocol (PPP-SDTP)", 0x004b: "SNA over 802.2", 0x004d: "SNA", 0x004f: "IPv6 Header Compression", 0x0051: "KNX Bridging Data [ianp]", 0x0053: "Encryption [Meyer]", 0x0055: "Individual Link Encryption [Meyer]", 0x0057: "Internet Protocol version 6 [Hinden]", 0x0059: "PPP Muxing [RFC3153]", 0x005b: "Vendor-Specific Network Protocol (VSNP) [RFC3772]", 0x0061: "RTP IPHC Full Header [RFC3544]", 0x0063: "RTP IPHC Compressed TCP [RFC3544]", 0x0065: "RTP IPHC Compressed Non TCP [RFC3544]", 0x0067: "RTP IPHC Compressed UDP 8 [RFC3544]", 0x0069: "RTP IPHC Compressed RTP 8 [RFC3544]", 0x006f: "Stampede Bridging", 0x0071: "Reserved [Fox]", 0x0073: "MP+ Protocol [Smith]", 0x007d: "reserved (Control Escape) [RFC1661]", 0x007f: "reserved (compression inefficient [RFC1662]", 0x0081: "Reserved Until 20-Oct-2000 [IANA]", 0x0083: "Reserved Until 20-Oct-2000 [IANA]", 0x00c1: "NTCITS IPI [Ungar]", 0x00cf: "reserved (PPP NLID)", 0x00fb: "single link compression in multilink [RFC1962]", 0x00fd: "compressed datagram [RFC1962]", 0x00ff: "reserved (compression inefficient)", 0x0201: "802.1d Hello Packets", 0x0203: "IBM Source Routing BPDU", 0x0205: "DEC LANBridge100 Spanning Tree", 0x0207: "Cisco Discovery Protocol [Sastry]", 0x0209: "Netcs Twin Routing [Korfmacher]", 0x020b: "STP - Scheduled Transfer Protocol [Segal]", 0x020d: "EDP - Extreme Discovery Protocol [Grosser]", 0x0211: "Optical Supervisory Channel Protocol (OSCP)[Prasad]", 0x0213: "Optical Supervisory Channel Protocol (OSCP)[Prasad]", 0x0231: "Luxcom", 0x0233: "Sigma Network Systems", 0x0235: "Apple Client Server Protocol [Ridenour]", 0x0281: "MPLS Unicast [RFC3032] ", 0x0283: "MPLS Multicast [RFC3032]", 0x0285: "IEEE p1284.4 standard - data packets [Batchelder]", 0x0287: "ETSI TETRA Network Protocol Type 1 [Nieminen]", 0x0289: "Multichannel Flow Treatment Protocol [McCann]", 0x2063: "RTP IPHC Compressed TCP No Delta [RFC3544]", 0x2065: "RTP IPHC Context State [RFC3544]", 0x2067: "RTP IPHC Compressed UDP 16 [RFC3544]", 0x2069: "RTP IPHC Compressed RTP 16 [RFC3544]", 0x4001: "Cray Communications Control Protocol [Stage]", 0x4003: "CDPD Mobile Network Registration Protocol [Quick]", 0x4005: "Expand accelerator protocol [Rachmani]", 0x4007: "ODSICP NCP [Arvind]", 0x4009: "DOCSIS DLL [Gaedtke]", 0x400B: "Cetacean Network Detection Protocol [Siller]", 0x4021: "Stacker LZS [Simpson]", 0x4023: "RefTek Protocol [Banfill]", 0x4025: "Fibre Channel [Rajagopal]", 0x4027: "EMIT Protocols [Eastham]", 0x405b: "Vendor-Specific Protocol (VSP) [RFC3772]", 0x8021: "Internet Protocol Control Protocol", 0x8023: "OSI Network Layer Control Protocol", 0x8025: "Xerox NS IDP Control Protocol", 0x8027: "DECnet Phase IV Control Protocol", 0x8029: "Appletalk Control Protocol", 0x802b: "Novell IPX Control Protocol", 0x802d: "reserved", 0x802f: "reserved", 0x8031: "Bridging NCP", 0x8033: "Stream Protocol Control Protocol", 0x8035: "Banyan Vines Control Protocol", 0x8037: "reserved (until 1993)", 0x8039: "reserved", 0x803b: "reserved", 0x803d: "Multi-Link Control Protocol", 0x803f: "NETBIOS Framing Control Protocol", 0x8041: "Cisco Systems Control Protocol", 0x8043: "Ascom Timeplex", 0x8045: "Fujitsu LBLB Control Protocol", 0x8047: "DCA Remote Lan Network Control Protocol (RLNCP)", 0x8049: "Serial Data Control Protocol (PPP-SDCP)", 0x804b: "SNA over 802.2 Control Protocol", 0x804d: "SNA Control Protocol", 0x804f: "IP6 Header Compression Control Protocol", 0x8051: "KNX Bridging Control Protocol [ianp]", 0x8053: "Encryption Control Protocol [Meyer]", 0x8055: "Individual Link Encryption Control Protocol [Meyer]", 0x8057: "IPv6 Control Protovol [Hinden]", 0x8059: "PPP Muxing Control Protocol [RFC3153]", 0x805b: "Vendor-Specific Network Control Protocol (VSNCP) [RFC3772]", 0x806f: "Stampede Bridging Control Protocol", 0x8073: "MP+ Control Protocol [Smith]", 0x8071: "Reserved [Fox]", 0x807d: "Not Used - reserved [RFC1661]", 0x8081: "Reserved Until 20-Oct-2000 [IANA]", 0x8083: "Reserved Until 20-Oct-2000 [IANA]", 0x80c1: "NTCITS IPI Control Protocol [Ungar]", 0x80cf: "Not Used - reserved [RFC1661]", 0x80fb: "single link compression in multilink control [RFC1962]", 0x80fd: "Compression Control Protocol [RFC1962]", 0x80ff: "Not Used - reserved [RFC1661]", 0x8207: "Cisco Discovery Protocol Control [Sastry]", 0x8209: "Netcs Twin Routing [Korfmacher]", 0x820b: "STP - Control Protocol [Segal]", 0x820d: "EDPCP - Extreme Discovery Protocol Ctrl Prtcl [Grosser]", 0x8235: "Apple Client Server Protocol Control [Ridenour]", 0x8281: "MPLSCP [RFC3032]", 0x8285: "IEEE p1284.4 standard - Protocol Control [Batchelder]", 0x8287: "ETSI TETRA TNP1 Control Protocol [Nieminen]", 0x8289: "Multichannel Flow Treatment Protocol [McCann]", 0xc021: "Link Control Protocol", 0xc023: "Password Authentication Protocol", 0xc025: "Link Quality Report", 0xc027: "Shiva Password Authentication Protocol", 0xc029: "CallBack Control Protocol (CBCP)", 0xc02b: "BACP Bandwidth Allocation Control Protocol [RFC2125]", 0xc02d: "BAP [RFC2125]", 0xc05b: "Vendor-Specific Authentication Protocol (VSAP) [RFC3772]", 0xc081: "Container Control Protocol [KEN]", 0xc223: "Challenge Handshake Authentication Protocol", 0xc225: "RSA Authentication Protocol [Narayana]", 0xc227: "Extensible Authentication Protocol [RFC2284]", 0xc229: "Mitsubishi Security Info Exch Ptcl (SIEP) [Seno]", 0xc26f: "Stampede Bridging Authorization Protocol", 0xc281: "Proprietary Authentication Protocol [KEN]", 0xc283: "Proprietary Authentication Protocol [Tackabury]", 0xc481: "Proprietary Node ID Authentication Protocol [KEN]"} class HDLC(Packet): fields_desc = [ XByteField("address",0xff), XByteField("control",0x03) ] class PPP(Packet): name = "PPP Link Layer" fields_desc = [ ShortEnumField("proto", 0x0021, _PPP_proto) ] @classmethod def dispatch_hook(cls, _pkt=None, *args, **kargs): if _pkt and _pkt[0] == '\xff': cls = HDLC return cls _PPP_conftypes = { 1:"Configure-Request", 2:"Configure-Ack", 3:"Configure-Nak", 4:"Configure-Reject", 5:"Terminate-Request", 6:"Terminate-Ack", 7:"Code-Reject", 8:"Protocol-Reject", 9:"Echo-Request", 10:"Echo-Reply", 11:"Discard-Request", 14:"Reset-Request", 15:"Reset-Ack", } ### PPP IPCP stuff (RFC 1332) # All IPCP options are defined below (names and associated classes) _PPP_ipcpopttypes = { 1:"IP-Addresses (Deprecated)", 2:"IP-Compression-Protocol", 3:"IP-Address", 4:"Mobile-IPv4", # not implemented, present for completeness 129:"Primary-DNS-Address", 130:"Primary-NBNS-Address", 131:"Secondary-DNS-Address", 132:"Secondary-NBNS-Address"} class PPP_IPCP_Option(Packet): name = "PPP IPCP Option" fields_desc = [ ByteEnumField("type" , None , _PPP_ipcpopttypes), FieldLenField("len", None, length_of="data", fmt="B", adjust=lambda p,x:x+2), StrLenField("data", "", length_from=lambda p:max(0,p.len-2)) ] def extract_padding(self, pay): return "",pay registered_options = {} @classmethod def register_variant(cls): cls.registered_options[cls.type.default] = cls @classmethod def dispatch_hook(cls, _pkt=None, *args, **kargs): if _pkt: o = ord(_pkt[0]) return cls.registered_options.get(o, cls) return cls class PPP_IPCP_Option_IPAddress(PPP_IPCP_Option): name = "PPP IPCP Option: IP Address" fields_desc = [ ByteEnumField("type" , 3 , _PPP_ipcpopttypes), FieldLenField("len", None, length_of="data", fmt="B", adjust=lambda p,x:x+2), IPField("data","0.0.0.0"), ConditionalField(StrLenField("garbage","", length_from=lambda pkt:pkt.len-6), lambda p:p.len!=6) ] class PPP_IPCP_Option_DNS1(PPP_IPCP_Option): name = "PPP IPCP Option: DNS1 Address" fields_desc = [ ByteEnumField("type" , 129 , _PPP_ipcpopttypes), FieldLenField("len", None, length_of="data", fmt="B", adjust=lambda p,x:x+2), IPField("data","0.0.0.0"), ConditionalField(StrLenField("garbage","", length_from=lambda pkt:pkt.len-6), lambda p:p.len!=6) ] class PPP_IPCP_Option_DNS2(PPP_IPCP_Option): name = "PPP IPCP Option: DNS2 Address" fields_desc = [ ByteEnumField("type" , 131 , _PPP_ipcpopttypes), FieldLenField("len", None, length_of="data", fmt="B", adjust=lambda p,x:x+2), IPField("data","0.0.0.0"), ConditionalField(StrLenField("garbage","", length_from=lambda pkt:pkt.len-6), lambda p:p.len!=6) ] class PPP_IPCP_Option_NBNS1(PPP_IPCP_Option): name = "PPP IPCP Option: NBNS1 Address" fields_desc = [ ByteEnumField("type" , 130 , _PPP_ipcpopttypes), FieldLenField("len", None, length_of="data", fmt="B", adjust=lambda p,x:x+2), IPField("data","0.0.0.0"), ConditionalField(StrLenField("garbage","", length_from=lambda pkt:pkt.len-6), lambda p:p.len!=6) ] class PPP_IPCP_Option_NBNS2(PPP_IPCP_Option): name = "PPP IPCP Option: NBNS2 Address" fields_desc = [ ByteEnumField("type" , 132 , _PPP_ipcpopttypes), FieldLenField("len", None, length_of="data", fmt="B", adjust=lambda p,x:x+2), IPField("data","0.0.0.0"), ConditionalField(StrLenField("garbage","", length_from=lambda pkt:pkt.len-6), lambda p:p.len!=6) ] class PPP_IPCP(Packet): fields_desc = [ ByteEnumField("code" , 1, _PPP_conftypes), XByteField("id", 0 ), FieldLenField("len" , None, fmt="H", length_of="options", adjust=lambda p,x:x+4 ), PacketListField("options", [], PPP_IPCP_Option, length_from=lambda p:p.len-4,) ] ### ECP _PPP_ecpopttypes = { 0:"OUI", 1:"DESE", } class PPP_ECP_Option(Packet): name = "PPP ECP Option" fields_desc = [ ByteEnumField("type" , None , _PPP_ecpopttypes), FieldLenField("len", None, length_of="data", fmt="B", adjust=lambda p,x:x+2), StrLenField("data", "", length_from=lambda p:max(0,p.len-2)) ] def extract_padding(self, pay): return "",pay registered_options = {} @classmethod def register_variant(cls): cls.registered_options[cls.type.default] = cls @classmethod def dispatch_hook(cls, _pkt=None, *args, **kargs): if _pkt: o = ord(_pkt[0]) return cls.registered_options.get(o, cls) return cls class PPP_ECP_Option_OUI(PPP_ECP_Option): fields_desc = [ ByteEnumField("type" , 0 , _PPP_ecpopttypes), FieldLenField("len", None, length_of="data", fmt="B", adjust=lambda p,x:x+6), StrFixedLenField("oui","",3), ByteField("subtype",0), StrLenField("data", "", length_from=lambda p:p.len-6) ] class PPP_ECP(Packet): fields_desc = [ ByteEnumField("code" , 1, _PPP_conftypes), XByteField("id", 0 ), FieldLenField("len" , None, fmt="H", length_of="options", adjust=lambda p,x:x+4 ), PacketListField("options", [], PPP_ECP_Option, length_from=lambda p:p.len-4,) ] bind_layers( Ether, PPPoED, type=0x8863) bind_layers( Ether, PPPoE, type=0x8864) bind_layers( CookedLinux, PPPoED, proto=0x8863) bind_layers( CookedLinux, PPPoE, proto=0x8864) bind_layers( PPPoE, PPP, code=0) bind_layers( HDLC, PPP, ) bind_layers( PPP, IP, proto=0x0021) bind_layers( PPP, IPv6, proto=0x0057) bind_layers( PPP, PPP_IPCP, proto=0x8021) bind_layers( PPP, PPP_ECP, proto=0x8053) bind_layers( Ether, PPP_IPCP, type=0x8021) bind_layers( Ether, PPP_ECP, type=0x8053) from __future__ import unicode_literals from .common import InfoExtractor from .zdf import extract_from_xml_url class PhoenixIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?phoenix\.de/content/(?P[0-9]+)' _TEST = { 'url': 'http://www.phoenix.de/content/884301', 'md5': 'ed249f045256150c92e72dbb70eadec6', 'info_dict': { 'id': '884301', 'ext': 'mp4', 'title': 'Michael Krons mit Hans-Werner Sinn', 'description': 'Im Dialog - Sa. 25.10.14, 00.00 - 00.35 Uhr', 'upload_date': '20141025', 'uploader': 'Im Dialog', } } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) internal_id = self._search_regex( r'
\n'] ret.append('\n') ret.append(pydevd_xml.var_to_xml( searched_obj, 'Skipping getting referrers for None', additionalInXml=' id="%s"' % (id(searched_obj),))) ret.append('\n') ret.append('') ret = ''.join(ret) return ret obj_id = id(searched_obj) try: if DEBUG: sys.stderr.write('Getting referrers...\n') import gc referrers = gc.get_referrers(searched_obj) except: traceback.print_exc() ret = ['\n'] ret.append('\n') ret.append(pydevd_xml.var_to_xml( searched_obj, 'Exception raised while trying to get_referrers.', additionalInXml=' id="%s"' % (id(searched_obj),))) ret.append('\n') ret.append('') ret = ''.join(ret) return ret if DEBUG: sys.stderr.write('Found %s referrers.\n' % (len(referrers),)) curr_frame = sys._getframe() frame_type = type(curr_frame) #Ignore this frame and any caller frame of this frame ignore_frames = {} #Should be a set, but it's not available on all python versions. while curr_frame is not None: if basename(curr_frame.f_code.co_filename).startswith('pydev'): ignore_frames[curr_frame] = 1 curr_frame = curr_frame.f_back ret = ['\n'] ret.append('\n') if DEBUG: sys.stderr.write('Searching Referrers of obj with id="%s"\n' % (obj_id,)) ret.append(pydevd_xml.var_to_xml( searched_obj, 'Referrers of obj with id="%s"' % (obj_id,))) ret.append('\n') all_objects = None for r in referrers: try: if dict_contains(ignore_frames, r): continue #Skip the references we may add ourselves except: pass #Ok: unhashable type checked... if r is referrers: continue r_type = type(r) r_id = str(id(r)) representation = str(r_type) found_as = '' if r_type == frame_type: if DEBUG: sys.stderr.write('Found frame referrer: %r\n' % (r,)) for key, val in r.f_locals.items(): if val is searched_obj: found_as = key break elif r_type == dict: if DEBUG: sys.stderr.write('Found dict referrer: %r\n' % (r,)) # Try to check if it's a value in the dict (and under which key it was found) for key, val in r.items(): if val is searched_obj: found_as = key if DEBUG: sys.stderr.write(' Found as %r in dict\n' % (found_as,)) break #Ok, there's one annoying thing: many times we find it in a dict from an instance, #but with this we don't directly have the class, only the dict, so, to workaround that #we iterate over all reachable objects ad check if one of those has the given dict. if all_objects is None: all_objects = gc.get_objects() for x in all_objects: try: if getattr(x, '__dict__', None) is r: r = x r_type = type(x) r_id = str(id(r)) representation = str(r_type) break except: pass #Just ignore any error here (i.e.: ReferenceError, etc.) elif r_type in (tuple, list): if DEBUG: sys.stderr.write('Found tuple referrer: %r\n' % (r,)) #Don't use enumerate() because not all Python versions have it. i = 0 for x in r: if x is searched_obj: found_as = '%s[%s]' % (r_type.__name__, i) if DEBUG: sys.stderr.write(' Found as %s in tuple: \n' % (found_as,)) break i += 1 if found_as: if not isinstance(found_as, str): found_as = str(found_as) found_as = ' found_as="%s"' % (pydevd_xml.make_valid_xml_value(found_as),) ret.append(pydevd_xml.var_to_xml( r, representation, additionalInXml=' id="%s"%s' % (r_id, found_as))) finally: if DEBUG: sys.stderr.write('Done searching for references.\n') #If we have any exceptions, don't keep dangling references from this frame to any of our objects. all_objects = None referrers = None searched_obj = None r = None x = None key = None val = None curr_frame = None ignore_frames = None except: traceback.print_exc() ret = ['\n'] ret.append('\n') ret.append(pydevd_xml.var_to_xml( searched_obj, 'Error getting referrers for:', additionalInXml=' id="%s"' % (id(searched_obj),))) ret.append('\n') ret.append('') ret = ''.join(ret) return ret ret.append('') ret = ''.join(ret) return ret import mock from django.test import TestCase from django.utils import timezone from myvoice.clinics.models import Visit from myvoice.core.tests import factories from .. import tasks from .. import models from ..textit import TextItException @mock.patch('myvoice.survey.tasks.importer.import_responses') class TestImportResponses(TestCase): def test_active_survey(self, import_responses): """We should call the import_responses utility for active surveys.""" self.survey = factories.Survey(active=True) tasks.import_responses() self.assertEqual(import_responses.call_count, 1) self.assertEqual(import_responses.call_args, ((self.survey.flow_id,),)) def test_inactive_survey(self, import_responses): """We should not try to import responses for inactive surveys.""" self.survey = factories.Survey(active=False) tasks.import_responses() self.assertEqual(import_responses.call_count, 0) @mock.patch.object(tasks.TextItApi, 'start_flow') class TestStartFeedbackSurvey(TestCase): def setUp(self): super(TestStartFeedbackSurvey, self).setUp() self.survey = factories.Survey(role=models.Survey.PATIENT_FEEDBACK) self.visit = factories.Visit(mobile='01234567890') def test_no_such_survey(self, start_flow): """No flow should be started if there is no patient feedback survey.""" self.survey.delete() self.assertRaises(models.Survey.DoesNotExist, tasks.start_feedback_survey, self.visit.pk) self.assertEqual(start_flow.call_count, 0) self.visit = Visit.objects.get(pk=self.visit.pk) self.assertIsNone(self.visit.survey_sent) def test_no_such_visit(self, start_flow): """No flow should be started if there is no associated visit.""" self.assertRaises(Visit.DoesNotExist, tasks.start_feedback_survey, 12345) self.assertEqual(start_flow.call_count, 0) self.visit = Visit.objects.get(pk=self.visit.pk) self.assertIsNone(self.visit.survey_sent) def test_start_flow(self, start_flow): """When survey is sent, survey_sent field should be updated.""" tasks.start_feedback_survey(self.visit.pk) self.assertEqual(start_flow.call_count, 1) expected = ((self.survey.flow_id, self.visit.mobile),) self.assertEqual(start_flow.call_args, expected) self.visit = Visit.objects.get(pk=self.visit.pk) self.assertIsNotNone(self.visit.survey_sent) def test_error(self, start_flow): """If error occurs during start_flow, survey_sent should be null.""" start_flow.side_effect = TextItException self.assertRaises(start_flow.side_effect, tasks.start_feedback_survey, self.visit.pk) self.assertEqual(start_flow.call_count, 1) expected = ((self.survey.flow_id, self.visit.mobile),) self.assertEqual(start_flow.call_args, expected) self.visit = Visit.objects.get(pk=self.visit.pk) self.assertIsNone(self.visit.survey_sent) @mock.patch.object(tasks.TextItApi, 'send_message') @mock.patch('myvoice.survey.tasks.start_feedback_survey.apply_async') class TestHandleNewVisits(TestCase): def setUp(self): super(TestHandleNewVisits, self).setUp() self.survey = factories.Survey(role=models.Survey.PATIENT_FEEDBACK) def test_new_visit(self, start_feedback_survey, send_message): """ We should send a welcome message and schedule the survey to be started for a new visit. """ visit = factories.Visit(welcome_sent=None, mobile='01234567890') tasks.handle_new_visits() self.assertEqual(send_message.call_count, 0) visit = Visit.objects.get(pk=visit.pk) self.assertIsNotNone(visit.welcome_sent) self.assertEqual(start_feedback_survey.call_count, 1) def test_only_invalid(self, start_feedback_survey, send_message): """Nothing should happen if all phone numbers are invalid.""" visit = factories.Visit(welcome_sent=None, mobile='invalid') tasks.handle_new_visits() self.assertEqual(send_message.call_count, 0) visit = Visit.objects.get(pk=visit.pk) self.assertIsNone(visit.welcome_sent) self.assertEqual(start_feedback_survey.call_count, 0) def test_mixed_valid_invalid_phones(self, start_feedback_survey, send_message): """ We should send a welcome message and schedule the survey to be started for a new visit. """ visit1 = factories.Visit(welcome_sent=None, mobile='invalid') visit2 = factories.Visit(welcome_sent=None, mobile='01234567890') tasks.handle_new_visits() # No welcome message sent so send_message.call_count = 0 self.assertEqual(send_message.call_count, 0) visit1 = Visit.objects.get(pk=visit1.pk) self.assertIsNone(visit1.welcome_sent) visit2 = Visit.objects.get(pk=visit2.pk) self.assertIsNotNone(visit2.welcome_sent) self.assertEqual(start_feedback_survey.call_count, 1) def test_past_visit(self, start_feedback_survey, send_message): """ We should not do anything for visits that have already had the welcome message sent. """ welcome_sent = timezone.now() visit = factories.Visit(welcome_sent=welcome_sent, mobile='01234567890') tasks.handle_new_visits() # No welcome message sent so send_message.call_count = 0 self.assertEqual(send_message.call_count, 0) self.assertEqual(start_feedback_survey.call_count, 0) visit = Visit.objects.get(pk=visit.pk) self.assertEqual(visit.welcome_sent, welcome_sent) self.assertIsNone(visit.survey_sent) def test_blocked_number(self, start_feedback_survey, send_message): """ We don't start surveys for blocked numbers which are those that are senders in one or more Visits. """ factories.Visit(welcome_sent=None, mobile='01234567890', sender='09876543210') visit2 = factories.Visit(welcome_sent=None, mobile='09876543210') tasks.handle_new_visits() # No welcome message sent so send_message.call_count = 0 self.assertEqual(send_message.call_count, 0) visit2 = Visit.objects.get(pk=visit2.pk) self.assertIsNone(visit2.welcome_sent) self.assertEqual(start_feedback_survey.call_count, 1) @mock.patch('myvoice.survey.tasks.settings') class TestGetSurveyStartTime(TestCase): def setUp(self): self.t1 = timezone.make_aware( timezone.datetime(2014, 07, 21, 10, 0, 0, 0), timezone.utc) def test_get_start_time(self, settings): settings.DEFAULT_SURVEY_DELAY = timezone.timedelta(minutes=5) settings.SURVEY_TIME_WINDOW = (7, 20) eta = tasks._get_survey_start_time(self.t1) self.assertEqual(eta, self.t1.replace(minute=5)) def test_get_eta_early(self, settings): settings.DEFAULT_SURVEY_DELAY = timezone.timedelta(minutes=5) settings.SURVEY_TIME_WINDOW = (7, 20) tm = self.t1.replace(hour=4) eta = tasks._get_survey_start_time(tm) self.assertEqual(eta, self.t1.replace(hour=7)) def test_get_eta_late(self, settings): settings.DEFAULT_SURVEY_DELAY = timezone.timedelta(minutes=5) settings.SURVEY_TIME_WINDOW = (7, 20) tm = self.t1.replace(hour=23) eta = tasks._get_survey_start_time(tm) self.assertEqual(eta, self.t1.replace(hour=7, day=22)) #!/usr/bin/env python from __future__ import print_function from __future__ import absolute_import import os import sys import tct params = tct.readjson(sys.argv[1]) facts = tct.readjson(params['factsfile']) milestones = tct.readjson(params['milestonesfile']) reason = '' resultfile = params['resultfile'] result = tct.readjson(resultfile) toolname = params['toolname'] toolname_pure = params['toolname_pure'] toolchain_name = facts['toolchain_name'] workdir = params['workdir'] loglist = result['loglist'] = result.get('loglist', []) exitcode = CONTINUE = 0 # ================================================== # Make a copy of milestones for later inspection? # -------------------------------------------------- if 0 or milestones.get('debug_always_make_milestones_snapshot'): tct.make_snapshot_of_milestones(params['milestonesfile'], sys.argv[1]) # ================================================== # Helper functions # -------------------------------------------------- deepget = tct.deepget def lookup(D, *keys, **kwdargs): result = deepget(D, *keys, **kwdargs) loglist.append((keys, result)) return result # ================================================== # define # -------------------------------------------------- TheProjectLog = None TheProjectBuild = None TheProjectWebroot = None # ================================================== # Check params # -------------------------------------------------- if exitcode == CONTINUE: loglist.append('CHECK PARAMS') TheProject = lookup(milestones, 'TheProject', default=None) if not TheProject: exitcode = 22 reason = 'Bad PARAMS or nothing to do' if exitcode == CONTINUE: loglist.append('PARAMS are ok') else: loglist.append('Bad PARAMS or nothing to do') # ================================================== # work # -------------------------------------------------- if exitcode == CONTINUE: resultdir = lookup(milestones, 'resultdir', default=None) TheProjectLog = TheProject + 'Log' if not os.path.exists(TheProjectLog): os.makedirs(TheProjectLog) TheProjectBuild = TheProject + 'Build' if not os.path.exists(TheProjectBuild): os.makedirs(TheProjectBuild) if resultdir: TheProjectWebroot = os.path.join(resultdir, 'Result') else: TheProjectWebroot = TheProject + 'Webroot' if not os.path.exists(TheProjectWebroot): os.makedirs(TheProjectWebroot) # ================================================== # Set MILESTONE # -------------------------------------------------- if TheProjectBuild: result['MILESTONES'].append({'TheProjectBuild': TheProjectBuild}) if TheProjectLog: result['MILESTONES'].append({'TheProjectLog': TheProjectLog}) if TheProjectWebroot: result['MILESTONES'].append({'TheProjectWebroot': TheProjectWebroot}) # ================================================== # save result # -------------------------------------------------- tct.save_the_result(result, resultfile, params, facts, milestones, exitcode, CONTINUE, reason) # ================================================== # Return with proper exitcode # -------------------------------------------------- sys.exit(exitcode) from django.conf import settings from django.core.cache import caches from django.core.cache.backends.db import BaseDatabaseCache from django.core.management.base import BaseCommand, CommandError from django.db import ( DEFAULT_DB_ALIAS, connections, models, router, transaction, ) from django.db.utils import DatabaseError from django.utils.encoding import force_text class Command(BaseCommand): help = "Creates the tables needed to use the SQL cache backend." requires_system_checks = False def add_arguments(self, parser): parser.add_argument( 'args', metavar='table_name', nargs='*', help='Optional table names. Otherwise, settings.CACHES is used to find cache tables.', ) parser.add_argument( '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database onto which the cache tables will be ' 'installed. Defaults to the "default" database.', ) parser.add_argument( '--dry-run', action='store_true', dest='dry_run', help='Does not create the table, just prints the SQL that would be run.', ) def handle(self, *tablenames, **options): db = options['database'] self.verbosity = options['verbosity'] dry_run = options['dry_run'] if len(tablenames): # Legacy behavior, tablename specified as argument for tablename in tablenames: self.create_table(db, tablename, dry_run) else: for cache_alias in settings.CACHES: cache = caches[cache_alias] if isinstance(cache, BaseDatabaseCache): self.create_table(db, cache._table, dry_run) def create_table(self, database, tablename, dry_run): cache = BaseDatabaseCache(tablename, {}) if not router.allow_migrate_model(database, cache.cache_model_class): return connection = connections[database] if tablename in connection.introspection.table_names(): if self.verbosity > 0: self.stdout.write("Cache table '%s' already exists." % tablename) return fields = ( # "key" is a reserved word in MySQL, so use "cache_key" instead. models.CharField(name='cache_key', max_length=255, unique=True, primary_key=True), models.TextField(name='value'), models.DateTimeField(name='expires', db_index=True), ) table_output = [] index_output = [] qn = connection.ops.quote_name for f in fields: field_output = [ qn(f.name), f.db_type(connection=connection), '%sNULL' % ('NOT ' if not f.null else ''), ] if f.primary_key: field_output.append("PRIMARY KEY") elif f.unique: field_output.append("UNIQUE") if f.db_index: unique = "UNIQUE " if f.unique else "" index_output.append( "CREATE %sINDEX %s ON %s (%s);" % (unique, qn('%s_%s' % (tablename, f.name)), qn(tablename), qn(f.name)) ) table_output.append(" ".join(field_output)) full_statement = ["CREATE TABLE %s (" % qn(tablename)] for i, line in enumerate(table_output): full_statement.append(' %s%s' % (line, ',' if i < len(table_output) - 1 else '')) full_statement.append(');') full_statement = "\n".join(full_statement) if dry_run: self.stdout.write(full_statement) for statement in index_output: self.stdout.write(statement) return with transaction.atomic(using=database, savepoint=connection.features.can_rollback_ddl): with connection.cursor() as curs: try: curs.execute(full_statement) except DatabaseError as e: raise CommandError( "Cache table '%s' could not be created.\nThe error was: %s." % (tablename, force_text(e))) for statement in index_output: curs.execute(statement) if self.verbosity > 1: self.stdout.write("Cache table '%s' created." % tablename) """Generic linux daemon base class""" # Adapted from http://www.jejik.com/files/examples/daemon3x.py # thanks to the original author import sys import os import time import atexit import signal import syslog import psutil import traceback import gc class Daemon(object): """A generic daemon class. Usage: subclass the daemon class and override the run() method.""" def __init__(self, pidfile): self.pidfile = pidfile def daemonize(self): """Deamonize class. UNIX double fork mechanism.""" try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError as err: sys.stderr.write('fork #1 failed: {0}\n'.format(err)) sys.exit(1) # decouple from parent environment os.chdir('/') os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError as err: sys.stderr.write('fork #2 failed: {0}\n'.format(err)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() stdi = open(os.devnull, 'r') stdo = open(os.devnull, 'a+') stde = open(os.devnull, 'a+') os.dup2(stdi.fileno(), sys.stdin.fileno()) os.dup2(stdo.fileno(), sys.stdout.fileno()) os.dup2(stde.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) with open(self.pidfile, 'w+') as fd: fd.write(pid + '\n') def delpid(self): """Delete pid file""" os.remove(self.pidfile) def start(self): """Start the daemon.""" # Check for a pidfile to see if the daemon already runs try: with open(self.pidfile, 'r') as pidf: pid = int(pidf.read().strip()) except IOError: pid = None if pid: message = "pidfile {0} already exist. " + \ "Daemon already running?\n" sys.stderr.write(message.format(self.pidfile)) sys.exit(1) # Start the daemon self.daemonize() syslog.syslog(syslog.LOG_INFO, '{}: started'.format(os.path.basename(sys.argv[0]))) while True: # look if steam is running if len([p for p in psutil.process_iter() if p.name() == 'steam']) == 0: try: self.run() except Exception as e: # pylint: disable=W0703 syslog.syslog(syslog.LOG_ERR, '{}: {!s}'.format(os.path.basename(sys.argv[0]), e)) syslog.syslog(syslog.LOG_ERR, traceback.format_exc()) gc.collect() else: syslog.syslog(syslog.LOG_INFO, '{}: steam client is runing'.format(os.path.basename(sys.argv[0]))) time.sleep(2) def stop(self): """Stop the daemon.""" # Get the pid from the pidfile try: with open(self.pidfile, 'r') as pidf: pid = int(pidf.read().strip()) except IOError: pid = None if not pid: message = "pidfile {0} does not exist. " + \ "Daemon not running?\n" sys.stderr.write(message.format(self.pidfile)) return # not an error in a restart # Try killing the daemon process try: while True: os.kill(pid, signal.SIGTERM) time.sleep(0.1) except OSError as err: e = str(err.args) if e.find("No such process") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print(str(err.args)) sys.exit(1) syslog.syslog(syslog.LOG_INFO, '{}: stopped'.format(os.path.basename(sys.argv[0]))) def restart(self): """Restart the daemon.""" self.stop() self.start() def run(self): """You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart().""" # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. # ============================================================================== """Tests for utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np from scipy import special import tensorflow as tf from tensorflow.contrib.distributions.python.ops import distribution_util from tensorflow.python.framework import tensor_util class AssertCloseTest(tf.test.TestCase): def testAssertCloseIntegerDtype(self): x = [1, 5, 10, 15, 20] y = x z = [2, 5, 10, 15, 20] with self.test_session(): with tf.control_dependencies([distribution_util.assert_close(x, y)]): tf.identity(x).eval() with tf.control_dependencies([distribution_util.assert_close(y, x)]): tf.identity(x).eval() with self.assertRaisesOpError("Condition x ~= y"): with tf.control_dependencies([distribution_util.assert_close(x, z)]): tf.identity(x).eval() with self.assertRaisesOpError("Condition x ~= y"): with tf.control_dependencies([distribution_util.assert_close(y, z)]): tf.identity(y).eval() def testAssertCloseNonIntegerDtype(self): x = np.array([1., 5, 10, 15, 20], dtype=np.float32) y = x + 1e-8 z = [2., 5, 10, 15, 20] with self.test_session(): with tf.control_dependencies([distribution_util.assert_close(x, y)]): tf.identity(x).eval() with tf.control_dependencies([distribution_util.assert_close(y, x)]): tf.identity(x).eval() with self.assertRaisesOpError("Condition x ~= y"): with tf.control_dependencies([distribution_util.assert_close(x, z)]): tf.identity(x).eval() with self.assertRaisesOpError("Condition x ~= y"): with tf.control_dependencies([distribution_util.assert_close(y, z)]): tf.identity(y).eval() def testAssertCloseEpsilon(self): x = [0., 5, 10, 15, 20] # x != y y = [0.1, 5, 10, 15, 20] # x = z z = [1e-8, 5, 10, 15, 20] with self.test_session(): with tf.control_dependencies([distribution_util.assert_close(x, z)]): tf.identity(x).eval() with self.assertRaisesOpError("Condition x ~= y"): with tf.control_dependencies([distribution_util.assert_close(x, y)]): tf.identity(x).eval() with self.assertRaisesOpError("Condition x ~= y"): with tf.control_dependencies([distribution_util.assert_close(y, z)]): tf.identity(y).eval() def testAssertIntegerForm(self): # This should only be detected as an integer. x = [1., 5, 10, 15, 20] y = [1.1, 5, 10, 15, 20] # First component isn't less than float32.eps = 1e-7 z = [1.0001, 5, 10, 15, 20] # This shouldn"t be detected as an integer. w = [1e-8, 5, 10, 15, 20] with self.test_session(): with tf.control_dependencies([distribution_util.assert_integer_form(x)]): tf.identity(x).eval() with self.assertRaisesOpError("x has non-integer components"): with tf.control_dependencies([ distribution_util.assert_integer_form(y)]): tf.identity(y).eval() with self.assertRaisesOpError("x has non-integer components"): with tf.control_dependencies([ distribution_util.assert_integer_form(z)]): tf.identity(z).eval() with self.assertRaisesOpError("x has non-integer components"): with tf.control_dependencies([ distribution_util.assert_integer_form(w)]): tf.identity(w).eval() class GetLogitsAndProbTest(tf.test.TestCase): def testGetLogitsAndProbImproperArguments(self): with self.test_session(): with self.assertRaises(ValueError): distribution_util.get_logits_and_prob(logits=None, p=None) with self.assertRaises(ValueError): distribution_util.get_logits_and_prob(logits=[0.1], p=[0.1]) def testGetLogitsAndProbLogits(self): p = np.array([0.01, 0.2, 0.5, 0.7, .99], dtype=np.float32) logits = special.logit(p) with self.test_session(): new_logits, new_p = distribution_util.get_logits_and_prob( logits=logits, validate_args=True) self.assertAllClose(p, new_p.eval()) self.assertAllClose(logits, new_logits.eval()) def testGetLogitsAndProbLogitsMultidimensional(self): p = np.array([0.2, 0.3, 0.5], dtype=np.float32) logits = np.log(p) with self.test_session(): new_logits, new_p = distribution_util.get_logits_and_prob( logits=logits, multidimensional=True, validate_args=True) self.assertAllClose(new_p.eval(), p) self.assertAllClose(new_logits.eval(), logits) def testGetLogitsAndProbProbability(self): p = np.array([0.01, 0.2, 0.5, 0.7, .99], dtype=np.float32) with self.test_session(): new_logits, new_p = distribution_util.get_logits_and_prob( p=p, validate_args=True) self.assertAllClose(special.logit(p), new_logits.eval()) self.assertAllClose(p, new_p.eval()) def testGetLogitsAndProbProbabilityMultidimensional(self): p = np.array([[0.3, 0.4, 0.3], [0.1, 0.5, 0.4]], dtype=np.float32) with self.test_session(): new_logits, new_p = distribution_util.get_logits_and_prob( p=p, multidimensional=True, validate_args=True) self.assertAllClose(np.log(p), new_logits.eval()) self.assertAllClose(p, new_p.eval()) def testGetLogitsAndProbProbabilityValidateArgs(self): p = [0.01, 0.2, 0.5, 0.7, .99] # Component less than 0. p2 = [-1, 0.2, 0.5, 0.3, .2] # Component greater than 1. p3 = [2, 0.2, 0.5, 0.3, .2] with self.test_session(): _, prob = distribution_util.get_logits_and_prob(p=p, validate_args=True) prob.eval() with self.assertRaisesOpError("Condition x >= 0"): _, prob = distribution_util.get_logits_and_prob( p=p2, validate_args=True) prob.eval() _, prob = distribution_util.get_logits_and_prob(p=p2, validate_args=False) prob.eval() with self.assertRaisesOpError("p has components greater than 1"): _, prob = distribution_util.get_logits_and_prob( p=p3, validate_args=True) prob.eval() _, prob = distribution_util.get_logits_and_prob(p=p3, validate_args=False) prob.eval() def testGetLogitsAndProbProbabilityValidateArgsMultidimensional(self): p = np.array([[0.3, 0.4, 0.3], [0.1, 0.5, 0.4]], dtype=np.float32) # Component less than 0. Still sums to 1. p2 = np.array([[-.3, 0.4, 0.9], [0.1, 0.5, 0.4]], dtype=np.float32) # Component greater than 1. Does not sum to 1. p3 = np.array([[1.3, 0.0, 0.0], [0.1, 0.5, 0.4]], dtype=np.float32) # Does not sum to 1. p4 = np.array([[1.1, 0.3, 0.4], [0.1, 0.5, 0.4]], dtype=np.float32) with self.test_session(): _, prob = distribution_util.get_logits_and_prob( p=p, multidimensional=True) prob.eval() with self.assertRaisesOpError("Condition x >= 0"): _, prob = distribution_util.get_logits_and_prob( p=p2, multidimensional=True, validate_args=True) prob.eval() _, prob = distribution_util.get_logits_and_prob( p=p2, multidimensional=True, validate_args=False) prob.eval() with self.assertRaisesOpError( "(p has components greater than 1|p does not sum to 1)"): _, prob = distribution_util.get_logits_and_prob( p=p3, multidimensional=True, validate_args=True) prob.eval() _, prob = distribution_util.get_logits_and_prob( p=p3, multidimensional=True, validate_args=False) prob.eval() with self.assertRaisesOpError("p does not sum to 1"): _, prob = distribution_util.get_logits_and_prob( p=p4, multidimensional=True, validate_args=True) prob.eval() _, prob = distribution_util.get_logits_and_prob( p=p4, multidimensional=True, validate_args=False) prob.eval() class LogCombinationsTest(tf.test.TestCase): def testLogCombinationsBinomial(self): n = [2, 5, 12, 15] k = [1, 2, 4, 11] log_combs = np.log(special.binom(n, k)) with self.test_session(): n = np.array(n, dtype=np.float32) counts = [[1., 1], [2., 3], [4., 8], [11, 4]] log_binom = distribution_util.log_combinations(n, counts) self.assertEqual([4], log_binom.get_shape()) self.assertAllClose(log_combs, log_binom.eval()) def testLogCombinationsShape(self): # Shape [2, 2] n = [[2, 5], [12, 15]] with self.test_session(): n = np.array(n, dtype=np.float32) # Shape [2, 2, 4] counts = [[[1., 1, 0, 0], [2., 2, 1, 0]], [[4., 4, 1, 3], [10, 1, 1, 4]]] log_binom = distribution_util.log_combinations(n, counts) self.assertEqual([2, 2], log_binom.get_shape()) class DynamicShapeTest(tf.test.TestCase): def testSameDynamicShape(self): with self.test_session(): scalar = tf.constant(2.0) scalar1 = tf.placeholder(dtype=tf.float32) vector = [0.3, 0.4, 0.5] vector1 = tf.placeholder(dtype=tf.float32, shape=[None]) vector2 = tf.placeholder(dtype=tf.float32, shape=[None]) multidimensional = [[0.3, 0.4], [0.2, 0.6]] multidimensional1 = tf.placeholder(dtype=tf.float32, shape=[None, None]) multidimensional2 = tf.placeholder(dtype=tf.float32, shape=[None, None]) # Scalar self.assertTrue(distribution_util.same_dynamic_shape( scalar, scalar1).eval({ scalar1: 2.0})) # Vector self.assertTrue(distribution_util.same_dynamic_shape( vector, vector1).eval({ vector1: [2.0, 3.0, 4.0]})) self.assertTrue(distribution_util.same_dynamic_shape( vector1, vector2).eval({ vector1: [2.0, 3.0, 4.0], vector2: [2.0, 3.5, 6.0]})) # Multidimensional self.assertTrue(distribution_util.same_dynamic_shape( multidimensional, multidimensional1).eval({ multidimensional1: [[2.0, 3.0], [3.0, 4.0]]})) self.assertTrue(distribution_util.same_dynamic_shape( multidimensional1, multidimensional2).eval({ multidimensional1: [[2.0, 3.0], [3.0, 4.0]], multidimensional2: [[1.0, 3.5], [6.3, 2.3]]})) # Scalar, X self.assertFalse(distribution_util.same_dynamic_shape( scalar, vector1).eval({ vector1: [2.0, 3.0, 4.0]})) self.assertFalse(distribution_util.same_dynamic_shape( scalar1, vector1).eval({ scalar1: 2.0, vector1: [2.0, 3.0, 4.0]})) self.assertFalse(distribution_util.same_dynamic_shape( scalar, multidimensional1).eval({ multidimensional1: [[2.0, 3.0], [3.0, 4.0]]})) self.assertFalse(distribution_util.same_dynamic_shape( scalar1, multidimensional1).eval({ scalar1: 2.0, multidimensional1: [[2.0, 3.0], [3.0, 4.0]]})) # Vector, X self.assertFalse(distribution_util.same_dynamic_shape( vector, vector1).eval({ vector1: [2.0, 3.0]})) self.assertFalse(distribution_util.same_dynamic_shape( vector1, vector2).eval({ vector1: [2.0, 3.0, 4.0], vector2: [6.0]})) self.assertFalse(distribution_util.same_dynamic_shape( vector, multidimensional1).eval({ multidimensional1: [[2.0, 3.0], [3.0, 4.0]]})) self.assertFalse(distribution_util.same_dynamic_shape( vector1, multidimensional1).eval({ vector1: [2.0, 3.0, 4.0], multidimensional1: [[2.0, 3.0], [3.0, 4.0]]})) # Multidimensional, X self.assertFalse(distribution_util.same_dynamic_shape( multidimensional, multidimensional1).eval({ multidimensional1: [[1.0, 3.5, 5.0], [6.3, 2.3, 7.1]]})) self.assertFalse(distribution_util.same_dynamic_shape( multidimensional1, multidimensional2).eval({ multidimensional1: [[2.0, 3.0], [3.0, 4.0]], multidimensional2: [[1.0, 3.5, 5.0], [6.3, 2.3, 7.1]]})) class RotateTransposeTest(tf.test.TestCase): def _np_rotate_transpose(self, x, shift): if not isinstance(x, np.ndarray): x = np.array(x) return np.transpose(x, np.roll(np.arange(len(x.shape)), shift)) def testRollStatic(self): with self.test_session(): with self.assertRaisesRegexp( ValueError, "None values not supported."): distribution_util.rotate_transpose(None, 1) for x in (np.ones(1), np.ones((2, 1)), np.ones((3, 2, 1))): for shift in np.arange(-5, 5): y = distribution_util.rotate_transpose(x, shift) self.assertAllEqual(self._np_rotate_transpose(x, shift), y.eval()) self.assertAllEqual(np.roll(x.shape, shift), y.get_shape().as_list()) def testRollDynamic(self): with self.test_session() as sess: x = tf.placeholder(tf.float32) shift = tf.placeholder(tf.int32) for x_value in (np.ones(1, dtype=x.dtype.as_numpy_dtype()), np.ones((2, 1), dtype=x.dtype.as_numpy_dtype()), np.ones((3, 2, 1), dtype=x.dtype.as_numpy_dtype())): for shift_value in np.arange(-5, 5): self.assertAllEqual( self._np_rotate_transpose(x_value, shift_value), sess.run(distribution_util.rotate_transpose(x, shift), feed_dict={x: x_value, shift: shift_value})) class PickVectorTest(tf.test.TestCase): def testCorrectlyPicksVector(self): with self.test_session(): x = np.arange(10, 12) y = np.arange(15, 18) self.assertAllEqual( x, distribution_util.pick_vector( tf.less(0, 5), x, y).eval()) self.assertAllEqual( y, distribution_util.pick_vector( tf.less(5, 0), x, y).eval()) self.assertAllEqual( x, distribution_util.pick_vector( tf.constant(True), x, y)) # No eval. self.assertAllEqual( y, distribution_util.pick_vector( tf.constant(False), x, y)) # No eval. class FillLowerTriangularTest(tf.test.TestCase): def setUp(self): self._rng = np.random.RandomState(42) def _fill_lower_triangular(self, x): """Numpy implementation of `fill_lower_triangular`.""" x = np.asarray(x) d = x.shape[-1] # d = n(n+1)/2 implies n is: n = int(0.5 * (math.sqrt(1. + 8. * d) - 1.)) ids = np.tril_indices(n) y = np.zeros(list(x.shape[:-1]) + [n, n], dtype=x.dtype) y[..., ids[0], ids[1]] = x return y def testCorrectlyMakes1x1LowerTril(self): with self.test_session(): x = tf.convert_to_tensor(self._rng.randn(3, 1)) expected = self._fill_lower_triangular(tensor_util.constant_value(x)) actual = distribution_util.fill_lower_triangular(x, validate_args=True) self.assertAllEqual(expected.shape, actual.get_shape()) self.assertAllEqual(expected, actual.eval()) def testCorrectlyMakesNoBatchLowerTril(self): with self.test_session(): x = tf.convert_to_tensor(self._rng.randn(10)) expected = self._fill_lower_triangular(tensor_util.constant_value(x)) actual = distribution_util.fill_lower_triangular(x, validate_args=True) self.assertAllEqual(expected.shape, actual.get_shape()) self.assertAllEqual(expected, actual.eval()) g = tf.gradients(distribution_util.fill_lower_triangular(x), x) self.assertAllEqual(np.tri(4).reshape(-1), g[0].values.eval()) def testCorrectlyMakesBatchLowerTril(self): with self.test_session(): x = tf.convert_to_tensor(self._rng.randn(2, 2, 6)) expected = self._fill_lower_triangular(tensor_util.constant_value(x)) actual = distribution_util.fill_lower_triangular(x, validate_args=True) self.assertAllEqual(expected.shape, actual.get_shape()) self.assertAllEqual(expected, actual.eval()) self.assertAllEqual( np.ones((2, 2, 6)), tf.gradients(distribution_util.fill_lower_triangular( x), x)[0].eval()) class GenNewSeedTest(tf.test.TestCase): def testOnlyNoneReturnsNone(self): self.assertFalse(distribution_util.gen_new_seed(0, "salt") is None) self.assertTrue(distribution_util.gen_new_seed(None, "salt") is None) if __name__ == "__main__": tf.test.main() import os import tempfile import numpy import math import random import time from weka_utilities import test_file_creation, feature_selection, Test_result from data_mining.PrintOutput import PrintOutput #loads system variables path = os.environ.get('OPUS_HOME') path = os.path.join(path, "src", "data_mining", "SYSTEM_VARIABLES.py") execfile(path) class Num_model : def __init__(self, xml_elem, MAKE_ALL_PREDS, logCB = None, progressCB = None) : #For reporting results self.printOut = PrintOutput(logCB, progressCB, PROFILING) #Test specific information self.test_attribute = xml_elem.attributes["test_attribute"].value self.test_classifier = "weka.classifiers.lazy.IBk" if xml_elem.hasAttribute("test_classifier") : self.test_classifier = xml_elem.attributes["classifier"].value self.test_options = "-I -K 20 -X -A weka.core.neighboursearch.KDTree" if xml_elem.hasAttribute("options") : self.test_options = xml_elem.attributes["options"].value #Feature selection information self.use_feature_selection = False self.using_pca = False self.search_class = "" self.evaluation_class = "" if xml_elem.hasAttribute('fs_evaluation_class'): self.use_feature_selection = True self.search_class = xml_elem.attributes["fs_search_class"].value self.evaluation_class = xml_elem.attributes["fs_evaluation_class"].value #Checking for pca if self.evaluation_class.find("PrincipalComponents") > -1 : self.using_pca = True #Attributes that the search class starts with (Not used with PCA) self.start_attributes = [] if xml_elem.hasAttribute('fs_start_attributes') : self.start_attributes = util_get_attribute_list(xml_elem.attributes['fs_start_attributes'].value) #Attributes that are used to make the prediction attributes_string = xml_elem.attributes["train_attributes"].value self.attributes = util_get_attribute_list(attributes_string) #Values that are considered null for the target attribute self.null_value_list = [] elements = xml_elem.getElementsByTagName('null_values') if len(elements) > 0 : null_val_element = elements[0] for element in null_val_element.getElementsByTagName('v') : attribute = element.attributes['attribute'].value type = element.attributes['type'].value value = element.attributes['value'].value vt = element.attributes['vt'].value null_dict = {"attribute" : attribute, "type" : type} if vt == "int" : null_dict["value"] = int(value) elif vt == "string" : null_dict["value"] = str(value) self.null_value_list.append(null_dict) #Simply defined null values if xml_elem.hasAttribute("null_value") : null_value = xml_elem.attributes["null_value"].value null_dict = {"attribute" : self.test_attribute, "type" : "E", "value" : int(null_value)} self.null_value_list.append(null_dict) #Random information self.test_type = "Num" self.MAKE_ALL_PREDS = MAKE_ALL_PREDS def get_predictions(self, query_manager) : #Filenames test_filename = "test" + str(int(time.time())) + ".arff" train_filename = "train" + str(int(time.time())) + ".arff" train_log = "train_log" + str(int(time.time())) + ".arff" result_filename = "results" + str(int(time.time())) + ".txt" #Creates (or clears) files that are used by the binary IS_NUM_TEST = True file_creation_info = test_file_creation(IS_NUM_TEST, self.using_pca, test_filename, train_filename, query_manager, self) target_values = file_creation_info["target_values"] target_value_null = file_creation_info["target_value_null"] attribute_indexes = file_creation_info["attribute_indexes"] #If there are no null values in the test set #And the run is only replacing null values then terminate if no null values if not self.MAKE_ALL_PREDS and target_value_null.count(True) == 0 : os.remove(test_filename) os.remove(train_filename) return None #Running feature selection process if needed acc_est = {} if self.use_feature_selection : (test_filename, train_filename, selected_attributes) = feature_selection(test_filename, train_filename, query_manager, file_creation_info, self, IS_NUM_TEST) acc_est["selected attributes"] = selected_attributes #Running tests model_name = "saved_model" + str(int(time.time())) path_spef_weka = os.path.join( path, "models", "weka.jar") train_string = "java -Xmx1024m -cp " + path_spef_weka + " " + self.test_classifier + " -d " + model_name + " " + self.test_options + " -t " + train_filename + " >> " + train_log test_string = "java -Xmx1024m -cp " + path_spef_weka + " " + self.test_classifier + " -l " + model_name + " -T " + test_filename + " -p 0 >> " + result_filename self.printOut.pLog( "PRED- Training model") os.system(train_string) self.printOut.pLog( "PRED- Making predictions") os.system(test_string) #Gathering results for each test instance self.printOut.pLog( "PRED- Getting results") f = open(result_filename) prediction_list = [] confidence_list = [] #For stat keeping absolute_diff_list = [] relative_diff_list = [] index = 0 collect_results = False for line in f.readlines() : line_list = line.split() #Getting results if collect_results and len(line_list) > 1: prediction = float(line_list[2]) prediction_list.append(prediction) confidence_list.append(0.0) #Getting difference between predicted and actuall results #For non null values if not target_value_null[index] : actual = float(target_values[index]) diff = math.fabs(actual - prediction) absolute_diff_list.append(diff) if actual > 0 : relative_diff_list.append(diff / actual) else : relative_diff_list.append(-1) index += 1 #Seeing if you are at the results portion of the file if line.find("inst#") > -1 : collect_results = True f.close() #Gathering accuracy estimations f = open(train_log) cross_val_info = False get_k_value = False for line in f.readlines() : #Getting all performance related metrics if cross_val_info : line = line.rstrip('\n') line = line.rstrip('\t') line = line.rstrip('\b') line = line.rstrip(' %') list = line.split(' ') if len(list) > 1: attribute = list[0] value = list[len(list) - 1] value = float(value) acc_est[attribute] = value #Getting parameter search results if get_k_value and line.find('using') > -1: list = line.split(' ') k = int(list[1]) acc_est["1 Parameter: k value"] = k get_k_value = False #Finding cross validation info if line.find('Cross-validation') > -1 : cross_val_info = True #Finding k value info if line.find('IB1 instance-based classifier') > -1 : get_k_value = True f.close() #Adding actual performance statistics absolute_diff_array = numpy.array(absolute_diff_list) relative_diff_array = numpy.array(relative_diff_list) absolute_mean = numpy.mean(absolute_diff_array) absolute_std = numpy.std(absolute_diff_array) relative_mean = numpy.mean(relative_diff_array) relative_std = numpy.std(relative_diff_array) acc_est["2 On test data: mean absolute diff"] = absolute_mean acc_est["2 On test data: std absolute diff"] = absolute_std acc_est["2 On test data: mean relative diff"] = relative_mean acc_est["2 On test data: std relative diff"] = relative_std #Add number of test instances to the accuracy estimation current_test_num = query_manager.current_test_block.parcel_count acc_est["test instance count"] = current_test_num / query_manager.group_max acc_est["block number"] = (len(query_manager.used_blocks) - 1)*query_manager.group_max + query_manager.group_count #Removing files os.remove(test_filename) os.remove(train_filename) os.remove(train_log) os.remove(result_filename) os.remove(model_name) return Test_result("Num", self.test_attribute, prediction_list, confidence_list, acc_est) #Gets attributes from a string def util_get_attribute_list(string): initial_list = string.split(",") list = [] for attribute in initial_list : new = attribute.rstrip(" ") new = new.lstrip(" ") list.append(str(new)) return list #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2014 The ProteinDF development team. # see also AUTHORS and README if provided. # # This file is a part of the ProteinDF software package. # # The ProteinDF 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. # # The ProteinDF 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 ProteinDF. If not, see . """ output xyz """ import os import sys import argparse try: import msgpack except: import msgpack_pure as msgpack import proteindf_tools as pdf ANG2AU = 0.52917721067 def main(): # parse args parser = argparse.ArgumentParser(description='output XYZ file') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-d', '--db', nargs='?', action='store', const='pdfresults.db', help='ProteinDF results file') group.add_argument('-p', '--param', nargs='?', action='store', const='pdfparam.mpac', help='ProteinDF parameter file') parser.add_argument("-v", "--verbose", action="store_true", default=False) parser.add_argument('-D', '--debug', action='store_true', default=False) args = parser.parse_args() # setting verbose = args.verbose if args.debug: logging.basicConfig(level=logging.DEBUG) # atomgroup = None if args.db: entry = pdf.PdfArchive(args.db) atomgroup = entry.get_molecule() elif args.param: pdfparam = pdf.load_pdfparam(args.param) atomgroup = pdfparam.molecule # a.u, to angstroam atomgroup *= ANG2AU print(atomgroup.get_xyz()) if __name__ == '__main__': main() # -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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. # import getpass import os import luigi.contrib.hadoop import luigi.contrib.hdfs from nose.plugins.attrib import attr import unittest try: from snakebite.minicluster import MiniCluster except ImportError: raise unittest.SkipTest('Snakebite not installed') @attr('minicluster') class MiniClusterTestCase(unittest.TestCase): """ Base class for test cases that rely on Hadoop's minicluster functionality. This in turn depends on Snakebite's minicluster setup: http://hadoop.apache.org/docs/r2.5.1/hadoop-project-dist/hadoop-common/CLIMiniCluster.html https://github.com/spotify/snakebite""" cluster = None @classmethod def setupClass(cls): if not cls.cluster: cls.cluster = MiniCluster(None, nnport=50030) cls.cluster.mkdir("/tmp") @classmethod def tearDownClass(cls): if cls.cluster: cls.cluster.terminate() def setUp(self): self.fs = luigi.contrib.hdfs.get_autoconfig_client() cfg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "testconfig") hadoop_bin = os.path.join(os.environ['HADOOP_HOME'], 'bin/hadoop') cmd = "{} --config {}".format(hadoop_bin, cfg_path) self.stashed_hdfs_client = luigi.configuration.get_config().get('hadoop', 'command', None) luigi.configuration.get_config().set('hadoop', 'command', cmd) def tearDown(self): if self.fs.exists(self._test_dir()): self.fs.remove(self._test_dir(), skip_trash=True) if self.stashed_hdfs_client: luigi.configuration.get_config().set('hadoop', 'command', self.stashed_hdfs_client) @staticmethod def _test_dir(): return '/tmp/luigi_tmp_testdir_%s' % getpass.getuser() @staticmethod def _test_file(suffix=""): return '%s/luigi_tmp_testfile%s' % (MiniClusterTestCase._test_dir(), suffix) class MiniClusterHadoopJobRunner(luigi.contrib.hadoop.HadoopJobRunner): ''' The default job runner just reads from config and sets stuff ''' def __init__(self): # Locate the hadoop streaming jar in the hadoop directory hadoop_tools_lib = os.path.join(os.environ['HADOOP_HOME'], 'share/hadoop/tools/lib') for path in os.listdir(hadoop_tools_lib): if path.startswith('hadoop-streaming') and path.endswith('.jar'): streaming_jar = os.path.join(hadoop_tools_lib, path) break else: raise Exception('Could not locate streaming jar in ' + hadoop_tools_lib) super(MiniClusterHadoopJobRunner, self).__init__(streaming_jar=streaming_jar) # # Newfies-Dialer License # http://www.newfies-dialer.org # # 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 (C) 2011-2012 Star2Billing S.L. # # The Initial Developer of the Original Code is # Arezqui Belaid # from django.template.defaultfilters import register from django.utils.translation import ugettext as _ from mod_sms.constants import SMS_CAMPAIGN_STATUS, SMS_CAMPAIGN_STATUS_COLOR from mod_utils.function_def import get_common_campaign_status_url, get_common_campaign_status,\ get_status_value @register.filter(name='sms_campaign_status') def sms_campaign_status(value): """SMS Campaign Status >>> sms_campaign_status(1) 'START' >>> sms_campaign_status(2) 'PAUSE' >>> sms_campaign_status(3) 'ABORT' >>> sms_campaign_status(4) 'END' >>> sms_campaign_status(0) '' """ return get_status_value(value, SMS_CAMPAIGN_STATUS) @register.filter(name='get_sms_campaign_status') def get_sms_campaign_status(id): return get_common_campaign_status(id, SMS_CAMPAIGN_STATUS, SMS_CAMPAIGN_STATUS_COLOR) @register.simple_tag(name='get_sms_campaign_status_url') def get_sms_campaign_status_url(id, status): return get_common_campaign_status_url( id, status, 'update_sms_campaign_status_cust/', SMS_CAMPAIGN_STATUS) @register.filter(name='create_duplicate_sms_campaign') def create_duplicate_sms_campaign(sms_campaign_id): """Create link to make duplicate campaign""" link = '' \ % (sms_campaign_id, _('duplicate this sms campaign').capitalize()) return link @register.filter(name='get_sms_campaign_textmessage') def get_sms_campaign_textmessage(sms_campaign_id): """Create link to get sms campaign's text-message""" link = '' \ % (sms_campaign_id, _('get text-message of this sms campaign').capitalize()) return link import hashlib import simplejson from django.contrib.auth.models import User from django.db import models from django.shortcuts import get_object_or_404 from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from guardian.shortcuts import * from agora_site.misc.utils import JSONField from agora_site.agora_core.models.election import Election from agora_site.agora_core.models.castvote import CastVote class DelegateElectionCount(models.Model): ''' Stores how many people delegated into a delegate in a given election ''' delegate = models.ForeignKey(User, related_name='delegate_election_counts', verbose_name=_('Delegate'), null=False) election = models.ForeignKey(Election, related_name='delegate_election_counts', verbose_name=_('Election'), null=False) # number of effective vote delegations count = models.IntegerField(null=False) # number of effective vote delegations / number of valid votes in the election # 0 if number of valid votes is zero count_percentage = models.FloatField(null=False, default=0) # position in the rank of delegates with more effective vote delegations # None if the delegate did not get any effective vote delegation rank = models.IntegerField(null=True, blank=True) created_at_date = models.DateTimeField(_(u'Created at date'), auto_now_add=True, editable=True, default=timezone.now()) delegate_vote = models.ForeignKey(CastVote, related_name='delegate_election_count', verbose_name=_('Delegate vote'), null=True, blank=True) class Meta: app_label = 'agora_core' unique_together = (('election', 'delegate'),) # Copyright 2006--2010 Red Hat, 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; version 2 of the License. # # 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, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # Authors: # Jan Pazdziora jpazdziora at redhat dot com # Daniel Benamy import sys sys.path.append("/usr/share/rhn") from up2date_client import rhnreg from up2date_client import rhnregGui import gtk from gtk import glade import gettext _ = lambda x: gettext.ldgettext("rhn-client-tools", x) gtk.glade.bindtextdomain("rhn-client-tools") from firstboot.module import Module from firstboot.constants import * class moduleClass(Module): def __init__(self): Module.__init__(self) self.priority = 107.5 self.sidebarTitle = _("Provide Certificate") self.title = _("Provide Certificate") def needsNetwork(self): return True def apply(self, interface, testing=False): if testing: return RESULT_SUCCESS status = self.provideCertificatePage.provideCertificatePageApply() if status == 0: # cert was installed return RESULT_SUCCESS elif status == 1: # the user doesn't want to provide a cert right now # TODO write a message to disk like the other cases? need to decide # how we want to do error handling in general. interface.moveToPage(moduleTitle=_("Finish Updates Setup")) return RESULT_JUMP else: # an error occurred and the user was notified assert status == 2 return RESULT_FAILURE def createScreen(self): self.provideCertificatePage = rhnregGui.ProvideCertificatePage() self.vbox = gtk.VBox(spacing=5) self.vbox.pack_start(self.provideCertificatePage.provideCertificatePageVbox(), True, True) def initializeUI(self): self.provideCertificatePage.setUrlInWidget() def shouldAppear(self): if rhnreg.registered(): return False return True #!/usr/bin/env python # ---------------------------------------------------------------------------- # 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. # ---------------------------------------------------------------------------- # An example setup.py that can be used to create both standalone Windows # executables (requires py2exe) and Mac OS X applications (requires py2app). # # On Windows:: # # python setup.py py2exe # # On Mac OS X:: # # python setup.py py2app # from distutils.core import setup import os # The main entry point of the program script_file = 'astraea.py' # Create a list of data files. Add everything in the 'res/' directory. data_files = [] for file in os.listdir('res'): file = os.path.join('res', file) if os.path.isfile(file): data_files.append(file) # Setup args that apply to all setups, including ordinary distutils. setup_args = dict( data_files=[('res', data_files)] ) # py2exe options try: import py2exe setup_args.update(dict( windows=[dict( script=script_file, icon_resources=[(1, 'assets/app.ico')], )], )) except ImportError: pass # py2app options try: import py2app setup_args.update(dict( app=[script_file], options=dict(py2app=dict( argv_emulation=True, iconfile='assets/app.icns', )), )) except ImportError: pass setup(**setup_args) # Copyright (c) 2013 NTT DOCOMO, INC. # Copyright 2014 IBM Corporation. # 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. """The bare-metal admin extension.""" from oslo_config import cfg from oslo_utils import importutils import webob from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.i18n import _ ironic_client = importutils.try_import('ironicclient.client') ironic_exc = importutils.try_import('ironicclient.exc') CONF = cfg.CONF ALIAS = "os-baremetal-nodes" authorize = extensions.os_compute_authorizer(ALIAS) node_fields = ['id', 'cpus', 'local_gb', 'memory_mb', 'pm_address', 'pm_user', 'service_host', 'terminal_port', 'instance_uuid'] node_ext_fields = ['uuid', 'task_state', 'updated_at', 'pxe_config_path'] interface_fields = ['id', 'address', 'datapath_id', 'port_no'] CONF.import_opt('api_version', 'nova.virt.ironic.driver', group='ironic') CONF.import_opt('api_endpoint', 'nova.virt.ironic.driver', group='ironic') CONF.import_opt('admin_username', 'nova.virt.ironic.driver', group='ironic') CONF.import_opt('admin_password', 'nova.virt.ironic.driver', group='ironic') CONF.import_opt('admin_tenant_name', 'nova.virt.ironic.driver', group='ironic') CONF.import_opt('compute_driver', 'nova.virt.driver') def _check_ironic_client_enabled(): """Check whether Ironic is installed or not.""" if ironic_client is None: common.raise_feature_not_supported() def _get_ironic_client(): """return an Ironic client.""" # TODO(NobodyCam): Fix insecure setting kwargs = {'os_username': CONF.ironic.admin_username, 'os_password': CONF.ironic.admin_password, 'os_auth_url': CONF.ironic.admin_url, 'os_tenant_name': CONF.ironic.admin_tenant_name, 'os_service_type': 'baremetal', 'os_endpoint_type': 'public', 'insecure': 'true', 'ironic_url': CONF.ironic.api_endpoint} icli = ironic_client.get_client(CONF.ironic.api_version, **kwargs) return icli def _no_ironic_proxy(cmd): raise webob.exc.HTTPBadRequest( explanation=_("Command Not supported. Please use Ironic " "command %(cmd)s to perform this " "action.") % {'cmd': cmd}) class BareMetalNodeController(wsgi.Controller): """The Bare-Metal Node API controller for the OpenStack API.""" def _node_dict(self, node_ref): d = {} for f in node_fields: d[f] = node_ref.get(f) for f in node_ext_fields: d[f] = node_ref.get(f) return d @extensions.expected_errors((404, 501)) def index(self, req): context = req.environ['nova.context'] authorize(context) nodes = [] # proxy command to Ironic _check_ironic_client_enabled() icli = _get_ironic_client() ironic_nodes = icli.node.list(detail=True) for inode in ironic_nodes: node = {'id': inode.uuid, 'interfaces': [], 'host': 'IRONIC MANAGED', 'task_state': inode.provision_state, 'cpus': inode.properties.get('cpus', 0), 'memory_mb': inode.properties.get('memory_mb', 0), 'disk_gb': inode.properties.get('local_gb', 0)} nodes.append(node) return {'nodes': nodes} @extensions.expected_errors((404, 501)) def show(self, req, id): context = req.environ['nova.context'] authorize(context) # proxy command to Ironic _check_ironic_client_enabled() icli = _get_ironic_client() try: inode = icli.node.get(id) except ironic_exc.NotFound: msg = _("Node %s could not be found.") % id raise webob.exc.HTTPNotFound(explanation=msg) iports = icli.node.list_ports(id) node = {'id': inode.uuid, 'interfaces': [], 'host': 'IRONIC MANAGED', 'task_state': inode.provision_state, 'cpus': inode.properties.get('cpus', 0), 'memory_mb': inode.properties.get('memory_mb', 0), 'disk_gb': inode.properties.get('local_gb', 0), 'instance_uuid': inode.instance_uuid} for port in iports: node['interfaces'].append({'address': port.address}) return {'node': node} @extensions.expected_errors(400) def create(self, req, body): _no_ironic_proxy("port-create") @extensions.expected_errors(400) def delete(self, req, id): _no_ironic_proxy("port-create") @wsgi.action('add_interface') @extensions.expected_errors(400) def _add_interface(self, req, id, body): _no_ironic_proxy("port-create") @wsgi.action('remove_interface') @extensions.expected_errors(400) def _remove_interface(self, req, id, body): _no_ironic_proxy("port-delete") class BareMetalNodes(extensions.V3APIExtensionBase): """Admin-only bare-metal node administration.""" name = "BareMetalNodes" alias = ALIAS version = 1 def get_resources(self): resource = [extensions.ResourceExtension(ALIAS, BareMetalNodeController(), member_actions={"action": "POST"})] return resource def get_controller_extensions(self): """It's an abstract function V3APIExtensionBase and the extension will not be loaded without it. """ return [] #!/usr/bin/env python # Copyright 2017 gRPC authors. # # 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. import yaml import argparse import datetime import csv argp = argparse.ArgumentParser(description='Convert cloc yaml to bigquery csv') argp.add_argument('-i', '--input', type=str) argp.add_argument( '-d', '--date', type=str, default=datetime.date.today().strftime('%Y-%m-%d')) argp.add_argument('-o', '--output', type=str, default='out.csv') args = argp.parse_args() data = yaml.load(open(args.input).read()) with open(args.output, 'w') as outf: writer = csv.DictWriter( outf, ['date', 'name', 'language', 'code', 'comment', 'blank']) for key, value in data.iteritems(): if key == 'header': continue if key == 'SUM': continue if key.startswith('third_party/'): continue row = {'name': key, 'date': args.date} row.update(value) writer.writerow(row) # 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. import os.path from oslo_log import log as logging from tempest_lib.common.utils import data_utils from tempest_lib import exceptions as lib_exc import yaml from tempest import config import tempest.test CONF = config.CONF LOG = logging.getLogger(__name__) class BaseOrchestrationTest(tempest.test.BaseTestCase): """Base test case class for all Orchestration API tests.""" credentials = ['primary'] @classmethod def skip_checks(cls): super(BaseOrchestrationTest, cls).skip_checks() if not CONF.service_available.heat: raise cls.skipException("Heat support is required") @classmethod def setup_credentials(cls): super(BaseOrchestrationTest, cls).setup_credentials() stack_owner_role = CONF.orchestration.stack_owner_role cls.os = cls.get_client_manager(roles=[stack_owner_role]) @classmethod def setup_clients(cls): super(BaseOrchestrationTest, cls).setup_clients() cls.orchestration_client = cls.os.orchestration_client cls.client = cls.orchestration_client cls.servers_client = cls.os.servers_client cls.keypairs_client = cls.os.keypairs_client cls.network_client = cls.os.network_client cls.volumes_client = cls.os.volumes_client cls.images_v2_client = cls.os.image_client_v2 @classmethod def resource_setup(cls): super(BaseOrchestrationTest, cls).resource_setup() cls.build_timeout = CONF.orchestration.build_timeout cls.build_interval = CONF.orchestration.build_interval cls.stacks = [] cls.keypairs = [] cls.images = [] @classmethod def create_stack(cls, stack_name, template_data, parameters=None, environment=None, files=None): if parameters is None: parameters = {} body = cls.client.create_stack( stack_name, template=template_data, parameters=parameters, environment=environment, files=files) stack_id = body.response['location'].split('/')[-1] stack_identifier = '%s/%s' % (stack_name, stack_id) cls.stacks.append(stack_identifier) return stack_identifier @classmethod def _clear_stacks(cls): for stack_identifier in cls.stacks: try: cls.client.delete_stack(stack_identifier) except lib_exc.NotFound: pass for stack_identifier in cls.stacks: try: cls.client.wait_for_stack_status( stack_identifier, 'DELETE_COMPLETE') except lib_exc.NotFound: pass @classmethod def _create_keypair(cls, name_start='keypair-heat-'): kp_name = data_utils.rand_name(name_start) body = cls.keypairs_client.create_keypair(kp_name) cls.keypairs.append(kp_name) return body @classmethod def _clear_keypairs(cls): for kp_name in cls.keypairs: try: cls.keypairs_client.delete_keypair(kp_name) except Exception: pass @classmethod def _create_image(cls, name_start='image-heat-', container_format='bare', disk_format='iso'): image_name = data_utils.rand_name(name_start) body = cls.images_v2_client.create_image(image_name, container_format, disk_format) image_id = body['id'] cls.images.append(image_id) return body @classmethod def _clear_images(cls): for image_id in cls.images: try: cls.images_v2_client.delete_image(image_id) except lib_exc.NotFound: pass @classmethod def read_template(cls, name, ext='yaml'): loc = ["stacks", "templates", "%s.%s" % (name, ext)] fullpath = os.path.join(os.path.dirname(__file__), *loc) with open(fullpath, "r") as f: content = f.read() return content @classmethod def load_template(cls, name, ext='yaml'): loc = ["stacks", "templates", "%s.%s" % (name, ext)] fullpath = os.path.join(os.path.dirname(__file__), *loc) with open(fullpath, "r") as f: return yaml.safe_load(f) @classmethod def resource_cleanup(cls): cls._clear_stacks() cls._clear_keypairs() cls._clear_images() super(BaseOrchestrationTest, cls).resource_cleanup() @staticmethod def stack_output(stack, output_key): """Return a stack output value for a given key.""" return next((o['output_value'] for o in stack['outputs'] if o['output_key'] == output_key), None) def assert_fields_in_dict(self, obj, *fields): for field in fields: self.assertIn(field, obj) def list_resources(self, stack_identifier): """Get a dict mapping of resource names to types.""" resources = self.client.list_resources(stack_identifier) self.assertIsInstance(resources, list) for res in resources: self.assert_fields_in_dict(res, 'logical_resource_id', 'resource_type', 'resource_status', 'updated_time') return dict((r['resource_name'], r['resource_type']) for r in resources) def get_stack_output(self, stack_identifier, output_key): body = self.client.show_stack(stack_identifier) return self.stack_output(body, output_key) # Copyright (c) 2005 The Regents of The University of Michigan # 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 copyright holders 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. # # Authors: Nathan Binkert from __future__ import print_function import os, sys from time import time if sys.version_info >= (3, 0): import tkinter as tk else: import Tkinter as tk # import rospkg as rp __all__ = ['InteractiveCostTuning'] class InteractiveCostTuning(object): def __init__(self, problem): # Initial setup self.master = tk.Tk() self.problem = problem # Set title self.master.winfo_toplevel().title("Interactive Cost Tuning") # Set icon # icon = rp.RosStack().get_path('exotica') + '/doc/images/EXOTica_icon.png' # img = tk.PhotoImage(file=icon) # self.master.tk.call('wm', 'iconphoto', self.master._w, img) # Grab current rhos and cost task map names self.rho = {} self.original_rho = {} self.cost_task_map_names = [] for k in list(problem.get_task_maps().keys()): try: r = problem.get_rho(k) self.rho[k] = r self.original_rho[k] = r self.cost_task_map_names.append(k) except: continue # Setup labels and entries self.entries = {} for i, k in enumerate(self.cost_task_map_names): tk.Label(self.master, text=k).grid(row=i, column=0) self.entries[k] = tk.Entry(self.master) self.entries[k].grid(row=i, column=1, pady=4) self.entries[k].insert(0, self.rho[k]) n_cost_task_maps = len(self.cost_task_map_names) tk.Label(self.master, text='Filename').grid(row=n_cost_task_maps, column=0, pady=4) self.entries['filename'] = tk.Entry(self.master) self.entries['filename'].grid(row=n_cost_task_maps, column=1, pady=4) self.entries['filename'].insert(0, 'FilenameHere') # Setup buttons tk.Button(self.master, text="Set", command=self.set_button).grid(row=n_cost_task_maps+1, column=0, pady=4) tk.Button(self.master, text="Save", command=self.save_button).grid(row=n_cost_task_maps+1, column=1, pady=4) tk.Button(self.master, text="Reset", command=self.reset_button).grid(row=n_cost_task_maps+2, column=0, pady=4) tk.Button(self.master, text="Quit", command=self.quit_button).grid(row=n_cost_task_maps+2, column=1, pady=4) def set_button(self): """Sets rho parameters in entries into Exotica problem.""" print("Setting cost parameters:") for k in self.cost_task_map_names: userin = self.entries[k].get() # is a str rho = float(eval(userin)) self.entries[k].delete(0, 'end') self.entries[k].insert(0, rho) self.problem.set_rho(k, rho) print(" {}\t{}".format(k, rho)) def save_button(self): """Saves current rho parameters in entries to file in home dir.""" # Generate filename, filename structure is FILENAMEINENTRY_TIMEINMS.costparams # Use time to avoid overwriting errors t = int(round(time() * 1000)) # time in ms (int) filename = "%s/%s_%d.costparams" % (os.environ['HOME'], self.entries['filename'].get(), t) # Save parameters with open(filename, 'w') as fout: fout.write('\n') for k in self.cost_task_map_names: fout.write(' \n'.format(k, float(eval(self.entries[k].get())))) fout.write('\n') print("Saved cost parameters to %s" % filename) def reset_button(self): """Resets entries/exotica to original cost terms as specified in xml.""" print("Resetting cost parameters:") for k in self.cost_task_map_names: rho = self.original_rho[k] # Reset entries self.entries[k].delete(0, 'end') self.entries[k].insert(0, rho) # Reset exotica problem self.problem.set_rho(k, rho) print(" {}\t{}".format(k, rho)) def quit_button(self): """Quits interactive cost tuning.""" print("Quitting interactive cost tuning...") self.master.quit() def mainloop(self): """Starts tk mainloop.""" tk.mainloop() #!/usr/bin/python # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see . # This is a DOCUMENTATION stub specific to this module, it extends # a documentation fragment located in ansible.utils.module_docs_fragments DOCUMENTATION = ''' --- module: rax_cbs short_description: Manipulate Rackspace Cloud Block Storage Volumes description: - Manipulate Rackspace Cloud Block Storage Volumes version_added: 1.6 options: description: description: - Description to give the volume being created default: null image: description: - image to use for bootable volumes. Can be an C(id), C(human_id) or C(name). This option requires C(pyrax>=1.9.3) default: null version_added: 1.9 meta: description: - A hash of metadata to associate with the volume default: null name: description: - Name to give the volume being created default: null required: true size: description: - Size of the volume to create in Gigabytes default: 100 required: true snapshot_id: description: - The id of the snapshot to create the volume from default: null state: description: - Indicate desired state of the resource choices: - present - absent default: present required: true volume_type: description: - Type of the volume being created choices: - SATA - SSD default: SATA required: true wait: description: - wait for the volume to be in state 'available' before returning default: "no" choices: - "yes" - "no" wait_timeout: description: - how long before wait gives up, in seconds default: 300 author: - "Christopher H. Laco (@claco)" - "Matt Martz (@sivel)" extends_documentation_fragment: rackspace.openstack ''' EXAMPLES = ''' - name: Build a Block Storage Volume gather_facts: False hosts: local connection: local tasks: - name: Storage volume create request local_action: module: rax_cbs credentials: ~/.raxpub name: my-volume description: My Volume volume_type: SSD size: 150 region: DFW wait: yes state: present meta: app: my-cool-app register: my_volume ''' from distutils.version import LooseVersion try: import pyrax HAS_PYRAX = True except ImportError: HAS_PYRAX = False def cloud_block_storage(module, state, name, description, meta, size, snapshot_id, volume_type, wait, wait_timeout, image): changed = False volume = None instance = {} cbs = pyrax.cloud_blockstorage if cbs is None: module.fail_json(msg='Failed to instantiate client. This ' 'typically indicates an invalid region or an ' 'incorrectly capitalized region name.') if image: # pyrax<1.9.3 did not have support for specifying an image when # creating a volume which is required for bootable volumes if LooseVersion(pyrax.version.version) < LooseVersion('1.9.3'): module.fail_json(msg='Creating a bootable volume requires ' 'pyrax>=1.9.3') image = rax_find_image(module, pyrax, image) volume = rax_find_volume(module, pyrax, name) if state == 'present': if not volume: kwargs = dict() if image: kwargs['image'] = image try: volume = cbs.create(name, size=size, volume_type=volume_type, description=description, metadata=meta, snapshot_id=snapshot_id, **kwargs) changed = True except Exception, e: module.fail_json(msg='%s' % e.message) else: if wait: attempts = wait_timeout / 5 pyrax.utils.wait_for_build(volume, interval=5, attempts=attempts) volume.get() instance = rax_to_dict(volume) result = dict(changed=changed, volume=instance) if volume.status == 'error': result['msg'] = '%s failed to build' % volume.id elif wait and volume.status not in VOLUME_STATUS: result['msg'] = 'Timeout waiting on %s' % volume.id if 'msg' in result: module.fail_json(**result) else: module.exit_json(**result) elif state == 'absent': if volume: instance = rax_to_dict(volume) try: volume.delete() changed = True except Exception, e: module.fail_json(msg='%s' % e.message) module.exit_json(changed=changed, volume=instance) def main(): argument_spec = rax_argument_spec() argument_spec.update( dict( description=dict(type='str'), image=dict(type='str'), meta=dict(type='dict', default={}), name=dict(required=True), size=dict(type='int', default=100), snapshot_id=dict(), state=dict(default='present', choices=['present', 'absent']), volume_type=dict(choices=['SSD', 'SATA'], default='SATA'), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=300) ) ) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together() ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') description = module.params.get('description') image = module.params.get('image') meta = module.params.get('meta') name = module.params.get('name') size = module.params.get('size') snapshot_id = module.params.get('snapshot_id') state = module.params.get('state') volume_type = module.params.get('volume_type') wait = module.params.get('wait') wait_timeout = module.params.get('wait_timeout') setup_rax_module(module, pyrax) cloud_block_storage(module, state, name, description, meta, size, snapshot_id, volume_type, wait, wait_timeout, image) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.rax import * # invoke the module main() # -*- coding: utf-8 -*- """ longboxed.frontend.admin ~~~~~~~~~~~~~~~~~~~~~~~~~ Administrative interface """ from datetime import datetime from flask import flash from flask.ext.security import current_user from flask.ext.admin import Admin, AdminIndexView from flask.ext.admin.actions import action from flask.ext.admin.babel import gettext, lazy_gettext from flask.ext.admin.contrib.sqla import ModelView from flask.ext.admin.contrib.sqla.ajax import QueryAjaxModelLoader from ..core import db from ..helpers import current_wednesday, last_wednesday, next_wednesday from ..models import (Creator, Issue, Publisher, Title, User, Role, Bundle, DiamondList) class LongboxedAdminIndexView(AdminIndexView): def is_accessible(self): return current_user.has_role('admin') class AdministratorBase(ModelView): def is_accessible(self): return current_user.has_role('admin') class SuperUserBase(ModelView): def is_accessible(self): return (current_user.has_role('admin') and current_user.has_role('super')) class IssueAdmin(AdministratorBase): edit_template = 'edit_issue_model.html' # List of columns that can be sorted column_sortable_list = ('issue_number', 'complete_title', 'on_sale_date', ('title',Title.name), ('publisher', Publisher.name)) column_searchable_list = ('complete_title', 'diamond_id') column_list = ('on_sale_date', 'prospective_release_date', 'diamond_id', 'old_diamond_id', 'issue_number', 'issues', 'complete_title', 'title', 'publisher') form_excluded_columns = ('cover_image', 'bundles') form_ajax_refs = { 'title': QueryAjaxModelLoader( 'title', db.session, Title, fields=['name'], page_size=10), 'publisher': QueryAjaxModelLoader( 'publisher', db.session, Publisher, fields=['name'], page_size=10), 'creators': QueryAjaxModelLoader( 'creators', db.session, Creator, fields=['name'], page_size=10) } def __init__(self, session): # Just call parent class with predefined model. super(IssueAdmin, self).__init__(Issue, session) def on_model_change(self, form, model): """Sets last_updated attribute of issue object""" model.last_updated = datetime.now() return def set_on_sale_date(self, ids, date): try: issues = Issue.query.filter(Issue.id.in_(*ids)).all() for issue in issues: issue.update(**{'on_sale_date': date}) except Exception, ex: flash(gettext('Failed to set date %(error)s', error=str(ex)), 'error') return @action('set_cover_image', lazy_gettext('Set Cover Image'), lazy_gettext('Are you sure you want to set the cover image?')) def set_cover_image(self, ids): try: issues = Issue.query.filter(Issue.id.in_(ids)).all() for issue in issues: issue.set_cover_image_from_url(issue.big_image, True) issue.find_or_create_thumbnail(width=250) except Exception, ex: flash(gettext('Failed to set cover image %(errors)s', error=str(ex)), 'error') return @action('current_wednesday', lazy_gettext('This Wed | %(date)s', date=current_wednesday()), lazy_gettext('Are you sure? | %(date)s', date=current_wednesday())) def action_current_wednesday(self, ids): self.set_on_sale_date(ids, current_wednesday()) @action('next_wednesday', lazy_gettext('Next Wed | %(date)s', date=next_wednesday()), lazy_gettext('Are you sure? | %(date)s', date=next_wednesday())) def action_next_wednesday(self, ids): self.set_on_sale_date(ids, next_wednesday()) @action('last_wednesday', lazy_gettext('Last Wed | %(date)s', date=last_wednesday()), lazy_gettext('Are you sure? | %(date)s', date=last_wednesday())) def action_last_wednesday(self, ids): self.set_on_sale_date(ids, last_wednesday()) @action('no_date', lazy_gettext('No Date'), lazy_gettext('Are you sure? | No Date')) def action_no_date(self, ids): self.set_on_sale_date(ids, None) class PublisherAdmin(AdministratorBase): def __init__(self, session): # Just call parent class with predefined model. super(PublisherAdmin, self).__init__(Publisher, session) form_excluded_columns = ('titles', 'comics') form_ajax_refs = { 'users': QueryAjaxModelLoader( 'users', db.session, User, fields=['email'], page_size=10), } class TitleAdmin(AdministratorBase): column_sortable_list= ('name', ('publisher', Publisher.name)) def __init__(self, session): # Just call parent class with predefined model. super(TitleAdmin, self).__init__(Title, session) form_ajax_refs = { 'users': QueryAjaxModelLoader( 'users', db.session, User, fields=['email'], page_size=10), 'issues': QueryAjaxModelLoader( 'issues', db.session, Issue, fields=['complete_title'], page_size=10), 'publisher': QueryAjaxModelLoader( 'publisher', db.session, Publisher, fields=['name'], page_size=10) } class CreatorAdmin(AdministratorBase): def __init__(self, session): # Just call parent class with predefined model. super(CreatorAdmin, self).__init__(Creator, session) form_excluded_columns = ('issues') class BundleAdmin(AdministratorBase): def __init__(self, session): # Just call parent class with predefined model. super(BundleAdmin, self).__init__(Bundle, session) form_ajax_refs = { 'issues': QueryAjaxModelLoader( 'issues', db.session, Issue, fields=['complete_title'], page_size=10), 'user': QueryAjaxModelLoader( 'user', db.session, User, fields=['email'], page_size=10) } class UserAdmin(SuperUserBase): column_list = ('email', 'last_seen', 'login_count', 'pull_list', 'roles') column_searchable_list = ('email',) form_excluded_columns = ('bundles',) form_ajax_refs = { 'pull_list': QueryAjaxModelLoader( 'pull_list', db.session, Title, fields=['name'], page_size=10) } def __init__(self, session): # Just call parent class with predefined model. super(UserAdmin, self).__init__(User, session) class RoleAdmin(SuperUserBase): def __init__(self, session): # Just call parent class with predefined model. super(RoleAdmin, self).__init__(Role, session) form_ajax_refs = { 'users': QueryAjaxModelLoader( 'users', db.session, User, fields=['email'], page_size=10) } class DiamondListAdmin(SuperUserBase): def __init__(self, session): super(DiamondListAdmin, self).__init__(DiamondList, session) form_ajax_refs = {'issues': QueryAjaxModelLoader('issues', db.session, Issue, fields=['complete_title'], page_size=10)} column_list = ('date_created', 'date', 'revision', 'hash_string',) form_ajax_refs = { 'issues': QueryAjaxModelLoader( 'issues', db.session, Issue, fields=['complete_title'], page_size=10), } def init_app(app): admin = Admin(app, index_view=LongboxedAdminIndexView()) admin.add_view(UserAdmin(db.session)) admin.add_view(IssueAdmin(db.session)) admin.add_view(PublisherAdmin(db.session)) admin.add_view(TitleAdmin(db.session)) admin.add_view(CreatorAdmin(db.session)) admin.add_view(RoleAdmin(db.session)) admin.add_view(BundleAdmin(db.session)) admin.add_view(DiamondListAdmin(db.session)) #!/usr/bin/env python import os import logging from aatest.check import State, OK from aatest.events import EV_CONDITION from aatest.result import Result, safe_path from aatest.verify import Verify from future.backports.urllib.parse import quote_plus from future.backports.urllib.parse import parse_qs from aatest.summation import store_test_state from aatest.session import SessionHandler, Done from saml2.httputil import BadRequest from saml2.httputil import get_post from saml2.httputil import Response from saml2test.idp_test.webio import WebIO from saml2test.idp_test.setup import setup from saml2test.idp_test.wb_tool import Tester SERVER_LOG_FOLDER = "server_log" if not os.path.isdir(SERVER_LOG_FOLDER): os.makedirs(SERVER_LOG_FOLDER) try: from mako.lookup import TemplateLookup except Exception as ex: raise ex LOGGER = logging.getLogger("") def pick_args(args, kwargs): return dict([(k, kwargs[k]) for k in args]) def do_next(tester, resp, sh, webio, filename, path): tester.conv = tester.sh['conv'] tester.handle_response(resp, {}) store_test_state(sh, sh['conv'].events) tester.webio.store_test_info() tester.conv.index += 1 lix = len(tester.conv.sequence) while tester.conv.sequence[tester.conv.index] != Done: resp = tester.run_flow(tester.conv.test_id, index=tester.conv.index) store_test_state(sh, sh['conv'].events) if isinstance(resp, Response): webio.print_info(path, filename) return resp if tester.conv.index >= lix: break if tester.conv.events.last_item(EV_CONDITION).test_id == 'Done': pass else: if 'assert' in tester.conv.flow: _ver = Verify(tester.chk_factory, tester.conv) _ver.test_sequence(tester.conv.flow["assert"]) tester.conv.events.store(EV_CONDITION, State('Done', status=OK)) store_test_state(sh, sh['conv'].events) tester.webio.store_test_info() return webio.flow_list(filename) class Application(object): def __init__(self, webenv): self.webenv = webenv def application(self, environ, start_response): LOGGER.info("Connection from: %s" % environ["REMOTE_ADDR"]) session = environ['beaker.session'] path = environ.get('PATH_INFO', '').lstrip('/') LOGGER.info("path: %s" % path) try: sh = session['session_info'] except KeyError: sh = SessionHandler(**self.webenv) sh.session_init() session['session_info'] = sh webio = WebIO(session=sh, **self.webenv) webio.environ = environ webio.start_response = start_response tester = Tester(webio, sh, **self.webenv) if path == "robots.txt": return webio.static("static/robots.txt") elif path == "favicon.ico": return webio.static("static/favicon.ico") elif path.startswith('acs/site/static'): path = path[4:] return webio.static(path) elif path.startswith("site/static/") or path.startswith('static/'): return webio.static(path) elif path.startswith("export/"): return webio.static(path) if path == "" or path == "/": # list return tester.display_test_list() elif "flow_names" not in sh: sh.session_init() if path == "logs": return webio.display_log("log", issuer="", profile="", testid="") elif path.startswith("log"): if path == "log" or path == "log/": _cc = webio.conf.CLIENT try: _iss = _cc["srv_discovery_url"] except KeyError: _iss = _cc["provider_info"]["issuer"] parts = [quote_plus(_iss)] else: parts = [] while path != "log": head, tail = os.path.split(path) # tail = tail.replace(":", "%3A") # if tail.endswith("%2F"): # tail = tail[:-3] parts.insert(0, tail) path = head return webio.display_log("log", *parts) elif path.startswith("tar"): path = path.replace(":", "%3A") return webio.static(path) elif path.startswith("test_info"): p = path.split("/") try: return webio.test_info(p[1]) except KeyError: return webio.not_found() elif path == "continue": return tester.cont(environ, self.webenv) elif path == 'reset': for param in ['flow', 'flow_names', 'index', 'node', 'profile', 'sequence', 'test_info', 'test_id', 'tests']: del sh[param] return tester.display_test_list() elif path == "opresult": if tester.conv is None: return webio.sorry_response("", "No result to report") return webio.opresult(tester.conv, sh) # expected path format: /[/] elif path in sh["flow_names"]: resp = tester.run(path, **self.webenv) store_test_state(sh, sh['conv'].events) filename = self.webenv['profile_handler'](sh).log_path(path) if isinstance(resp, Response): res = Result(sh, self.webenv['profile_handler']) res.store_test_info() res.print_info(path, tester.fname(path)) return webio.respond(resp) else: return webio.flow_list(filename) elif path == "acs/post": qs = get_post(environ).decode('utf8') resp = dict([(k, v[0]) for k, v in parse_qs(qs).items()]) filename = self.webenv['profile_handler'](sh).log_path(tester.conv.test_id) return do_next(tester, resp, sh, webio, filename, path) elif path == "acs/redirect": qs = environ['QUERY_STRING'] resp = dict([(k, v[0]) for k, v in parse_qs(qs).items()]) filename = self.webenv['profile_handler'](sh).log_path(tester.conv.test_id) return do_next(tester, resp, sh, webio, filename, path) elif path == "acs/artifact": pass elif path == "ecp": pass elif path == "disco": pass elif path == "slo": pass else: resp = BadRequest() return resp(environ, start_response) if __name__ == '__main__': from beaker.middleware import SessionMiddleware from cherrypy import wsgiserver from mako.lookup import TemplateLookup cargs, kwargs = setup('wb') session_opts = { 'session.type': 'memory', 'session.cookie_expires': True, 'session.auto': True, 'session.timeout': 900 } LOOKUP = TemplateLookup(directories=['./' + 'templates', './' + 'htdocs'], module_directory='./' + 'modules', input_encoding='utf-8', output_encoding='utf-8') kwargs['lookup'] = LOOKUP _conf = kwargs['conf'] _app = Application(webenv=kwargs) SRV = wsgiserver.CherryPyWSGIServer(('0.0.0.0', _conf.PORT), SessionMiddleware(_app.application, session_opts)) if _conf.BASE.startswith("https"): from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter SRV.ssl_adapter = BuiltinSSLAdapter(_conf.SERVER_CERT, _conf.SERVER_KEY, _conf.CERT_CHAIN) extra = " using SSL/TLS" else: extra = "" txt = "SP listening on port:%s%s" % (_conf.PORT, extra) LOGGER.info(txt) print(txt) try: SRV.start() except KeyboardInterrupt: SRV.stop() """Helper functions which doesn't fit anywhere else""" import re import hashlib from importlib import import_module from pkgutil import iter_modules from w3lib.html import remove_entities from scrapy.utils.python import flatten from scrapy.item import BaseItem def arg_to_iter(arg): """Convert an argument to an iterable. The argument can be a None, single value, or an iterable. Exception: if arg is a dict, [arg] will be returned """ if arg is None: return [] elif not isinstance(arg, (dict, BaseItem)) and hasattr(arg, '__iter__'): return arg else: return [arg] def load_object(path): """Load an object given its absolute object path, and return it. object can be a class, function, variable o instance. path ie: 'scrapy.contrib.downloadermiddelware.redirect.RedirectMiddleware' """ try: dot = path.rindex('.') except ValueError: raise ValueError("Error loading object '%s': not a full path" % path) module, name = path[:dot], path[dot+1:] try: mod = import_module(module) except ImportError as e: raise ImportError("Error loading object '%s': %s" % (path, e)) try: obj = getattr(mod, name) except AttributeError: raise NameError("Module '%s' doesn't define any object named '%s'" % (module, name)) return obj def walk_modules(path, load=False): """Loads a module and all its submodules from a the given module path and returns them. If *any* module throws an exception while importing, that exception is thrown back. For example: walk_modules('scrapy.utils') """ mods = [] mod = import_module(path) mods.append(mod) if hasattr(mod, '__path__'): for _, subpath, ispkg in iter_modules(mod.__path__): fullpath = path + '.' + subpath if ispkg: mods += walk_modules(fullpath) else: submod = import_module(fullpath) mods.append(submod) return mods def extract_regex(regex, text, encoding='utf-8'): """Extract a list of unicode strings from the given text/encoding using the following policies: * if the regex contains a named group called "extract" that will be returned * if the regex contains multiple numbered groups, all those will be returned (flattened) * if the regex doesn't contain any group the entire regex matching is returned """ if isinstance(regex, basestring): regex = re.compile(regex, re.UNICODE) try: strings = [regex.search(text).group('extract')] # named group except: strings = regex.findall(text) # full regex or numbered groups strings = flatten(strings) if isinstance(text, unicode): return [remove_entities(s, keep=['lt', 'amp']) for s in strings] else: return [remove_entities(unicode(s, encoding), keep=['lt', 'amp']) for s in strings] def md5sum(file): """Calculate the md5 checksum of a file-like object without reading its whole content in memory. >>> from StringIO import StringIO >>> md5sum(StringIO('file content to hash')) '784406af91dd5a54fbb9c84c2236595a' """ m = hashlib.md5() while 1: d = file.read(8096) if not d: break m.update(d) return m.hexdigest() """Constants for the ozw integration.""" from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN from homeassistant.components.cover import DOMAIN as COVER_DOMAIN from homeassistant.components.fan import DOMAIN as FAN_DOMAIN from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN from homeassistant.components.lock import DOMAIN as LOCK_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN DOMAIN = "ozw" DATA_UNSUBSCRIBE = "unsubscribe" CONF_INTEGRATION_CREATED_ADDON = "integration_created_addon" CONF_USE_ADDON = "use_addon" PLATFORMS = [ BINARY_SENSOR_DOMAIN, COVER_DOMAIN, CLIMATE_DOMAIN, FAN_DOMAIN, LIGHT_DOMAIN, LOCK_DOMAIN, SENSOR_DOMAIN, SWITCH_DOMAIN, ] MANAGER = "manager" NODES_VALUES = "nodes_values" # MQTT Topics TOPIC_OPENZWAVE = "OpenZWave" # Common Attributes ATTR_CONFIG_PARAMETER = "parameter" ATTR_CONFIG_VALUE = "value" ATTR_INSTANCE_ID = "instance_id" ATTR_SECURE = "secure" ATTR_NODE_ID = "node_id" ATTR_SCENE_ID = "scene_id" ATTR_SCENE_LABEL = "scene_label" ATTR_SCENE_VALUE_ID = "scene_value_id" ATTR_SCENE_VALUE_LABEL = "scene_value_label" # Config entry data and options MIGRATED = "migrated" # Service specific SERVICE_ADD_NODE = "add_node" SERVICE_REMOVE_NODE = "remove_node" SERVICE_CANCEL_COMMAND = "cancel_command" SERVICE_SET_CONFIG_PARAMETER = "set_config_parameter" # Home Assistant Events EVENT_SCENE_ACTIVATED = f"{DOMAIN}.scene_activated" # Signals SIGNAL_DELETE_ENTITY = f"{DOMAIN}_delete_entity" # Discovery Information DISC_COMMAND_CLASS = "command_class" DISC_COMPONENT = "component" DISC_GENERIC_DEVICE_CLASS = "generic_device_class" DISC_GENRE = "genre" DISC_INDEX = "index" DISC_INSTANCE = "instance" DISC_NODE_ID = "node_id" DISC_OPTIONAL = "optional" DISC_PRIMARY = "primary" DISC_SPECIFIC_DEVICE_CLASS = "specific_device_class" DISC_TYPE = "type" DISC_VALUES = "values" #!/usr/bin/python # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see . # This is a DOCUMENTATION stub specific to this module, it extends # a documentation fragment located in ansible.utils.module_docs_fragments ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: rax_identity short_description: Load Rackspace Cloud Identity description: - Verifies Rackspace Cloud credentials and returns identity information version_added: "1.5" options: state: description: - Indicate desired state of the resource choices: ['present', 'absent'] default: present required: false author: - "Christopher H. Laco (@claco)" - "Matt Martz (@sivel)" extends_documentation_fragment: rackspace.openstack ''' EXAMPLES = ''' - name: Load Rackspace Cloud Identity gather_facts: False hosts: local connection: local tasks: - name: Load Identity local_action: module: rax_identity credentials: ~/.raxpub region: DFW register: rackspace_identity ''' try: import pyrax HAS_PYRAX = True except ImportError: HAS_PYRAX = False def cloud_identity(module, state, identity): instance = dict( authenticated=identity.authenticated, credentials=identity._creds_file ) changed = False instance.update(rax_to_dict(identity)) instance['services'] = instance.get('services', {}).keys() if state == 'present': if not identity.authenticated: module.fail_json(msg='Credentials could not be verified!') module.exit_json(changed=changed, identity=instance) def main(): argument_spec = rax_argument_spec() argument_spec.update( dict( state=dict(default='present', choices=['present']) ) ) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together() ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') state = module.params.get('state') setup_rax_module(module, pyrax) if not pyrax.identity: module.fail_json(msg='Failed to instantiate client. This ' 'typically indicates an invalid region or an ' 'incorrectly capitalized region name.') cloud_identity(module, state, pyrax.identity) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.rax import * # invoke the module if __name__ == '__main__': main() # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest import unicodedata import epitran class TestBengaliGeneral(unittest.TestCase): def setUp(self): self.epi = epitran.Epitran(u'ben-Beng') def _assert_trans(self, src, tar): trans = self.epi.transliterate(src) trans = unicodedata.normalize('NFD', trans) src = unicodedata.normalize('NFD', trans) # print('{}\t{}\t{}'.format(trans, tar, zip(trans, tar))) self.assertEqual(trans, tar) def test_somosto(self): self._assert_trans('সমস্ত', 's̪ɔmɔs̪t̪ɔ') def test_manush(self): self._assert_trans('মানুষ', 'man̪uʂ') def test_sbadinbabe(self): self._assert_trans('স্বাধীনভাবে', 's̪bad̪̤in̪b̤abe') def test_shoman(self): self._assert_trans('সমান', 's̪ɔman̪') def test_morjada(self): self._assert_trans('মর্যাদা', 'mɔrd͡zad̪a') def test_ebong(self): self._assert_trans('এবং', 'ebɔŋ') def test_odikar(self): self._assert_trans('অধিকার', 'od̪̤ikar') def test_niye(self): self._assert_trans('নিয়ে', 'n̪ie̯e') # -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## from openerp.osv import fields, osv from openerp import tools from openerp.addons.crm import crm MONTHS = [ ('01', 'January'), ('02', 'February'), ('03', 'March'), ('04', 'April'), ('05', 'May'), ('06', 'June'), ('07', 'July'), ('08', 'August'), ('09', 'September'), ('10', 'October'), ('11', 'November'), ('12', 'December') ] class crm_lead_report(osv.osv): """ CRM Lead Analysis """ _name = "crm.lead.report" _auto = False _description = "CRM Lead Analysis" _rec_name = 'date_deadline' _columns = { 'date_deadline': fields.date('Exp. Closing', size=10, readonly=True, help="Expected Closing"), 'create_date': fields.datetime('Creation Date', readonly=True), 'opening_date': fields.date('Assignation Date', readonly=True), 'date_closed': fields.date('Close Date', readonly=True), 'date_last_stage_update': fields.datetime('Last Stage Update', readonly=True), # durations 'delay_open': fields.float('Delay to Assign',digits=(16,2),readonly=True, group_operator="avg",help="Number of Days to open the case"), 'delay_close': fields.float('Delay to Close',digits=(16,2),readonly=True, group_operator="avg",help="Number of Days to close the case"), 'delay_expected': fields.float('Overpassed Deadline',digits=(16,2),readonly=True, group_operator="avg"), 'user_id':fields.many2one('res.users', 'User', readonly=True), 'country_id':fields.many2one('res.country', 'Country', readonly=True), 'section_id':fields.many2one('crm.case.section', 'Sales Team', readonly=True), 'channel_id':fields.many2one('crm.case.channel', 'Channel', readonly=True), 'type_id':fields.many2one('crm.case.resource.type', 'Campaign', readonly=True), 'company_id': fields.many2one('res.company', 'Company', readonly=True), 'probability': fields.float('Probability',digits=(16,2),readonly=True, group_operator="avg"), 'planned_revenue': fields.float('Planned Revenue',digits=(16,2),readonly=True), 'probable_revenue': fields.float('Probable Revenue', digits=(16,2),readonly=True), 'stage_id': fields.many2one ('crm.case.stage', 'Stage', readonly=True, domain="[('section_ids', '=', section_id)]"), 'partner_id': fields.many2one('res.partner', 'Partner' , readonly=True), 'company_id': fields.many2one('res.company', 'Company', readonly=True), 'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'), 'type':fields.selection([ ('lead','Lead'), ('opportunity','Opportunity'), ],'Type', help="Type is used to separate Leads and Opportunities"), } def init(self, cr): """ CRM Lead Report @param cr: the current row, from the database cursor """ tools.drop_view_if_exists(cr, 'crm_lead_report') cr.execute(""" CREATE OR REPLACE VIEW crm_lead_report AS ( SELECT id, c.date_deadline, to_char(c.date_open, 'YYYY-MM-DD') as opening_date, to_char(c.date_closed, 'YYYY-mm-dd') as date_closed, date_trunc('day',c.date_last_stage_update) as date_last_stage_update, c.user_id, c.probability, c.stage_id, c.type, c.company_id, c.priority, c.section_id, c.channel_id, c.type_id, c.partner_id, c.country_id, c.planned_revenue, c.planned_revenue*(c.probability/100) as probable_revenue, date_trunc('day',c.create_date) as create_date, extract('epoch' from (c.date_closed-c.create_date))/(3600*24) as delay_close, abs(extract('epoch' from (c.date_deadline - c.date_closed))/(3600*24)) as delay_expected, extract('epoch' from (c.date_open-c.create_date))/(3600*24) as delay_open FROM crm_lead c WHERE c.active = 'true' )""") # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: # 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 django.core.urlresolvers import reverse from django import http from mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.test import helpers as test INDEX_URL = reverse( 'horizon:project:data_processing.data_image_registry:index') REGISTER_URL = reverse( 'horizon:project:data_processing.data_image_registry:register') class DataProcessingImageRegistryTests(test.TestCase): @test.create_stubs({api.sahara: ('image_list',)}) def test_index(self): api.sahara.image_list(IsA(http.HttpRequest)) \ .AndReturn(self.images.list()) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed( res, 'project/data_processing.data_image_registry/image_registry.html') self.assertContains(res, 'Image Registry') self.assertContains(res, 'Image') self.assertContains(res, 'Tags') @test.create_stubs({api.sahara: ('image_update', 'image_tags_update', 'image_list'), api.glance: ('image_list_detailed',)}) def test_register(self): image_id = self.images.first().id test_username = 'myusername' test_description = 'mydescription' api.glance.image_list_detailed(IsA(http.HttpRequest), filters={'owner': self.user.id, 'status': 'active'}) \ .AndReturn((self.images.list(), False, False)) api.sahara.image_update(IsA(http.HttpRequest), image_id, test_username, test_description) \ .AndReturn(True) api.sahara.image_tags_update(IsA(http.HttpRequest), image_id, {}) \ .AndReturn(True) api.sahara.image_list(IsA(http.HttpRequest)) \ .AndReturn([]) self.mox.ReplayAll() res = self.client.post( REGISTER_URL, {'image_id': image_id, 'user_name': test_username, 'description': test_description, 'tags_list': '{}'}) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) self.assertMessageCount(success=1) @test.create_stubs({api.sahara: ('image_list', 'image_unregister')}) def test_unregister(self): image = self.images.first() api.sahara.image_list(IsA(http.HttpRequest)) \ .AndReturn(self.images.list()) api.sahara.image_unregister(IsA(http.HttpRequest), image.id) self.mox.ReplayAll() form_data = {'action': 'image_registry__delete__%s' % image.id} res = self.client.post(INDEX_URL, form_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) self.assertMessageCount(success=1) @test.create_stubs({api.sahara: ('image_get', 'image_update', 'image_tags_update')}) def test_edit_tags(self): image = self.registered_images.first() api.sahara.image_get(IsA(http.HttpRequest), image.id) \ .AndReturn(image) api.sahara.image_update(IsA(http.HttpRequest), image.id, image.username, image.description) \ .AndReturn(True) api.sahara.image_tags_update(IsA(http.HttpRequest), image.id, {"0": "mytag"}) \ .AndReturn(True) self.mox.ReplayAll() edit_tags_url = reverse( 'horizon:project:data_processing.data_image_registry:edit_tags', args=[image.id]) res = self.client.post( edit_tags_url, {'image_id': image.id, 'user_name': image.username, 'description': image.description, 'tags_list': '{"0": "mytag"}'}) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) self.assertMessageCount(success=1) """ Django settings for k666 project. Generated by 'django-admin startproject' using Django 1.8.3. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^_bk5wj9el+un48)*jyeva_482cky7ap1p)djrk6a8qr7v()@$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ['DEBUG'] ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'comments', 'freek666', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django_messages', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'k666.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', ], }, }, ] WSGI_APPLICATION = 'k666.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASE_CHOICES = { 'sqlite3': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'postgresql': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'postgres', # 'PORT': '5432', } } DATABASES = { 'default': DATABASE_CHOICES[os.environ['DEFAULT_DATABASE']], } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' SITE_ID = 1 LOGIN_REDIRECT_URL = '/' AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) if DEBUG: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #@+leo-ver=4-thin #@+node:Zoomq.20051028115650:@thin dict4ini.py #@verbatim #@ignore #@verbatim #@language python #@<< dict4ini declarations >> #@+node:Zoomq.20051028115650.1:<< dict4ini declarations >> #coding=utf-8 # dump python dict to ini format file # Author: limodou (limodou@gmail.com) # Copyleft GPL # $Revision$ # you can see http://wiki.woodpecker.org.cn/moin/Dict4Ini for more details # # Updates: # 2005/10/16 # Saving the order of the items # Adding float format # __version__ = '0.2' import sys import locale import os.path import re r_float = re.compile('\d*\.\d+') section_delimeter = '/' #@-node:Zoomq.20051028115650.1:<< dict4ini declarations >> #@nl #@+others #@+node:Zoomq.20051028115650.3:class DictNode class DictNode(object): #@ @+others #@+node:Zoomq.20051028115650.4:__init__ def __init__(self, values, encoding=None, root=None, section=[], orders=[]): self._items = values self._orders = orders self._encoding = encoding self._root = root self._section = section #@-node:Zoomq.20051028115650.4:__init__ #@+node:Zoomq.20051028115650.5:__getitem__ def __getitem__(self, name): if self._items.has_key(name): value = self._items[name] if isinstance(value, dict): return DictNode(value, self._encoding, self._root, self._section + [name]) else: return value else: self._items[name] = {} self._root.setorder(self.get_full_keyname(name)) return DictNode(self._items[name], self._encoding, self._root, self._section + [name]) #@-node:Zoomq.20051028115650.5:__getitem__ #@+node:Zoomq.20051028115650.6:__setitem__ def __setitem__(self, name, value): if section_delimeter in name: sec = name.split(section_delimeter) obj = self._items _s = self._section[:] for i in sec[:-1]: _s.append(i) if obj.has_key(i): if isinstance(obj[i], dict): obj = obj[i] else: obj[i] = {} #may lost some data obj = obj[i] else: obj[i] = {} self._root.setorder(section_delimeter.join(_s)) obj = obj[i] obj[sec[-1]] = value self._root.setorder(section_delimeter.join(_s + [sec[-1]])) else: self._items[name] = value self._root.setorder(self.get_full_keyname(name)) #@-node:Zoomq.20051028115650.6:__setitem__ #@+node:Zoomq.20051028115650.7:__delitem__ def __delitem__(self, name): if self._items.has_key(name): del self._items[name] #@-node:Zoomq.20051028115650.7:__delitem__ #@+node:Zoomq.20051028115650.8:__repr__ def __repr__(self): return repr(self._items) #@-node:Zoomq.20051028115650.8:__repr__ #@+node:Zoomq.20051028115650.9:__getattr__ def __getattr__(self, name): return self.__getitem__(name) #@-node:Zoomq.20051028115650.9:__getattr__ #@+node:Zoomq.20051028115650.10:__setattr__ def __setattr__(self, name, value): if name.startswith('_'): if name == '_comment': self._root._comments[section_delimeter.join(self._section)] = value else: self.__dict__[name] = value else: self.__setitem__(name, value) #@-node:Zoomq.20051028115650.10:__setattr__ #@+node:Zoomq.20051028115650.11:comment def comment(self, name, comment): if name: self._root._comments[section_delimeter.join(self._section + [name])] = comment else: self._root._comments[section_delimeter.join(self._section)] = comment #@-node:Zoomq.20051028115650.11:comment #@+node:Zoomq.20051028115650.12:__delattr__ def __delattr__(self, name): if self._items.has_key(name): del self._items[name] #@-node:Zoomq.20051028115650.12:__delattr__ #@+node:Zoomq.20051028115650.13:__str__ def __str__(self): return repr(self._items) #@-node:Zoomq.20051028115650.13:__str__ #@+node:Zoomq.20051028115650.14:__len__ def __len__(self): return len(self._items) #@-node:Zoomq.20051028115650.14:__len__ #@+node:Zoomq.20051028115650.15:has_key def has_key(self, name): return self._items.has_key(name) #@-node:Zoomq.20051028115650.15:has_key #@+node:Zoomq.20051028115650.16:items def items(self): return self._items.items() #@-node:Zoomq.20051028115650.16:items #@+node:Zoomq.20051028115650.17:setdefault def setdefault(self, name, value): return self._items.setdefault(name, value) #@-node:Zoomq.20051028115650.17:setdefault #@+node:Zoomq.20051028115650.18:get def get(self, name, default=None): return self._items.get(name, default) #@-node:Zoomq.20051028115650.18:get #@+node:Zoomq.20051028115650.19:keys def keys(self): return self._items.keys() #@-node:Zoomq.20051028115650.19:keys #@+node:Zoomq.20051028115650.20:values def values(self): return self._items.values() #@-node:Zoomq.20051028115650.20:values #@+node:Zoomq.20051028115650.21:get_full_keyname def get_full_keyname(self, key): return section_delimeter.join(self._section + [key]) #@-node:Zoomq.20051028115650.21:get_full_keyname #@-others #@-node:Zoomq.20051028115650.3:class DictNode #@+node:Zoomq.20051028115650.22:class DictIni class DictIni(DictNode): #@ @+others #@+node:Zoomq.20051028115650.23:__init__ def __init__(self, inifile=None, values=None, encoding=None, commentdelimeter='#'): self._items = {} self._inifile = inifile self._root = self self._section = [] self._commentdelimeter = commentdelimeter if values is not None: self._items = values self._comments = {} self._orders = {} self._ID = 1 self._encoding = getdefaultencoding(encoding) if self._inifile and os.path.exists(self._inifile): self.read(self._inifile, self._encoding) #@-node:Zoomq.20051028115650.23:__init__ #@+node:Zoomq.20051028115650.24:setfilename def setfilename(self, filename): self._inifile = filename #@-node:Zoomq.20051028115650.24:setfilename #@+node:Zoomq.20051028115650.25:getfilename def getfilename(self): return self._inifile #@-node:Zoomq.20051028115650.25:getfilename #@+node:Zoomq.20051028115650.26:save def save(self, inifile=None, encoding=None): if inifile is None: inifile = self._inifile if isinstance(inifile, (str, unicode)): f = file(inifile, 'w') elif isinstance(inifile, file): f = inifile else: f = inifile if not f: f = sys.stdout if encoding is None: encoding = self._encoding f.write(self._savedict([], self._items, encoding)) if isinstance(inifile, (str, unicode)): f.close() #@-node:Zoomq.20051028115650.26:save #@+node:Zoomq.20051028115650.27:_savedict def _savedict(self, section, values, encoding): if values: buf = [] default = [] for key, value in self._getorderitems(values.items()): if isinstance(value, dict): sec = section[:] sec.append(key) buf.append(self._savedict(sec, value, encoding)) else: c = self._comments.get(section_delimeter.join(section + [key]), '') if c: lines = c.splitlines() default.append('\n'.join(['%s %s' % (self._commentdelimeter, x) for x in lines])) default.append("%s = %s" % (key, uni_prt(value, encoding))) if default: buf.insert(0, '\n'.join(default)) buf.insert(0, '[%s]' % section_delimeter.join(section)) c = self._comments.get(section_delimeter.join(section), '') if c: lines = c.splitlines() buf.insert(0, '\n'.join(['%s %s' % (self._commentdelimeter, x) for x in lines])) return '\n'.join(buf + ['']) else: return '' #@-node:Zoomq.20051028115650.27:_savedict #@+node:Zoomq.20051028115650.28:read def read(self, inifile=None, encoding=None): if inifile is None: inifile = self._inifile if isinstance(inifile, (str, unicode)): try: f = file(inifile, 'r') except: return #may raise Exception is better elif isinstance(inifile, file): f = inifile else: f = inifile if not f: f = sys.stdin if encoding is None: encoding = self._encoding comments = [] section = '' for line in f.readlines(): line = line.strip() if not line: continue if line.startswith(self._commentdelimeter): comments.append(line[1:].lstrip()) continue if line.startswith('['): #section section = line[1:-1] #if comment then set it if comments: self.comment(section, '\n'.join(comments)) comments = [] continue key, value = line.split('=', 1) key = key.strip() value = process_value(value.strip(), encoding) if section: self.__setitem__(section + section_delimeter + key, value) #if comment then set it if comments: self.__getitem__(section).comment(key, '\n'.join(comments)) comments = [] else: self.__setitem__(key, value) #if comment then set it if comments: self.comment(key, '\n'.join(comments)) comments = [] if isinstance(inifile, (str, unicode)): f.close() #@-node:Zoomq.20051028115650.28:read #@+node:Zoomq.20051028115650.29:setorder def setorder(self, key): if not self._orders.has_key(key): self._orders[key] = self._ID self._ID += 1 #@-node:Zoomq.20051028115650.29:setorder #@+node:Zoomq.20051028115650.30:_getorderitems def _getorderitems(self, values): s = [] for key, value in values: s.append((self._orders.get(key, 99999), key, value)) s.sort() return [(x, y) for z, x, y in s] #@-node:Zoomq.20051028115650.30:_getorderitems #@-others #@-node:Zoomq.20051028115650.22:class DictIni #@+node:Zoomq.20051028115650.31:process_value def process_value(value, encoding=None): length = len(value) t = value i = 0 r = [] buf = [] listflag = False while i < length: if t[i] == '"': #string quote buf.append(t[i]) i += 1 while t[i] != '"' or (t[i] == '"' and t[i-1] == '\\'): buf.append(t[i]) i += 1 buf.append(t[i]) i += 1 elif t[i] == ',': r.append(''.join(buf)) buf = [] i += 1 listflag = True elif t[i] == 'u': buf.append(t[i]) i += 1 else: buf.append(t[i]) i += 1 while i < length and t[i] != ',': buf.append(t[i]) i += 1 if buf: r.append(''.join(buf)) result = [] for i in r: if i.isdigit(): result.append(int(i)) elif i and i.startswith('u"'): result.append(unicode(unescstr(i[1:]), encoding)) else: b = r_float.match(i) if b: result.append(float(b.group())) else: result.append(unescstr(i)) if listflag: return result elif result: return result[0] else: return '' #@-node:Zoomq.20051028115650.31:process_value #@+node:Zoomq.20051028115650.32:unescstr def unescstr(value): if value.startswith('"') and value.endswith('"'): value = value[1:-1] escapechars = [("\\", "\\\\"), ("'", r"\'"), ('\"', r'\"'), ('\b', r'\b'), ('\t', r"\t"), ('\r', r"\r"), ('\n', r"\n")] for item in escapechars: k, v = item value = value.replace(v, k) return value #@-node:Zoomq.20051028115650.32:unescstr #@+node:Zoomq.20051028115650.33:getdefaultencoding def getdefaultencoding(encoding): if not encoding: encoding = locale.getdefaultlocale()[1] if not encoding: encoding = sys.getfilesystemencoding() if not encoding: encoding = 'utf-8' return encoding #@-node:Zoomq.20051028115650.33:getdefaultencoding #@+node:Zoomq.20051028115650.34:uni_prt def uni_prt(a, encoding=None): escapechars = [("\\", "\\\\"), ("'", r"\'"), ('\"', r'\"'), ('\b', r'\b'), ('\t', r"\t"), ('\r', r"\r"), ('\n', r"\n")] s = [] if isinstance(a, (list, tuple)): for i, k in enumerate(a): s.append(uni_prt(k, encoding)) s.append(',') elif isinstance(a, str): t = a for i in escapechars: t = t.replace(i[0], i[1]) if ' ' in t or ',' in t or t.isdigit(): s.append('"%s"' % t) else: s.append("%s" % t) elif isinstance(a, unicode): t = a for i in escapechars: t = t.replace(i[0], i[1]) s.append('u"%s"' % t.encode(encoding)) else: s.append(str(a)) return ''.join(s) #@-node:Zoomq.20051028115650.34:uni_prt #@-others if __name__ == '__main__': #@ << try >> #@+node:Zoomq.20051028115650.2:<< try >> d = DictIni('test.ini') # d._comment = 'Test\nTest2' # d.a = 'b' # d['b'] = 3 # d.c.d = (1,2,'b asf aaa') # d['s']['t'] = u'涓�浗' # d['s'].a = 1 # d['m/m'] = 'testing' # d.t.m.p = '3' print d # d.setfilename('test.ini') # d.t.m.comment('p', 'PTesting') # print d.getfilename() # print '---------------------' # # d.save('test.ini') # # a = process_value('1,abc,"aa cc",," ,\\"sdf",u"aaa"', 'ascii') # print a # print uni_prt(a, 'utf-8') # # t = DictIni(inifile='test.ini') # print t # # t.setfilename('test1.ini') # t.save() # t.setfilename('test2.ini') # t.save() #@-node:Zoomq.20051028115650.2:<< try >> #@nl #@nonl #@-node:Zoomq.20051028115650:@thin dict4ini.py #@-leo # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt import webnotes import webnotes.model from webnotes.model.doc import Document from webnotes import _ class DocList(list): """DocList object as a wrapper around a list""" def get(self, filters, limit=0): """pass filters as: {"key": "val", "key": ["!=", "val"], "key": ["in", "val"], "key": ["not in", "val"], "key": "^val", "key" : True (exists), "key": False (does not exist) }""" out = [] for doc in self: d = isinstance(getattr(doc, "fields", None), dict) and doc.fields or doc add = True for f in filters: fval = filters[f] if fval is True: fval = ["not None", fval] elif fval is False: fval = ["None", fval] elif not isinstance(fval, list): if isinstance(fval, basestring) and fval.startswith("^"): fval = ["^", fval[1:]] else: fval = ["=", fval] if not webnotes.compare(d.get(f), fval[0], fval[1]): add = False break if add: out.append(doc) if limit and (len(out)-1)==limit: break return DocList(out) def get_distinct_values(self, fieldname): return filter(None, list(set(map(lambda d: d.fields.get(fieldname), self)))) def remove_items(self, filters): for d in self.get(filters): self.remove(d) def getone(self, filters): return self.get(filters, limit=1)[0] def copy(self): out = [] for d in self: if isinstance(d, dict): fielddata = d else: fielddata = d.fields fielddata.update({"name": None}) out.append(Document(fielddata=fielddata)) return DocList(out) def get_item_value(self, d, name): if isinstance(d, dict): return d.get(name) else: return d.fields.get(name) def filter_valid_fields(self): import webnotes.model fieldnames = {} for d in self: remove = [] for f in d: if f not in fieldnames.setdefault(d.doctype, webnotes.model.get_fieldnames(d.doctype)): remove.append(f) for f in remove: del d[f] def append(self, doc): if not isinstance(doc, Document): doc = Document(fielddata=doc) self._prepare_doc(doc) super(DocList, self).append(doc) def extend(self, doclist): doclist = objectify(doclist) for doc in doclist: self._prepare_doc(doc) super(DocList, self).extend(doclist) return self def _prepare_doc(self, doc): if not doc.name: doc.fields["__islocal"] = 1 doc.docstatus = 0 if doc.parentfield: if not doc.parenttype: doc.parenttype = self[0].doctype if not doc.parent: doc.parent = self[0].name if not doc.idx: siblings = [int(self.get_item_value(d, "idx") or 0) for d in self.get({"parentfield": doc.parentfield})] doc.idx = (max(siblings) + 1) if siblings else 1 def update(self, doclist): for i, d in enumerate(self): if d.get("parent") and d.get("name") not in [t.get("name") for t in doclist]: del self[i] for d in doclist: if not d["name"]: d["__islocal"] = 1 self.append(d) else: # child found_in_existing = False for ref in self: if d["name"] and ref.name and ref.name == d["name"]: ref.fields.update(d) found_in_existing = True break if not found_in_existing: d["__islocal"] = 1 d["name"] = None self.append(d) return self def objectify(doclist): from webnotes.model.doc import Document return map(lambda d: isinstance(d, Document) and d or Document(d), doclist) # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 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. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ Template file used by the OPF Experiment Generator to generate the actual description.py file by replacing $XXXXXXXX tokens with desired values. This description.py file was generated by: '/Users/ronmarianetti/nta/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py' """ from nupic.frameworks.opf.expdescriptionapi import ExperimentDescriptionAPI from nupic.frameworks.opf.expdescriptionhelpers import ( updateConfigFromSubConfig, applyValueGettersToContainer, DeferredDictLookup) from nupic.frameworks.opf.clamodelcallbacks import * from nupic.frameworks.opf.metrics import MetricSpec from nupic.frameworks.opf.opfutils import (InferenceType, InferenceElement) from nupic.support import aggregationDivide from nupic.frameworks.opf.opftaskdriver import ( IterationPhaseSpecLearnOnly, IterationPhaseSpecInferOnly, IterationPhaseSpecLearnAndInfer) # Model Configuration Dictionary: # # Define the model parameters and adjust for any modifications if imported # from a sub-experiment. # # These fields might be modified by a sub-experiment; this dict is passed # between the sub-experiment and base experiment # # # NOTE: Use of DEFERRED VALUE-GETTERs: dictionary fields and list elements # within the config dictionary may be assigned futures derived from the # ValueGetterBase class, such as DeferredDictLookup. # This facility is particularly handy for enabling substitution of values in # the config dictionary from other values in the config dictionary, which is # needed by permutation.py-based experiments. These values will be resolved # during the call to applyValueGettersToContainer(), # which we call after the base experiment's config dictionary is updated from # the sub-experiment. See ValueGetterBase and # DeferredDictLookup for more details about value-getters. # # For each custom encoder parameter to be exposed to the sub-experiment/ # permutation overrides, define a variable in this section, using key names # beginning with a single underscore character to avoid collisions with # pre-defined keys (e.g., _dsEncoderFieldName2_N). # # Example: # config = dict( # _dsEncoderFieldName2_N = 70, # _dsEncoderFieldName2_W = 5, # dsEncoderSchema = [ # base=dict( # fieldname='Name2', type='ScalarEncoder', # name='Name2', minval=0, maxval=270, clipInput=True, # n=DeferredDictLookup('_dsEncoderFieldName2_N'), # w=DeferredDictLookup('_dsEncoderFieldName2_W')), # ], # ) # updateConfigFromSubConfig(config) # applyValueGettersToContainer(config) config = { # Type of model that the rest of these parameters apply to. 'model': "CLA", # Version that specifies the format of the config. 'version': 1, # Intermediate variables used to compute fields in modelParams and also # referenced from the control section. 'aggregationInfo': { 'days': 0, 'fields': [], 'hours': 0, 'microseconds': 0, 'milliseconds': 0, 'minutes': 0, 'months': 0, 'seconds': 0, 'weeks': 0, 'years': 0}, 'predictAheadTime': None, # Model parameter dictionary. 'modelParams': { # The type of inference that this model will perform 'inferenceType': 'NontemporalClassification', 'sensorParams': { # Sensor diagnostic output verbosity control; # if > 0: sensor region will print out on screen what it's sensing # at each step 0: silent; >=1: some info; >=2: more info; # >=3: even more info (see compute() in py/regions/RecordSensor.py) 'verbosity' : 0, # Example: # dsEncoderSchema = [ # DeferredDictLookup('__field_name_encoder'), # ], # # (value generated from DS_ENCODER_SCHEMA) 'encoders': { u'A': { 'fieldname': u'daynight', 'n': 300, 'name': u'daynight', 'type': 'SDRCategoryEncoder', 'w': 21}, u'B': { 'fieldname': u'daynight', 'n': 300, 'name': u'daynight', 'type': 'SDRCategoryEncoder', 'w': 21}, u'C': { 'fieldname': u'precip', 'n': 300, 'name': u'precip', 'type': 'SDRCategoryEncoder', 'w': 21}, u'D': { 'clipInput': True, 'fieldname': u'visitor_winloss', 'maxval': 0.78600000000000003, 'minval': 0.0, 'n': 150, 'name': u'visitor_winloss', 'type': 'AdaptiveScalarEncoder', 'w': 21}, u'E': { 'clipInput': True, 'fieldname': u'home_winloss', 'maxval': 0.69999999999999996, 'minval': 0.0, 'n': 150, 'name': u'home_winloss', 'type': 'AdaptiveScalarEncoder', 'w': 21}, u'F': { 'dayOfWeek': (7, 1), 'fieldname': u'timestamp', 'name': u'timestamp_dayOfWeek', 'type': 'DateEncoder'}, u'G': { 'fieldname': u'timestamp', 'name': u'timestamp_timeOfDay', 'timeOfDay': (7, 1), 'type': 'DateEncoder'}, u'_classifierInput': { 'clipInput': True, 'fieldname': u'attendance', 'classifierOnly': True, 'maxval': 36067, 'minval': 0, 'n': 150, 'name': u'attendance', 'type': 'AdaptiveScalarEncoder', 'w': 21}}, # A dictionary specifying the period for automatically-generated # resets from a RecordSensor; # # None = disable automatically-generated resets (also disabled if # all of the specified values evaluate to 0). # Valid keys is the desired combination of the following: # days, hours, minutes, seconds, milliseconds, microseconds, weeks # # Example for 1.5 days: sensorAutoReset = dict(days=1,hours=12), # # (value generated from SENSOR_AUTO_RESET) 'sensorAutoReset' : None, }, 'spEnable': True, 'spParams': { # SP diagnostic output verbosity control; # 0: silent; >=1: some info; >=2: more info; 'spVerbosity' : 0, 'globalInhibition': 1, # Number of cell columns in the cortical region (same number for # SP and TP) # (see also tpNCellsPerCol) 'columnCount': 2048, 'inputWidth': 0, # SP inhibition control (absolute value); # Maximum number of active columns in the SP region's output (when # there are more, the weaker ones are suppressed) 'numActivePerInhArea': 40, 'seed': 1956, # coincInputPoolPct # What percent of the columns's receptive field is available # for potential synapses. At initialization time, we will # choose coincInputPoolPct * (2*coincInputRadius+1)^2 'coincInputPoolPct': 1.0, # The default connected threshold. Any synapse whose # permanence value is above the connected threshold is # a "connected synapse", meaning it can contribute to the # cell's firing. Typical value is 0.10. Cells whose activity # level before inhibition falls below minDutyCycleBeforeInh # will have their own internal synPermConnectedCell # threshold set below this default value. # (This concept applies to both SP and TP and so 'cells' # is correct here as opposed to 'columns') 'synPermConnected': 0.1, 'synPermActiveInc': 0.1, 'synPermInactiveDec': 0.01, }, # Controls whether TP is enabled or disabled; # TP is necessary for making temporal predictions, such as predicting # the next inputs. Without TP, the model is only capable of # reconstructing missing sensor inputs (via SP). 'tpEnable' : True, 'tpParams': { # TP diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity # (see verbosity in nta/trunk/py/nupic/research/TP.py and TP10X*.py) 'verbosity': 0, # Number of cell columns in the cortical region (same number for # SP and TP) # (see also tpNCellsPerCol) 'columnCount': 2048, # The number of cells (i.e., states), allocated per column. 'cellsPerColumn': 32, 'inputWidth': 2048, 'seed': 1960, # Temporal Pooler implementation selector (see _getTPClass in # CLARegion.py). 'temporalImp': 'cpp', # New Synapse formation count # NOTE: If None, use spNumActivePerInhArea # # TODO: need better explanation 'newSynapseCount': 15, # Maximum number of synapses per segment # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # # TODO: for Ron: once the appropriate value is placed in TP # constructor, see if we should eliminate this parameter from # description.py. 'maxSynapsesPerSegment': 32, # Maximum number of segments per cell # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # # TODO: for Ron: once the appropriate value is placed in TP # constructor, see if we should eliminate this parameter from # description.py. 'maxSegmentsPerCell': 128, # Initial Permanence # TODO: need better explanation 'initialPerm': 0.21, # Permanence Increment 'permanenceInc': 0.1, # Permanence Decrement # If set to None, will automatically default to tpPermanenceInc # value. 'permanenceDec' : 0.1, 'globalDecay': 0.0, 'maxAge': 0, # Minimum number of active synapses for a segment to be considered # during search for the best-matching segments. # None=use default # Replaces: tpMinThreshold 'minThreshold': 12, # Segment activation threshold. # A segment is active if it has >= tpSegmentActivationThreshold # connected synapses that are active due to infActiveState # None=use default # Replaces: tpActivationThreshold 'activationThreshold': 16, 'outputType': 'normal', # "Pay Attention Mode" length. This tells the TP how many new # elements to append to the end of a learned sequence at a time. # Smaller values are better for datasets with short sequences, # higher values are better for datasets with long sequences. 'pamLength': 1, }, 'clParams': { 'regionName' : 'CLAClassifierRegion', # Classifier diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity 'clVerbosity' : 0, # This controls how fast the classifier learns/forgets. Higher values # make it adapt faster and forget older patterns faster. 'alpha': 0.001, # This is set after the call to updateConfigFromSubConfig and is # computed from the aggregationInfo and predictAheadTime. 'steps': '1', }, 'trainSPNetOnlyIfRequested': False, }, } # end of config dictionary # Adjust base config dictionary for any modifications if imported from a # sub-experiment updateConfigFromSubConfig(config) # Compute predictionSteps based on the predictAheadTime and the aggregation # period, which may be permuted over. if config['predictAheadTime'] is not None: predictionSteps = int(round(aggregationDivide( config['predictAheadTime'], config['aggregationInfo']))) assert (predictionSteps >= 1) config['modelParams']['clParams']['steps'] = str(predictionSteps) # Adjust config by applying ValueGetterBase-derived # futures. NOTE: this MUST be called after updateConfigFromSubConfig() in order # to support value-getter-based substitutions from the sub-experiment (if any) applyValueGettersToContainer(config) ################################################################################ control = { # The environment that the current model is being run in "environment": 'nupic', # Input stream specification per py/nupicengine/cluster/database/StreamDef.json. # 'dataset' : { u'info': u'baseball benchmark test', u'streams': [ { u'columns': [ u'daynight', u'precip', u'home_winloss', u'visitor_winloss', u'attendance', u'timestamp'], u'info': u'OAK01.csv', u'source': u'file://extra/baseball_stadium/OAK01reformatted.csv'}], u'version': 1}, # Iteration count: maximum number of iterations. Each iteration corresponds # to one record from the (possibly aggregated) dataset. The task is # terminated when either number of iterations reaches iterationCount or # all records in the (possibly aggregated) database have been processed, # whichever occurs first. # # iterationCount of -1 = iterate over the entire dataset #'iterationCount' : ITERATION_COUNT, # Metrics: A list of MetricSpecs that instantiate the metrics that are # computed for this experiment 'metrics':[ MetricSpec(field=u'attendance', metric='multiStep', inferenceElement='multiStepBestPredictions', params={'window': 1000, 'steps': [0], 'errorMetric': 'aae'}), ], # Logged Metrics: A sequence of regular expressions that specify which of # the metrics from the Inference Specifications section MUST be logged for # every prediction. The regex's correspond to the automatically generated # metric labels. This is similar to the way the optimization metric is # specified in permutations.py. 'loggedMetrics': ['.*'], } ################################################################################ ################################################################################ descriptionInterface = ExperimentDescriptionAPI(modelConfig=config, control=control) ### # Copyright (c) 2004-2005, Jeremiah Fincher # 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 author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # 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. ### import supybot.conf as conf import supybot.registry as registry def configure(advanced): # This will be called by supybot to configure this module. advanced is # a bool that specifies whether the user identified himself as an advanced # user or not. You should effect your configuration by manipulating the # registry as appropriate. from supybot.questions import expect, anything, something, yn conf.registerPlugin('Misc', True) Misc = conf.registerPlugin('Misc') conf.registerGlobalValue(Misc, 'listPrivatePlugins', registry.Boolean(True, """Determines whether the bot will list private plugins with the list command if given the --private switch. If this is disabled, non-owner users should be unable to see what private plugins are loaded.""")) conf.registerGlobalValue(Misc, 'timestampFormat', registry.String('[%H:%M:%S]', """Determines the format string for timestamps in the Misc.last command. Refer to the Python documentation for the time module to see what formats are accepted. If you set this variable to the empty string, the timestamp will not be shown.""")) conf.registerGroup(Misc, 'last') conf.registerGroup(Misc.last, 'nested') conf.registerChannelValue(Misc.last.nested, 'includeTimestamp', registry.Boolean(False, """Determines whether or not the timestamp will be included in the output of last when it is part of a nested command""")) conf.registerChannelValue(Misc.last.nested, 'includeNick', registry.Boolean(False, """Determines whether or not the nick will be included in the output of last when it is part of a nested command""")) # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys from nose.plugins.skip import SkipTest if sys.version_info < (2, 7): raise SkipTest("F5 Ansible modules require Python >= 2.7") from ansible.compat.tests import unittest from ansible.compat.tests.mock import Mock from ansible.compat.tests.mock import patch from ansible.module_utils.basic import AnsibleModule try: from library.bigip_profile_client_ssl import ModuleParameters from library.bigip_profile_client_ssl import ApiParameters from library.bigip_profile_client_ssl import ModuleManager from library.bigip_profile_client_ssl import ArgumentSpec from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import iControlUnexpectedHTTPError from test.unit.modules.utils import set_module_args except ImportError: try: from ansible.modules.network.f5.bigip_profile_client_ssl import ModuleParameters from ansible.modules.network.f5.bigip_profile_client_ssl import ApiParameters from ansible.modules.network.f5.bigip_profile_client_ssl import ModuleManager from ansible.modules.network.f5.bigip_profile_client_ssl import ArgumentSpec from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError from units.modules.utils import set_module_args except ImportError: raise SkipTest("F5 Ansible modules require the f5-sdk Python library") fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except Exception: pass fixture_data[path] = data return data class TestParameters(unittest.TestCase): def test_module_parameters(self): args = dict( name='foo', parent='bar', ciphers='!SSLv3:!SSLv2:ECDHE+AES-GCM+SHA256:ECDHE-RSA-AES128-CBC-SHA', cert_key_chain=[ dict( cert='bigip_ssl_cert1', key='bigip_ssl_key1', chain='bigip_ssl_cert1' ) ] ) p = ModuleParameters(params=args) assert p.name == 'foo' assert p.parent == '/Common/bar' assert p.ciphers == '!SSLv3:!SSLv2:ECDHE+AES-GCM+SHA256:ECDHE-RSA-AES128-CBC-SHA' def test_api_parameters(self): args = load_fixture('load_ltm_profile_clientssl.json') p = ApiParameters(params=args) assert p.name == 'foo' assert p.ciphers == 'DEFAULT' class TestManager(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() def test_create(self, *args): # Configure the arguments that would be sent to the Ansible module set_module_args(dict( name='foo', parent='bar', ciphers='!SSLv3:!SSLv2:ECDHE+AES-GCM+SHA256:ECDHE-RSA-AES128-CBC-SHA', cert_key_chain=[ dict( cert='bigip_ssl_cert1', key='bigip_ssl_key1', chain='bigip_ssl_cert1' ) ], password='passsword', server='localhost', user='admin' )) module = AnsibleModule( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode ) mm = ModuleManager(module=module) # Override methods to force specific logic in the module to happen mm.exists = Mock(return_value=False) mm.create_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True """ This module defines export functions for decision trees. """ # Authors: Gilles Louppe # Peter Prettenhofer # Brian Holt # Noel Dawe # Satrajit Gosh # Trevor Stephens # Licence: BSD 3 clause import numpy as np from ..externals import six from . import _tree def _color_brew(n): """Generate n colors with equally spaced hues. Parameters ---------- n : int The number of colors required. Returns ------- color_list : list, length n List of n tuples of form (R, G, B) being the components of each color. """ color_list = [] # Initialize saturation & value; calculate chroma & value shift s, v = 0.75, 0.9 c = s * v m = v - c for h in np.arange(25, 385, 360. / n).astype(int): # Calculate some intermediate values h_bar = h / 60. x = c * (1 - abs((h_bar % 2) - 1)) # Initialize RGB with same hue & chroma as our color rgb = [(c, x, 0), (x, c, 0), (0, c, x), (0, x, c), (x, 0, c), (c, 0, x), (c, x, 0)] r, g, b = rgb[int(h_bar)] # Shift the initial RGB values to match value and store rgb = [(int(255 * (r + m))), (int(255 * (g + m))), (int(255 * (b + m)))] color_list.append(rgb) return color_list def export_graphviz(decision_tree, out_file="tree.dot", max_depth=None, feature_names=None, class_names=None, label='all', filled=False, leaves_parallel=False, impurity=True, node_ids=False, proportion=False, rotate=False, rounded=False, special_characters=False): """Export a decision tree in DOT format. This function generates a GraphViz representation of the decision tree, which is then written into `out_file`. Once exported, graphical renderings can be generated using, for example:: $ dot -Tps tree.dot -o tree.ps (PostScript format) $ dot -Tpng tree.dot -o tree.png (PNG format) The sample counts that are shown are weighted with any sample_weights that might be present. Read more in the :ref:`User Guide `. Parameters ---------- decision_tree : decision tree classifier The decision tree to be exported to GraphViz. out_file : file object or string, optional (default="tree.dot") Handle or name of the output file. max_depth : int, optional (default=None) The maximum depth of the representation. If None, the tree is fully generated. feature_names : list of strings, optional (default=None) Names of each of the features. class_names : list of strings, bool or None, optional (default=None) Names of each of the target classes in ascending numerical order. Only relevant for classification and not supported for multi-output. If ``True``, shows a symbolic representation of the class name. label : {'all', 'root', 'none'}, optional (default='all') Whether to show informative labels for impurity, etc. Options include 'all' to show at every node, 'root' to show only at the top root node, or 'none' to not show at any node. filled : bool, optional (default=False) When set to ``True``, paint nodes to indicate majority class for classification, extremity of values for regression, or purity of node for multi-output. leaves_parallel : bool, optional (default=False) When set to ``True``, draw all leaf nodes at the bottom of the tree. impurity : bool, optional (default=True) When set to ``True``, show the impurity at each node. node_ids : bool, optional (default=False) When set to ``True``, show the ID number on each node. proportion : bool, optional (default=False) When set to ``True``, change the display of 'values' and/or 'samples' to be proportions and percentages respectively. rotate : bool, optional (default=False) When set to ``True``, orient tree left to right rather than top-down. rounded : bool, optional (default=False) When set to ``True``, draw node boxes with rounded corners and use Helvetica fonts instead of Times-Roman. special_characters : bool, optional (default=False) When set to ``False``, ignore special characters for PostScript compatibility. Examples -------- >>> from sklearn.datasets import load_iris >>> from sklearn import tree >>> clf = tree.DecisionTreeClassifier() >>> iris = load_iris() >>> clf = clf.fit(iris.data, iris.target) >>> tree.export_graphviz(clf, ... out_file='tree.dot') # doctest: +SKIP """ def get_color(value): # Find the appropriate color & intensity for a node if colors['bounds'] is None: # Classification tree color = list(colors['rgb'][np.argmax(value)]) sorted_values = sorted(value, reverse=True) alpha = int(255 * (sorted_values[0] - sorted_values[1]) / (1 - sorted_values[1])) else: # Regression tree or multi-output color = list(colors['rgb'][0]) alpha = int(255 * ((value - colors['bounds'][0]) / (colors['bounds'][1] - colors['bounds'][0]))) # Return html color code in #RRGGBBAA format color.append(alpha) hex_codes = [str(i) for i in range(10)] hex_codes.extend(['a', 'b', 'c', 'd', 'e', 'f']) color = [hex_codes[c // 16] + hex_codes[c % 16] for c in color] return '#' + ''.join(color) def node_to_str(tree, node_id, criterion): # Generate the node content string if tree.n_outputs == 1: value = tree.value[node_id][0, :] else: value = tree.value[node_id] # Should labels be shown? labels = (label == 'root' and node_id == 0) or label == 'all' # PostScript compatibility for special characters if special_characters: characters = ['#', '', '', '≤', '
', '>'] node_string = '<' else: characters = ['#', '[', ']', '<=', '\\n', '"'] node_string = '"' # Write node ID if node_ids: if labels: node_string += 'node ' node_string += characters[0] + str(node_id) + characters[4] # Write decision criteria if tree.children_left[node_id] != _tree.TREE_LEAF: # Always write node decision criteria, except for leaves if feature_names is not None: feature = feature_names[tree.feature[node_id]] else: feature = "X%s%s%s" % (characters[1], tree.feature[node_id], characters[2]) node_string += '%s %s %s%s' % (feature, characters[3], round(tree.threshold[node_id], 4), characters[4]) # Write impurity if impurity: if isinstance(criterion, _tree.FriedmanMSE): criterion = "friedman_mse" elif not isinstance(criterion, six.string_types): criterion = "impurity" if labels: node_string += '%s = ' % criterion node_string += (str(round(tree.impurity[node_id], 4)) + characters[4]) # Write node sample count if labels: node_string += 'samples = ' if proportion: percent = (100. * tree.n_node_samples[node_id] / float(tree.n_node_samples[0])) node_string += (str(round(percent, 1)) + '%' + characters[4]) else: node_string += (str(tree.n_node_samples[node_id]) + characters[4]) # Write node class distribution / regression value if proportion and tree.n_classes[0] != 1: # For classification this will show the proportion of samples value = value / tree.weighted_n_node_samples[node_id] if labels: node_string += 'value = ' if tree.n_classes[0] == 1: # Regression value_text = np.around(value, 4) elif proportion: # Classification value_text = np.around(value, 2) elif np.all(np.equal(np.mod(value, 1), 0)): # Classification without floating-point weights value_text = value.astype(int) else: # Classification with floating-point weights value_text = np.around(value, 4) # Strip whitespace value_text = str(value_text.astype('S32')).replace("b'", "'") value_text = value_text.replace("' '", ", ").replace("'", "") if tree.n_classes[0] == 1 and tree.n_outputs == 1: value_text = value_text.replace("[", "").replace("]", "") value_text = value_text.replace("\n ", characters[4]) node_string += value_text + characters[4] # Write node majority class if (class_names is not None and tree.n_classes[0] != 1 and tree.n_outputs == 1): # Only done for single-output classification trees if labels: node_string += 'class = ' if class_names is not True: class_name = class_names[np.argmax(value)] else: class_name = "y%s%s%s" % (characters[1], np.argmax(value), characters[2]) node_string += class_name # Clean up any trailing newlines if node_string[-2:] == '\\n': node_string = node_string[:-2] if node_string[-5:] == '
': node_string = node_string[:-5] return node_string + characters[5] def recurse(tree, node_id, criterion, parent=None, depth=0): if node_id == _tree.TREE_LEAF: raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF) left_child = tree.children_left[node_id] right_child = tree.children_right[node_id] # Add node with description if max_depth is None or depth <= max_depth: # Collect ranks for 'leaf' option in plot_options if left_child == _tree.TREE_LEAF: ranks['leaves'].append(str(node_id)) elif str(depth) not in ranks: ranks[str(depth)] = [str(node_id)] else: ranks[str(depth)].append(str(node_id)) out_file.write('%d [label=%s' % (node_id, node_to_str(tree, node_id, criterion))) if filled: # Fetch appropriate color for node if 'rgb' not in colors: # Initialize colors and bounds if required colors['rgb'] = _color_brew(tree.n_classes[0]) if tree.n_outputs != 1: # Find max and min impurities for multi-output colors['bounds'] = (np.min(-tree.impurity), np.max(-tree.impurity)) elif tree.n_classes[0] == 1: # Find max and min values in leaf nodes for regression colors['bounds'] = (np.min(tree.value), np.max(tree.value)) if tree.n_outputs == 1: node_val = (tree.value[node_id][0, :] / tree.weighted_n_node_samples[node_id]) if tree.n_classes[0] == 1: # Regression node_val = tree.value[node_id][0, :] else: # If multi-output color node by impurity node_val = -tree.impurity[node_id] out_file.write(', fillcolor="%s"' % get_color(node_val)) out_file.write('] ;\n') if parent is not None: # Add edge to parent out_file.write('%d -> %d' % (parent, node_id)) if parent == 0: # Draw True/False labels if parent is root node angles = np.array([45, -45]) * ((rotate - .5) * -2) out_file.write(' [labeldistance=2.5, labelangle=') if node_id == 1: out_file.write('%d, headlabel="True"]' % angles[0]) else: out_file.write('%d, headlabel="False"]' % angles[1]) out_file.write(' ;\n') if left_child != _tree.TREE_LEAF: recurse(tree, left_child, criterion=criterion, parent=node_id, depth=depth + 1) recurse(tree, right_child, criterion=criterion, parent=node_id, depth=depth + 1) else: ranks['leaves'].append(str(node_id)) out_file.write('%d [label="(...)"' % node_id) if filled: # color cropped nodes grey out_file.write(', fillcolor="#C0C0C0"') out_file.write('] ;\n' % node_id) if parent is not None: # Add edge to parent out_file.write('%d -> %d ;\n' % (parent, node_id)) own_file = False try: if isinstance(out_file, six.string_types): if six.PY3: out_file = open(out_file, "w", encoding="utf-8") else: out_file = open(out_file, "wb") own_file = True # The depth of each node for plotting with 'leaf' option ranks = {'leaves': []} # The colors to render each node with colors = {'bounds': None} out_file.write('digraph Tree {\n') # Specify node aesthetics out_file.write('node [shape=box') rounded_filled = [] if filled: rounded_filled.append('filled') if rounded: rounded_filled.append('rounded') if len(rounded_filled) > 0: out_file.write(', style="%s", color="black"' % ", ".join(rounded_filled)) if rounded: out_file.write(', fontname=helvetica') out_file.write('] ;\n') # Specify graph & edge aesthetics if leaves_parallel: out_file.write('graph [ranksep=equally, splines=polyline] ;\n') if rounded: out_file.write('edge [fontname=helvetica] ;\n') if rotate: out_file.write('rankdir=LR ;\n') # Now recurse the tree and add node & edge attributes if isinstance(decision_tree, _tree.Tree): recurse(decision_tree, 0, criterion="impurity") else: recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion) # If required, draw leaf nodes at same depth as each other if leaves_parallel: for rank in sorted(ranks): out_file.write("{rank=same ; " + "; ".join(r for r in ranks[rank]) + "} ;\n") out_file.write("}") finally: if own_file: out_file.close() class DuplicateArgument(Exception): pass class TooSamllBlockDuration(ValueError): """Raised when block_dur results in a block_size smaller than one sample.""" def __init__(self, message, block_dur, sampling_rate): self.block_dur = block_dur self.sampling_rate = sampling_rate super(TooSamllBlockDuration, self).__init__(message) class TimeFormatError(Exception): """Raised when a duration formatting directive is unknown.""" class EndOfProcessing(Exception): """Raised within command line script's main function to jump to postprocessing code.""" class AudioIOError(Exception): """Raised when a compressed audio file cannot be loaded or when trying to read from a not yet open AudioSource""" class AudioParameterError(AudioIOError): """Raised when one audio parameter is missing when loading raw data or saving data to a format other than raw. Also raised when an audio parameter has a wrong value.""" class AudioEncodingError(Exception): """Raised if audio data can not be encoded in the provided format""" class AudioEncodingWarning(RuntimeWarning): """Raised if audio data can not be encoded in the provided format but saved as wav. """ from __future__ import print_function, division from sympy.combinatorics.perm_groups import PermutationGroup from sympy.combinatorics.permutations import Permutation from sympy.utilities.iterables import uniq from sympy.core.compatibility import range _af_new = Permutation._af_new def DirectProduct(*groups): """ Returns the direct product of several groups as a permutation group. This is implemented much like the __mul__ procedure for taking the direct product of two permutation groups, but the idea of shifting the generators is realized in the case of an arbitrary number of groups. A call to DirectProduct(G1, G2, ..., Gn) is generally expected to be faster than a call to G1*G2*...*Gn (and thus the need for this algorithm). Examples ======== >>> from sympy.combinatorics.group_constructs import DirectProduct >>> from sympy.combinatorics.named_groups import CyclicGroup >>> C = CyclicGroup(4) >>> G = DirectProduct(C, C, C) >>> G.order() 64 See Also ======== __mul__ """ degrees = [] gens_count = [] total_degree = 0 total_gens = 0 for group in groups: current_deg = group.degree current_num_gens = len(group.generators) degrees.append(current_deg) total_degree += current_deg gens_count.append(current_num_gens) total_gens += current_num_gens array_gens = [] for i in range(total_gens): array_gens.append(list(range(total_degree))) current_gen = 0 current_deg = 0 for i in range(len(gens_count)): for j in range(current_gen, current_gen + gens_count[i]): gen = ((groups[i].generators)[j - current_gen]).array_form array_gens[j][current_deg:current_deg + degrees[i]] = \ [x + current_deg for x in gen] current_gen += gens_count[i] current_deg += degrees[i] perm_gens = list(uniq([_af_new(list(a)) for a in array_gens])) return PermutationGroup(perm_gens, dups=False) #!/usr/bin/python2.4 # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """New implementation of Visual Studio project generation for SCons.""" import common import os import random # hashlib is supplied as of Python 2.5 as the replacement interface for md5 # and other secure hashes. In 2.6, md5 is deprecated. Import hashlib if # available, avoiding a deprecation warning under 2.6. Import md5 otherwise, # preserving 2.4 compatibility. try: import hashlib _new_md5 = hashlib.md5 except ImportError: import md5 _new_md5 = md5.new # Initialize random number generator random.seed() # GUIDs for project types ENTRY_TYPE_GUIDS = { 'project': '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}', 'folder': '{2150E333-8FDC-42A3-9474-1A3956D46DE8}', } #------------------------------------------------------------------------------ # Helper functions def MakeGuid(name, seed='msvs_new'): """Returns a GUID for the specified target name. Args: name: Target name. seed: Seed for MD5 hash. Returns: A GUID-line string calculated from the name and seed. This generates something which looks like a GUID, but depends only on the name and seed. This means the same name/seed will always generate the same GUID, so that projects and solutions which refer to each other can explicitly determine the GUID to refer to explicitly. It also means that the GUID will not change when the project for a target is rebuilt. """ # Calculate a MD5 signature for the seed and name. d = _new_md5(str(seed) + str(name)).hexdigest().upper() # Convert most of the signature to GUID form (discard the rest) guid = ('{' + d[:8] + '-' + d[8:12] + '-' + d[12:16] + '-' + d[16:20] + '-' + d[20:32] + '}') return guid #------------------------------------------------------------------------------ class MSVSFolder: """Folder in a Visual Studio project or solution.""" def __init__(self, path, name = None, entries = None, guid = None, items = None): """Initializes the folder. Args: path: Full path to the folder. name: Name of the folder. entries: List of folder entries to nest inside this folder. May contain Folder or Project objects. May be None, if the folder is empty. guid: GUID to use for folder, if not None. items: List of solution items to include in the folder project. May be None, if the folder does not directly contain items. """ if name: self.name = name else: # Use last layer. self.name = os.path.basename(path) self.path = path self.guid = guid # Copy passed lists (or set to empty lists) self.entries = list(entries or []) self.items = list(items or []) self.entry_type_guid = ENTRY_TYPE_GUIDS['folder'] def get_guid(self): if self.guid is None: # Use consistent guids for folders (so things don't regenerate). self.guid = MakeGuid(self.path, seed='msvs_folder') return self.guid #------------------------------------------------------------------------------ class MSVSProject: """Visual Studio project.""" def __init__(self, path, name = None, dependencies = None, guid = None, config_platform_overrides = None): """Initializes the project. Args: path: Relative path to project file. name: Name of project. If None, the name will be the same as the base name of the project file. dependencies: List of other Project objects this project is dependent upon, if not None. guid: GUID to use for project, if not None. config_platform_overrides: optional dict of configuration platforms to used in place of the default for this target. """ self.path = path self.guid = guid if name: self.name = name else: # Use project filename self.name = os.path.splitext(os.path.basename(path))[0] # Copy passed lists (or set to empty lists) self.dependencies = list(dependencies or []) self.entry_type_guid = ENTRY_TYPE_GUIDS['project'] if config_platform_overrides: self.config_platform_overrides = config_platform_overrides else: self.config_platform_overrides = {} def get_guid(self): if self.guid is None: # Set GUID from path # TODO(rspangler): This is fragile. # 1. We can't just use the project filename sans path, since there could # be multiple projects with the same base name (for example, # foo/unittest.vcproj and bar/unittest.vcproj). # 2. The path needs to be relative to $SOURCE_ROOT, so that the project # GUID is the same whether it's included from base/base.sln or # foo/bar/baz/baz.sln. # 3. The GUID needs to be the same each time this builder is invoked, so # that we don't need to rebuild the solution when the project changes. # 4. We should be able to handle pre-built project files by reading the # GUID from the files. self.guid = MakeGuid(self.name) return self.guid #------------------------------------------------------------------------------ class MSVSSolution: """Visual Studio solution.""" def __init__(self, path, version, entries=None, variants=None, websiteProperties=True): """Initializes the solution. Args: path: Path to solution file. version: Format version to emit. entries: List of entries in solution. May contain Folder or Project objects. May be None, if the folder is empty. variants: List of build variant strings. If none, a default list will be used. websiteProperties: Flag to decide if the website properties section is generated. """ self.path = path self.websiteProperties = websiteProperties self.version = version # Copy passed lists (or set to empty lists) self.entries = list(entries or []) if variants: # Copy passed list self.variants = variants[:] else: # Use default self.variants = ['Debug|Win32', 'Release|Win32'] # TODO(rspangler): Need to be able to handle a mapping of solution config # to project config. Should we be able to handle variants being a dict, # or add a separate variant_map variable? If it's a dict, we can't # guarantee the order of variants since dict keys aren't ordered. # TODO(rspangler): Automatically write to disk for now; should delay until # node-evaluation time. self.Write() def Write(self, writer=common.WriteOnDiff): """Writes the solution file to disk. Raises: IndexError: An entry appears multiple times. """ # Walk the entry tree and collect all the folders and projects. all_entries = [] entries_to_check = self.entries[:] while entries_to_check: # Pop from the beginning of the list to preserve the user's order. e = entries_to_check.pop(0) # A project or folder can only appear once in the solution's folder tree. # This also protects from cycles. if e in all_entries: #raise IndexError('Entry "%s" appears more than once in solution' % # e.name) continue all_entries.append(e) # If this is a folder, check its entries too. if isinstance(e, MSVSFolder): entries_to_check += e.entries # Sort by name then guid (so things are in order on vs2008). def NameThenGuid(a, b): if a.name < b.name: return -1 if a.name > b.name: return 1 if a.get_guid() < b.get_guid(): return -1 if a.get_guid() > b.get_guid(): return 1 return 0 all_entries = sorted(all_entries, NameThenGuid) # Open file and print header f = writer(self.path) f.write('Microsoft Visual Studio Solution File, ' 'Format Version %s\r\n' % self.version.SolutionVersion()) f.write('# %s\r\n' % self.version.Description()) # Project entries for e in all_entries: f.write('Project("%s") = "%s", "%s", "%s"\r\n' % ( e.entry_type_guid, # Entry type GUID e.name, # Folder name e.path.replace('/', '\\'), # Folder name (again) e.get_guid(), # Entry GUID )) # TODO(rspangler): Need a way to configure this stuff if self.websiteProperties: f.write('\tProjectSection(WebsiteProperties) = preProject\r\n' '\t\tDebug.AspNetCompiler.Debug = "True"\r\n' '\t\tRelease.AspNetCompiler.Debug = "False"\r\n' '\tEndProjectSection\r\n') if isinstance(e, MSVSFolder): if e.items: f.write('\tProjectSection(SolutionItems) = preProject\r\n') for i in e.items: f.write('\t\t%s = %s\r\n' % (i, i)) f.write('\tEndProjectSection\r\n') if isinstance(e, MSVSProject): if e.dependencies: f.write('\tProjectSection(ProjectDependencies) = postProject\r\n') for d in e.dependencies: f.write('\t\t%s = %s\r\n' % (d.get_guid(), d.get_guid())) f.write('\tEndProjectSection\r\n') f.write('EndProject\r\n') # Global section f.write('Global\r\n') # Configurations (variants) f.write('\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n') for v in self.variants: f.write('\t\t%s = %s\r\n' % (v, v)) f.write('\tEndGlobalSection\r\n') # Sort config guids for easier diffing of solution changes. config_guids = [] config_guids_overrides = {} for e in all_entries: if isinstance(e, MSVSProject): config_guids.append(e.get_guid()) config_guids_overrides[e.get_guid()] = e.config_platform_overrides config_guids.sort() f.write('\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n') for g in config_guids: for v in self.variants: nv = config_guids_overrides[g].get(v, v) # Pick which project configuration to build for this solution # configuration. f.write('\t\t%s.%s.ActiveCfg = %s\r\n' % ( g, # Project GUID v, # Solution build configuration nv, # Project build config for that solution config )) # Enable project in this solution configuration. f.write('\t\t%s.%s.Build.0 = %s\r\n' % ( g, # Project GUID v, # Solution build configuration nv, # Project build config for that solution config )) f.write('\tEndGlobalSection\r\n') # TODO(rspangler): Should be able to configure this stuff too (though I've # never seen this be any different) f.write('\tGlobalSection(SolutionProperties) = preSolution\r\n') f.write('\t\tHideSolutionNode = FALSE\r\n') f.write('\tEndGlobalSection\r\n') # Folder mappings # TODO(rspangler): Should omit this section if there are no folders f.write('\tGlobalSection(NestedProjects) = preSolution\r\n') for e in all_entries: if not isinstance(e, MSVSFolder): continue # Does not apply to projects, only folders for subentry in e.entries: f.write('\t\t%s = %s\r\n' % (subentry.get_guid(), e.get_guid())) f.write('\tEndGlobalSection\r\n') f.write('EndGlobal\r\n') f.close() #!/usr/bin/env python2.4 """static - A stupidly simple WSGI way to serve static (or mixed) content. (See the docstrings of the various functions and classes.) Copyright (C) 2006-2009 Luke Arno - http://lukearno.com/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to: The Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Luke Arno can be found at http://lukearno.com/ """ import mimetypes import rfc822 import time import string import sys from os import path, stat from wsgiref import util from wsgiref.headers import Headers from wsgiref.simple_server import make_server from optparse import OptionParser try: from pkg_resources import resource_filename, Requirement except: pass try: import kid except: pass class MagicError(Exception): pass class StatusApp: """Used by WSGI apps to return some HTTP status.""" def __init__(self, status, message=None): self.status = status if message is None: self.message = status else: self.message = message def __call__(self, environ, start_response, headers=[]): if self.message: Headers(headers).add_header('Content-type', 'text/plain') start_response(self.status, headers) if environ['REQUEST_METHOD'] == 'HEAD': return [""] else: return [self.message] class Cling(object): """A stupidly simple way to serve static content via WSGI. Serve the file of the same path as PATH_INFO in self.datadir. Look up the Content-type in self.content_types by extension or use 'text/plain' if the extension is not found. Serve up the contents of the file or delegate to self.not_found. """ block_size = 16 * 4096 index_file = 'index.html' not_found = StatusApp('404 Not Found') not_modified = StatusApp('304 Not Modified', "") moved_permanently = StatusApp('301 Moved Permanently') method_not_allowed = StatusApp('405 Method Not Allowed') def __init__(self, root, **kw): """Just set the root and any other attribs passes via **kw.""" self.root = root for k, v in kw.iteritems(): setattr(self, k, v) def __call__(self, environ, start_response): """Respond to a request when called in the usual WSGI way.""" if environ['REQUEST_METHOD'] not in ('GET', 'HEAD'): headers = [('Allow', 'GET, HEAD')] return self.method_not_allowed(environ, start_response, headers) path_info = environ.get('PATH_INFO', '') full_path = self._full_path(path_info) if not self._is_under_root(full_path): return self.not_found(environ, start_response) if path.isdir(full_path): if full_path[-1] <> '/' or full_path == self.root: location = util.request_uri(environ, include_query=False) + '/' if environ.get('QUERY_STRING'): location += '?' + environ.get('QUERY_STRING') headers = [('Location', location)] return self.moved_permanently(environ, start_response, headers) else: full_path = self._full_path(path_info + self.index_file) content_type = self._guess_type(full_path) try: etag, last_modified = self._conditions(full_path, environ) headers = [('Date', rfc822.formatdate(time.time())), ('Last-Modified', last_modified), ('ETag', etag)] if_modified = environ.get('HTTP_IF_MODIFIED_SINCE') if if_modified and (rfc822.parsedate(if_modified) >= rfc822.parsedate(last_modified)): return self.not_modified(environ, start_response, headers) if_none = environ.get('HTTP_IF_NONE_MATCH') if if_none and (if_none == '*' or etag in if_none): return self.not_modified(environ, start_response, headers) file_like = self._file_like(full_path) headers.append(('Content-Type', content_type)) start_response("200 OK", headers) if environ['REQUEST_METHOD'] == 'GET': return self._body(full_path, environ, file_like) else: return [''] except (IOError, OSError), e: print e return self.not_found(environ, start_response) def _full_path(self, path_info): """Return the full path from which to read.""" return self.root + path_info def _is_under_root(self, full_path): """Guard against arbitrary file retrieval.""" if (path.abspath(full_path) + path.sep)\ .startswith(path.abspath(self.root) + path.sep): return True else: return False def _guess_type(self, full_path): """Guess the mime type using the mimetypes module.""" return mimetypes.guess_type(full_path)[0] or 'text/plain' def _conditions(self, full_path, environ): """Return a tuple of etag, last_modified by mtime from stat.""" mtime = stat(full_path).st_mtime return str(mtime), rfc822.formatdate(mtime) def _file_like(self, full_path): """Return the appropriate file object.""" return open(full_path, 'rb') def _body(self, full_path, environ, file_like): """Return an iterator over the body of the response.""" way_to_send = environ.get('wsgi.file_wrapper', iter_and_close) return way_to_send(file_like, self.block_size) def iter_and_close(file_like, block_size): """Yield file contents by block then close the file.""" while 1: try: block = file_like.read(block_size) if block: yield block else: raise StopIteration except StopIteration, si: file_like.close() return def cling_wrap(package_name, dir_name, **kw): """Return a Cling that serves from the given package and dir_name. This uses pkg_resources.resource_filename which is not the recommended way, since it extracts the files. I think this works fine unless you have some _very_ serious requirements for static content, in which case you probably shouldn't be serving it through a WSGI app, IMHO. YMMV. """ resource = Requirement.parse(package_name) return Cling(resource_filename(resource, dir_name), **kw) class Shock(Cling): """A stupidly simple way to serve up mixed content. Serves static content just like Cling (it's superclass) except that it process content with the first matching magic from self.magics if any apply. See Cling and classes with "Magic" in their names in this module. If you are using Shock with the StringMagic class for instance: shock = Shock('/data', magics=[StringMagic(food='cheese')]) Let's say you have a file called /data/foo.txt.stp containing one line: "I love to eat $food!" When you do a GET on /foo.txt you will see this in your browser: "I love to eat cheese!" This is really nice if you have a color variable in your css files or something trivial like that. It seems silly to create or change a handful of objects for a couple of dynamic bits of text. """ magics = () def _match_magic(self, full_path): """Return the first magic that matches this path or None.""" for magic in self.magics: if magic.matches(full_path): return magic def _full_path(self, path_info): """Return the full path from which to read.""" full_path = self.root + path_info if path.exists(full_path): return full_path else: for magic in self.magics: if path.exists(magic.new_path(full_path)): return magic.new_path(full_path) else: return full_path def _guess_type(self, full_path): """Guess the mime type magically or using the mimetypes module.""" magic = self._match_magic(full_path) if magic is not None: return (mimetypes.guess_type(magic.old_path(full_path))[0] or 'text/plain') else: return mimetypes.guess_type(full_path)[0] or 'text/plain' def _conditions(self, full_path, environ): """Return Etag and Last-Modified values defaults to now for both.""" magic = self._match_magic(full_path) if magic is not None: return magic.conditions(full_path, environ) else: mtime = stat(full_path).st_mtime return str(mtime), rfc822.formatdate(mtime) def _file_like(self, full_path): """Return the appropriate file object.""" magic = self._match_magic(full_path) if magic is not None: return magic.file_like(full_path) else: return open(full_path, 'rb') def _body(self, full_path, environ, file_like): """Return an iterator over the body of the response.""" magic = self._match_magic(full_path) if magic is not None: return magic.body(environ, file_like) else: way_to_send = environ.get('wsgi.file_wrapper', iter_and_close) return way_to_send(file_like, self.block_size) class BaseMagic(object): """Base class for magic file handling. Really a do nothing if you were to use this directly. In a strait forward case you would just override .extension and body(). (See StringMagic in this module for a simple example of subclassing.) In a more complex case you may need to override many or all methods. """ extension = '' def exists(self, full_path): """Check that self.new_path(full_path) exists.""" if path.exists(self.new_path(full_path)): return self.new_path(full_path) def new_path(self, full_path): """Add the self.extension to the path.""" return full_path + self.extension def old_path(self, full_path): """Remove self.extension from path or raise MagicError.""" if self.matches(full_path): return full_path[:-len(self.extension)] else: raise MagicError, "Path does not match this magic." def matches(self, full_path): """Check that path ends with self.extension.""" if full_path.endswith(self.extension): return full_path def conditions(self, full_path, environ): """Return Etag and Last-Modified values (based on mtime).""" mtime = int(time.time()) return str(mtime), rfc822.formatdate(mtime) def file_like(self, full_path): """Return a file object for path.""" return open(full_path, 'rb') def body(self, environ, file_like): """Return an iterator over the body of the response.""" return [file_like.read()] class StringMagic(BaseMagic): """Magic to replace variables in file contents using string.Template. Using this requires Python2.4. """ extension = '.stp' safe = False def __init__(self, **variables): """Keyword arguments populate self.variables.""" self.variables = variables def body(self, environ, file_like): """Pass environ and self.variables in to template. self.variables overrides environ so that suprises in environ don't cause unexpected output if you are passing a value in explicitly. """ variables = environ.copy() variables.update(self.variables) template = string.Template(file_like.read()) if self.safe is True: return [template.safe_substitute(variables)] else: return [template.substitute(variables)] class KidMagic(StringMagic): """Like StringMagic only using the Kid templating language. Using this requires Kid: http://kid.lesscode.org/ """ extension = '.kid' def body(self, environ, full_path): """Pass environ and **self.variables into the template.""" template = kid.Template(file=full_path, environ=environ, **self.variables) return [template.serialize()] def command(): parser = OptionParser(usage="%prog DIR [HOST][:][PORT]", version="static 0.3.6") options, args = parser.parse_args() if len(args) in (1, 2): if len(args) == 2: parts = args[1].split(":") if len(parts) == 1: host = parts[0] port = None elif len(parts) == 2: host, port = parts else: sys.exit("Invalid host:port specification.") elif len(args) == 1: host, port = None, None if not host: host = '0.0.0.0' if not port: port = 9999 try: port = int(port) except: sys.exit("Invalid host:port specification.") app = Cling(args[0]) try: make_server(host, port, app).serve_forever() except KeyboardInterrupt, ki: print "Cio, baby!" except: sys.exit("Problem initializing server.") else: parser.print_help(sys.stderr) sys.exit(1) def test(): from wsgiref.validate import validator magics = StringMagic(title="String Test"), KidMagic(title="Kid Test") app = Shock('testdata/pub', magics=magics) try: make_server('localhost', 9999, validator(app)).serve_forever() except KeyboardInterrupt, ki: print "Ciao, baby!" if __name__ == '__main__': test() #!/bin/python import pylab as pl import cPickle import matplotlib.pyplot as plt from sklearn import svm, metrics import numpy as np import sys square = 13 imgloc = '../images/v012-penn.10-1hA5D1-cropb.png' resd={'dot':0,'noise':1,'vein':2} currimg=plt.imread(imgloc) pkl_file=open('dots.pkl', 'r') dots = cPickle.load(pkl_file) pkl_file.close() pkl_file=open('noise.pkl', 'r') noise = cPickle.load(pkl_file) pkl_file.close() pkl_file=open('veins.pkl','r') veins = cPickle.load(pkl_file) pkl_file.close() #dots = zip(dots, [0 for i in range(len(dots))]) #noise = zip(noise, [1 for i in range(len(noise))]) #veins = zip(veins, [2 for i in range(len(veins))]) print np.shape(np.asarray(dots)) print np.shape(np.asarray(noise)) print np.shape(np.asarray(veins)) dots_data = np.asarray(dots).reshape((len(dots),-1)) noise_data= np.asarray(noise).reshape((len(noise),-1)) veins_data= np.asarray(veins).reshape((len(veins),-1)) data = np.concatenate((np.concatenate((dots_data,noise_data)),veins_data)) print len(data) target = [resd['dot'] for i in range(len(dots_data))] + [resd['noise'] for i in range(len(noise_data))] + [resd['vein'] for i in range(len(veins_data))] print len(target) classifier = svm.SVC(gamma=0.001) classifier.fit(data, target) tmpx, tmpy = len(currimg[0][:]), len(currimg[:][0]) final_image=np.ones((tmpy,tmpx)) blocks=[] print 'Going through the blocks...' sys.stdout.flush() for i in [i+square/2 for i in xrange(tmpy-square)]: for j in [j+square/2 for j in xrange(tmpx-square)]: currblock=currimg[i-square/2:i+square/2+1,j-square/2:j+square/2+1] blocks.append(currblock) blocks=np.asarray(blocks) print np.shape(blocks) blocks = np.asarray(blocks).reshape(len(blocks),-1) print np.shape(blocks) print 'About to make predictions...' sys.stdout.flush() predicted = classifier.predict(blocks) voting = np.zeros((tmpy, tmpx, 3)) print 'About to count votes...' sys.stdout.flush() for p in xrange(len(predicted)): j=p%(tmpx-square)+square/2 i=(p-j+square/2)/(tmpx-square)+square/2 #[i,j] are the coordinates of the center of that box #since p=(i-s/2)(X-s)+j-s/2 for y in range(i-square/2,i+square/2): for x in range(j-square/2,j+square/2): voting[y,x][predicted[p]]+=1 for i in xrange(tmpy): for j in xrange(tmpx): if voting[i,j].argmax()==resd['vein']: final_image[i,j]=0 plt.imshow(final_image, cmap=plt.cm.gray) plt.show() #for i in [i+square/2 for i in xrange(tmpx-square)]: # for j in [j+square/2 for j in xrange(tmpy-square)]: # for k in range(i-square/2,i+square/2+1): # for __author__ = 'DongMin Kim' from opencog.atomspace import * from test_conceptual_blending_base import TestConceptualBlendingBase # Only run the unit tests if the required dependencies have been installed # (see: https://github.com/opencog/opencog/issues/337) try: __import__("nose.tools") except ImportError: import unittest raise unittest.SkipTest( "ImportError exception: " + "Can't find Nose. " + "make sure the required dependencies are installed." ) else: # noinspection PyPackageRequirements from nose.tools import * try: __import__("opencog.scheme_wrapper") except ImportError: import unittest raise unittest.SkipTest( "ImportError exception: " + "Can't find Scheme wrapper for Python. " + "make sure the required dependencies are installed." ) else: from opencog.scheme_wrapper import * try: __import__("blending.blend") except ImportError: import unittest raise unittest.SkipTest( "ImportError exception: " + "Can't find Python Conceptual Blender. " + "make sure the required dependencies are installed." ) else: from blending.blend import ConceptualBlending try: from blending.util.py_cog_execute import PyCogExecute PyCogExecute().load_scheme() except (ImportError, RuntimeError): import unittest raise unittest.SkipTest( "Can't load Scheme." + "make sure the you installed atomspace to /usr/local/share/opencog." ) # noinspection PyArgumentList, PyTypeChecker class TestAtomsChooser(TestConceptualBlendingBase): """ 2.1. AtomsChooser tests. """ """ 2.1.1. ChooseNull tests. """ __test__ = True def __default_choose_null(self): self.a.add_link( types.InheritanceLink, [ self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "default-config") ] ) self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:atoms-chooser"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "ChooseNull") ] ) def test_choose_null_without_focus_atoms(self): self.__default_choose_null() # Test blender not makes blend node if we don't give focus atoms. result = self.blender.run( None, self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 0) # Test blender not makes blend node if we don't give focus atoms. result = self.blender.run( [], self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 0) def test_choose_null_with_focus_atoms(self): self.__default_choose_null() # Test blender makes only one new blend node. result = self.blender.run( [self.sample_nodes["car"], self.sample_nodes["man"], self.sample_nodes["metal"]], self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 1) # Test blender makes new blend node correctly. blended_node = result[0] assert_in("car", str(blended_node.name)) assert_in("man", str(blended_node.name)) assert_in("metal", str(blended_node.name)) assert_not_in("move", str(blended_node.name)) assert_not_in("vehicle", str(blended_node.name)) assert_not_in("person", str(blended_node.name)) """ 2.1.2. ChooseAll tests. """ def __default_choose_all(self): self.a.add_link( types.InheritanceLink, [ self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "default-config") ] ) self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:atoms-chooser"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "ChooseAll") ] ) def test_choose_all(self): self.__default_choose_all() # Test blender doesn't explain if focus atoms was not given, # but find all atoms in AtomSpace. result = self.blender.run( None, self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 1) # Test blender makes new blend node correctly. blended_node = result[0] assert_in("car", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("metal", str(blended_node.name)) assert_in("move", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("person", str(blended_node.name)) # Test blender doesn't explain if focus atoms was not given, # but find all atoms in AtomSpace. result = self.blender.run( [], self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 1) # Test blender makes new blend node correctly. blended_node = result[0] assert_in("car", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("metal", str(blended_node.name)) assert_in("move", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("person", str(blended_node.name)) # Test blender makes only one new blend node. result = self.blender.run( [self.sample_nodes["car"], self.sample_nodes["vehicle"]], self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 1) # Test blender makes new blend node correctly. blended_node = result[0] assert_in("car", str(blended_node.name)) assert_not_in("man", str(blended_node.name)) assert_not_in("metal", str(blended_node.name)) assert_not_in("move", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_not_in("person", str(blended_node.name)) def test_choose_all_with_type_limit(self): self.__default_choose_all() # Test blender limits node type correctly. choose_atom_type_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-atom-type"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "PredicateNode") ] ) result = self.blender.run( None, self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 0) self.a.remove(choose_atom_type_link) # Test blender limits node type correctly. choose_atom_type_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-atom-type"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "ConceptNode") ] ) result = self.blender.run( None, self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 1) # Test blender makes new blend node correctly. blended_node = result[0] assert_in("car", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("metal", str(blended_node.name)) assert_in("move", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("person", str(blended_node.name)) self.a.remove(choose_atom_type_link) def test_choose_all_with_count_limit(self): self.__default_choose_all() # Test blender checks node count correctly. choose_least_count_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-least-count"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "1000") ] ) result = self.blender.run( None, self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 0) self.a.remove(choose_least_count_link) # Test blender checks node count correctly. choose_least_count_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-least-count"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "2") ] ) result = self.blender.run( None, self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 1) self.a.remove(choose_least_count_link) """ 2.1.3. ChooseInSTIRange tests. """ def __default_choose_in_sti_range(self): self.a.add_link( types.InheritanceLink, [ self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "default-config") ] ) self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:atoms-chooser"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "ChooseInSTIRange") ] ) def test_choose_in_sti_range_without_focus_atoms(self): self.__default_choose_in_sti_range() # Test blender makes only one new blend node. result = self.blender.run( None, self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 0) def test_choose_in_sti_range_with_focus_atoms(self): self.__default_choose_in_sti_range() # Test blender makes only one new blend node. result = self.blender.run( self.a.get_atoms_by_type(types.Node), self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 1) # Test blender makes new blend node correctly. blended_node = result[0] assert_in("car", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("metal", str(blended_node.name)) assert_in("move", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("person", str(blended_node.name)) def test_choose_in_sti_range_with_type_limit(self): self.__default_choose_in_sti_range() # Test blender limits node type correctly. choose_atom_type_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-atom-type"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "PredicateNode") ] ) result = self.blender.run( self.a.get_atoms_by_type(types.Node), self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 0) self.a.remove(choose_atom_type_link) # Test blender limits node type correctly. choose_atom_type_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-atom-type"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "ConceptNode") ] ) result = self.blender.run( self.a.get_atoms_by_type(types.Node), self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 1) # Test blender makes new blend node correctly. blended_node = result[0] assert_in("car", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("metal", str(blended_node.name)) assert_in("move", str(blended_node.name)) assert_in("vehicle", str(blended_node.name)) assert_in("person", str(blended_node.name)) self.a.remove(choose_atom_type_link) def test_choose_in_sti_range_with_count_limit(self): self.__default_choose_in_sti_range() # Test blender limits node count correctly. choose_least_count_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-least-count"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "1000") ] ) result = self.blender.run( self.a.get_atoms_by_type(types.Node), self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 0) self.a.remove(choose_least_count_link) # Test blender limits node count correctly. choose_least_count_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-least-count"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, "2") ] ) result = self.blender.run( self.a.get_atoms_by_type(types.Node), self.a.add_node(types.ConceptNode, "my-config") ) assert_equal(len(result), 1) self.a.remove(choose_least_count_link) def test_choose_in_sti_range_with_min_sti_limit(self): self.__default_choose_in_sti_range() choose_sti_min = 15 # Test blender limits sti value correctly. choose_sti_min_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-sti-min"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, str(choose_sti_min)) ] ) result = self.blender.run( self.a.get_atoms_by_type(types.Node), self.a.add_node(types.ConceptNode, "my-config") ) # Test blender limits sti value correctly. blended_node = result[0] assert_true( str(blended_node.name) == "car-man" or str(blended_node.name) == "man-car" ) self.a.remove(choose_sti_min_link) def test_choose_in_sti_range_with_max_sti_limit(self): self.__default_choose_in_sti_range() choose_sti_max = 5 # Test blender limits sti value correctly. choose_sti_max_link = self.a.add_link( types.ExecutionLink, [ self.a.add_node(types.SchemaNode, "BLEND:choose-sti-max"), self.a.add_node(types.ConceptNode, "my-config"), self.a.add_node(types.ConceptNode, str(choose_sti_max)) ] ) result = self.blender.run( self.a.get_atoms_by_type(types.Node), self.a.add_node(types.ConceptNode, "my-config") ) # Test blender makes new blend node correctly. blended_node = result[0] assert_true( str(blended_node.name) == "metal-move" or str(blended_node.name) == "move-metal" ) self.a.remove(choose_sti_max_link) from .app import db from flask.ext.login import UserMixin from .app import login_manager class User(db.Model, UserMixin): pseudo = db.Column(db.String(100),primary_key=True) usermail = db.Column(db.String(100)) username = db.Column(db.String(50)) usersurname = db.Column(db.String(50)) password = db.Column(db.String(64)) score= db.Column(db.Integer) admin = db.Column(db.Boolean, nullable=False, default=False) def get_id(self): return self.pseudo def __repr__(self): return "%s - %s - %s" % (self.pseudo, self.username, self.usermail) def getUser(pseudo): return db.session.query(User).filter(User.pseudo==pseudo).first() @login_manager.user_loader def load_user(username): return User.query.get(username) class Ia(db.Model): id =db.Column(db.Integer, primary_key=True) user_pseudo =db.Column(db.String(100)) name =db.Column(db.String(100)) def removeIa(filename): s = db.session() m=s.query(Ia).filter(Ia.name==filename).all() for c in m: db.session.delete(c) def removeUser(pseudo): s=db.session() m=s.query(User).filter(User.pseudo==pseudo).all() for c in m: db.session.delete(c) # -*- coding: utf-8 -*- # # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2013 Vassilii Khachaturov # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # import unittest import sys try: if sys.version_info < (3,3): from mock import Mock else: from unittest.mock import Mock MOCKING = True except: MOCKING = False print ("Mocking disabled, some testing skipped", sys.exc_info()[0:2]) class LexGettextTest(unittest.TestCase): SRC_WORD = "Inflect-me" MSGID = "how-to-use-lexgettext||" + SRC_WORD def setUp(self): from ..grampslocale import GrampsTranslations from ..grampslocale import GrampsLocale as Loc self.trans = GrampsTranslations() def setup_sgettext_mock(self, msgval_expected): if MOCKING: mock = Mock(return_value=msgval_expected) else: mock = lambda msgid: msgval_expected self.trans.sgettext = mock def tearDown(self): if MOCKING: try: self.trans.sgettext.assert_called_once_with( self.MSGID) except AttributeError as e: print ("Apparently the test has never set up the mock: ", e) def testSrcWordOnlyIfNoTranslation(self): self.setup_sgettext_mock(self.SRC_WORD) result = self.trans.lexgettext(self.MSGID) self.assertEqual(result, self.SRC_WORD) def test3InflectionsExtractableByNameThroughForm(self): translated = "n=TargetNom|g=TargetGen|d=TargetDat" self.setup_sgettext_mock(translated) lex = self.trans.lexgettext(self.MSGID) formatted = "{lex.f[n]},{lex.f[g]},{lex.f[d]}".format(lex=lex) self.assertEqual(formatted, "TargetNom,TargetGen,TargetDat") def testFirstLexemeFormExtractableAsDefaultString(self): translated = "def=Default|v1=Option1|a=AnotherOption" self.setup_sgettext_mock(translated) lex = self.trans.lexgettext(self.MSGID) formatted = "{}".format(lex) self.assertEqual(formatted, "Default") class LexemeTest(unittest.TestCase): def setUp(self): from ..grampslocale import Lexeme self.lex = Lexeme((('a', 'aaa'), ('b', 'bbb'), ('c', 'ccc'))) self.zlex = Lexeme({'z' : 'zzz'}) self.elex = Lexeme({}) def testIsHashable(self): hash(self.lex) # throws if not hashable # test delegation to an arbitrary string method pulled in from unicode def testDefaultStringStartsWithAA(self): self.assertTrue(self.lex.startswith('aa'), msg="default string: {} dict: {}".format( self.lex, self.lex.__dict__)) def testCanConcatenateStringAndLexeme(self): moo = "moo" self.assertEqual(moo + self.lex, "mooaaa") def testCanConcatenateStringAndLexemeInPlace(self): moo = "moo" moo += self.lex self.assertEqual(moo, "mooaaa") def testCanConcatenateLexemeAndStringInPlace(self): moo = "moo" self.lex += moo self.assertEqual(self.lex, "aaamoo") def testCanConcatenateTwoLexemes(self): aaazzz = self.lex + self.zlex self.assertEqual(aaazzz, "aaazzz") def testCanJoinTwoLexemes(self): aaa_zzz = "_".join([self.lex,self.zlex]) self.assertEqual(aaa_zzz, "aaa_zzz") def testEmptyIterableLikeEmptyString(self): self.assertEqual(self.elex, "") if __name__ == "__main__": unittest.main() # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not 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. import wx import armid import ARM from RiskEnvironmentListCtrl import RiskEnvironmentListCtrl from DimensionListCtrl import DimensionListCtrl from MitigateEnvironmentProperties import MitigateEnvironmentProperties class MitigateEnvironmentPanel(wx.Panel): def __init__(self,parent,dp): wx.Panel.__init__(self,parent,armid.MITIGATE_PANELENVIRONMENT_ID) self.theResponsePanel = parent self.dbProxy = dp self.theEnvironmentDictionary = {} self.theSelectedIdx = -1 mainSizer = wx.BoxSizer(wx.HORIZONTAL) environmentBox = wx.StaticBox(self) environmentListSizer = wx.StaticBoxSizer(environmentBox,wx.HORIZONTAL) mainSizer.Add(environmentListSizer,0,wx.EXPAND) self.environmentList = RiskEnvironmentListCtrl(self,armid.MITIGATE_LISTENVIRONMENTS_ID,self.dbProxy) environmentListSizer.Add(self.environmentList,1,wx.EXPAND) environmentDimSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(environmentDimSizer,1,wx.EXPAND) typeBox = wx.StaticBox(self,-1,'Type') typeBoxSizer = wx.StaticBoxSizer(typeBox,wx.HORIZONTAL) environmentDimSizer.Add(typeBoxSizer,0,wx.EXPAND) self.typeCombo = wx.ComboBox(self,armid.MITIGATE_COMBOTYPE_ID,"",choices=['Deter','Prevent','Detect','React'],style=wx.CB_READONLY) typeBoxSizer.Add(self.typeCombo,1,wx.EXPAND) pointBox = wx.StaticBox(self,-1,'Detection Point') pointBoxSizer = wx.StaticBoxSizer(pointBox,wx.HORIZONTAL) environmentDimSizer.Add(pointBoxSizer,0,wx.EXPAND) self.pointCombo = wx.ComboBox(self,armid.MITIGATE_COMBODETECTIONPOINT_ID,"",choices=['Before','At','After'],style=wx.CB_READONLY) pointBoxSizer.Add(self.pointCombo,1,wx.EXPAND) dmBox = wx.StaticBox(self,-1,) dmBoxSizer = wx.StaticBoxSizer(dmBox,wx.HORIZONTAL) environmentDimSizer.Add(dmBoxSizer,1,wx.EXPAND) self.dmList = DimensionListCtrl(self,armid.MITIGATE_LISTDETMECH_ID,wx.DefaultSize,'Detection Mechanism','detection_mechanism',self.dbProxy,listStyle=wx.LC_REPORT) dmBoxSizer.Add(self.dmList,1,wx.EXPAND) self.typeCombo.Disable() self.pointCombo.Disable() self.dmList.Disable() self.SetSizer(mainSizer) self.typeCombo.Bind(wx.EVT_COMBOBOX,self.onTypeChange) self.environmentList.Bind(wx.EVT_LIST_INSERT_ITEM,self.OnAddEnvironment) self.environmentList.Bind(wx.EVT_LIST_DELETE_ITEM,self.OnDeleteEnvironment) self.environmentList.Bind(wx.EVT_LIST_ITEM_SELECTED,self.OnEnvironmentSelected) self.environmentList.Bind(wx.EVT_LIST_ITEM_DESELECTED,self.OnEnvironmentDeselected) def onTypeChange(self,evt): self.activateTypeCtrls() mitType = self.typeCombo.GetValue() riskCombo = self.theResponsePanel.FindWindowById(armid.RESPONSE_COMBORISK_ID) riskName = riskCombo.GetValue() if (riskName != ''): riskNameCtrl = self.theResponsePanel.FindWindowById(armid.RESPONSE_TEXTNAME_ID) riskNameLabel = mitType + ' ' + riskName riskNameCtrl.SetValue(riskNameLabel) def activateTypeCtrls(self): mitType = self.typeCombo.GetValue() if ((mitType == 'Deter') or (mitType == 'Prevent')): self.pointCombo.SetValue('') self.pointCombo.Disable() self.dmList.DeleteAllItems() self.dmList.Disable() elif (mitType == 'Detect'): self.pointCombo.Enable() self.dmList.Disable() elif (mitType == 'React'): self.pointCombo.Disable() self.dmList.Enable() def loadControls(self,accept): self.environmentList.Unbind(wx.EVT_LIST_ITEM_SELECTED) self.environmentList.Unbind(wx.EVT_LIST_ITEM_DESELECTED) environmentNames = [] for cp in accept.environmentProperties(): environmentNames.append(cp.name()) self.environmentList.load(environmentNames) for cp in accept.environmentProperties(): environmentName = cp.name() self.theEnvironmentDictionary[environmentName] = cp environmentNames.append(environmentName) environmentName = environmentNames[0] p = self.theEnvironmentDictionary[environmentName] self.typeCombo.SetStringSelection(p.type()) self.pointCombo.SetStringSelection(p.detectionPoint()) self.dmList.setEnvironment(environmentName) self.dmList.load(p.detectionMechanisms()) self.environmentList.Select(0) self.activateTypeCtrls() self.environmentList.Bind(wx.EVT_LIST_ITEM_SELECTED,self.OnEnvironmentSelected) self.environmentList.Bind(wx.EVT_LIST_ITEM_DESELECTED,self.OnEnvironmentDeselected) self.theSelectedIdx = 0 def OnEnvironmentSelected(self,evt): self.theSelectedIdx = evt.GetIndex() environmentName = self.environmentList.GetItemText(self.theSelectedIdx) p = self.theEnvironmentDictionary[environmentName] self.typeCombo.SetStringSelection(p.type()) self.pointCombo.SetStringSelection(p.detectionPoint()) self.dmList.setEnvironment(environmentName) self.dmList.load(p.detectionMechanisms()) self.typeCombo.Enable() self.activateTypeCtrls() def OnEnvironmentDeselected(self,evt): self.theSelectedIdx = evt.GetIndex() environmentName = self.environmentList.GetItemText(self.theSelectedIdx) self.theEnvironmentDictionary[environmentName] = MitigateEnvironmentProperties(environmentName,self.typeCombo.GetValue(),self.pointCombo.GetValue(),self.dmList.dimensions()) self.typeCombo.SetValue('') self.pointCombo.SetValue('') self.dmList.setEnvironment('') self.dmList.DeleteAllItems() self.theSelectedIdx = -1 self.typeCombo.Disable() self.pointCombo.Disable() self.dmList.Disable() def OnAddEnvironment(self,evt): self.theSelectedIdx = evt.GetIndex() environmentName = self.environmentList.GetItemText(self.theSelectedIdx) self.theEnvironmentDictionary[environmentName] = MitigateEnvironmentProperties(environmentName) self.typeCombo.SetValue('') self.pointCombo.SetValue('') self.dmList.setEnvironment(environmentName) self.dmList.DeleteAllItems() self.environmentList.Select(self.theSelectedIdx) self.typeCombo.Enable() def OnDeleteEnvironment(self,evt): selectedIdx = evt.GetIndex() environmentName = self.environmentList.GetItemText(selectedIdx) del self.theEnvironmentDictionary[environmentName] self.theSelectedIdx = -1 def environmentProperties(self): if (self.theSelectedIdx != -1): environmentName = self.environmentList.GetItemText(self.theSelectedIdx) properties = MitigateEnvironmentProperties(environmentName,self.typeCombo.GetValue(),self.pointCombo.GetValue(),self.dmList.dimensions()) self.theEnvironmentDictionary[environmentName] = properties for cname in self.environmentList.dimensions(): p = self.theEnvironmentDictionary[cname] mitType = p.type() if (len(mitType) == 0): exceptionText = 'No mitigation type selected for environment ' + p.name() raise ARM.EnvironmentValidationError(exceptionText) if (mitType == 'Detect') and (len(p.detectionPoint()) == 0): exceptionText = 'No detection point selected for environment ' + p.name() raise ARM.EnvironmentValidationError(exceptionText) if (mitType == 'React') and (len(p.detectionMechanisms()) == 0): exceptionText = 'No detection mechanisms selected for environment ' + p.name() raise ARM.EnvironmentValidationError(exceptionText) return self.theEnvironmentDictionary.values() def setRisk(self,riskName): self.environmentList.setRisk(riskName) # encoding: utf-8 import tornado.ioloop import tornado.web import sys import getopt import time import re import ply.yacc as yacc from sa_lex import tokens from treetagger import TreeTagger from treetagger_wordnet import TreetaggerToWordnet from sentiwordnet import SentiWordnet import csv class MainHandler(tornado.web.RequestHandler): """ """ def initialize(self, to_wordnet, sentiwordnet, tt, rules, stopwords, chunks, language): """ """ self.rules = rules self.chunks = chunks self.language = language self.stopwords = stopwords self.sentiwordnet = sentiwordnet self.tt = tt self.to_wordnet = to_wordnet def get(self): """ """ # Start operation time time_start = time.time() # Prepare the response DS response = {} # Check input text text = self.get_argument("text") text = text.replace("\n", "") text = text.encode("utf-8") response["raw_text"] = text # Replace chunks symbols for chunk in self.chunks: text = text.replace(chunk, " # ") # Mapping treetagger postaging to wordnet postagging aux = "" for tag in self.tt.tag(text): lemma = tag[2] if lemma == u"": lemma = tag[0] aux += "%s.%s " % (lemma, self.to_wordnet.wordnet_morph_category(self.language, tag[1])) text = aux # Replace stopwords for the entities for stopword in self.stopwords: text = text.replace(stopword, " ") # Replace postagging for the entities aux = "" chunks = text.split(" ") for chunk in chunks: sub_chunks = chunk.split(".") if sub_chunks[0].lower() in entities or sub_chunks[0].lower() in inverters: aux += "%s " % sub_chunks[0].lower() else: aux += "%s " % chunk text = aux # Detecting Words with sentiment (Sentiwordnet) aux = "" chunks = text.split(" ") for chunk in chunks: aux += chunk sub_chunks = chunk.split(".") if len(sub_chunks) > 1: # Apply sentiwordnet dictionary senti = self.sentiwordnet.get_sentiment(sub_chunks[0], sub_chunks[1], language) # Calculate score score = 0.0 if senti is not None: score = float(senti["positive"]) + float(senti["negative"]) if score < 0.0: aux += "%s" % score elif score > 0.0: aux += "+%s" % score # Return keyword aux += " " text = aux response["text"] = text # Split input text chunks = text.split('#.None') triggered_rule_cont = 0 response["matches"] = {} for chunk in chunks: chunk =' '.join(chunk.split()) # Apply rules and replace matchs rule_triggered = False while True: # Appling all rules over the text rule_triggered = False for rule in compiled_rules: for match in compiled_rules[rule]["regex"].finditer(chunk): rule_triggered = True response["matches"][triggered_rule_cont] = {} response["matches"][triggered_rule_cont]["rule_triggered"] = rule response["matches"][triggered_rule_cont]["score"] = compiled_rules[rule]["score"] response["matches"][triggered_rule_cont]["match"] = match.group() # Replace chunk with "***"" filling aux = "" for e in match.group().split(" "): aux += "*" * len(e) + " " aux = aux[0:len(aux)-2] # Perfom replace chunk = chunk.replace(match.group(), aux) triggered_rule_cont += 1 # Break rule matching (precedence behavior) if not rule_triggered: break # Return response response["elipsed_time"] = time.time() - time_start # Return result self.write(response) # Variables to manage values in the parser process start = 'rule' regex = '' compiled_rules = {} adhoc_sentiwords = {} def p_rule(p): 'rule : BEGINRULE expression THEN SCORE ENDRULE' if p[1] in compiled_rules: print("Error: Rule #ID duplicated.") sys.exit(0) # Replace special character "#" and cast to integer # This is main to sort the rules dictionary and to # apply them in order rule_id = int(p[1].replace("#", "")) # Save rule compiled_rules[rule_id] = {} compiled_rules[rule_id]["regex"] = regex compiled_rules[rule_id]["score"] = float(p[4]) #print(regex.pattern) def p_expresion_simple_one(p): 'expression : QUALIFICATOR ENTITY' global regex if p[1] == "+": regex = re.compile("(\w+\.\w(\%s)(\d+.\d+)+)(\s\S+){0,3}\s%s" % (combined_positives, combined_entities)) else: regex = re.compile("(\w+\.\w(\%s)(\d+.\d+)+)(\s\S+){0,3}\s%s" % (combined_negatives, combined_entities)) def p_expresion_simple_two(p): 'expression : ENTITY QUALIFICATOR' global regex if p[2] == "+": regex = re.compile("%s(\s\S+){0,3}\s(\w+\.\w(\%s)(\d+.\d+)+)" % (combined_entities, combined_positives)) else: regex = re.compile("%s(\s\S+){0,3}\s(\w+\.\w(\%s)(\d+.\d+)+)" % (combined_entities, combined_negatives)) def p_expresion_simple_swaping_one(p): 'expression : SWAP QUALIFICATOR ENTITY' global regex if p[2] == "+": regex = re.compile("%s(\s\S+){0,3}\s(\w+\.\w(\%s)(\d+.\d+)+)(\s\S+){0,3}\s%s" % (combined_inverters, combined_positives, combined_entities)) else: regex = re.compile("%s(\s\S+){0,3}\s(\w+\.\w(\%s)(\d+.\d+)+)(\s\S+){0,3}\s%s" % (combined_inverters, combined_negatives, combined_entities)) def p_expresion_simple_swaping_two(p): 'expression : ENTITY SWAP QUALIFICATOR' global regex if p[3] == "+": regex = re.compile("%s(\s\S+){0,3}\s%s(\s\S+){0,3}\s(\w+\.\w(\%s)(\d+.\d+)+)" % (combined_entities, combined_inverters, combined_positives)) else: regex = re.compile("%s(\s\S+){0,3}\s%s(\s\S+){0,3}\s(\w+\.\w(\%s)(\d+.\d+)+)" % (combined_entities, combined_inverters, combined_negatives)) # print(regex.pattern) def p_expresion_adhoc_one(p): 'expression : ENTITY IDENTIFICATOR' global regex regex = re.compile("%s(\s\S+){0,3}\s(%s)" % (combined_entities, p[2])) def p_expresion_adhoc_two(p): 'expression : IDENTIFICATOR ENTITY' global regex regex = re.compile("(%s)(\s\S+){0,3}\s%s" % (p[1], combined_entities)) # Error rule for syntax errors def p_error(p): print ">>> %s" % p print "Syntax error in input!" sys.exit(0) def load_dict(file_path): """ Load files from disk into variables """ aux = [] f_in = open(file_path, "r") tsv_reader = csv.reader(f_in, delimiter='\t') for row in tsv_reader: aux.append(row[0]) return aux # Check if parameters are valid try: opts, args = getopt.getopt(sys.argv[1:], "l:p:", ["language=","port="]) assert(len(opts) == 2) except: print 'sentiment_Service.py -l -p ' sys.exit() for o, a in opts: if o == "-l": language = a if language not in ["spanish", "english"]: print 'Valid languages: spanish, english' sys.exit() elif o == "-p": port = a else: pass # Load dicts into global variables print("Loading Negative and positive constants:") positive = load_dict("dict/positive.tsv") assert(len(positive) == 1) combined_positives = positive[0] negative = load_dict("dict/negative.tsv") combined_negatives = negative[0] assert(len(negative) == 1) print("...loaded.") print("\n") print("Loading dicts:") entities = load_dict("dict/entities.tsv") combined_entities = "(%s)" % "|".join(entities) print("\t%s entities terms loaded" % len(entities)) inverters = load_dict("dict/inverters.tsv") combined_inverters = "(%s)" % "|".join(inverters) print("\t%s inverters terms loaded" % len(inverters)) chunks = load_dict("dict/chunks.tsv") print("\t%s chunks loaded" % len(chunks)) stopwords = load_dict("data/stopwords.tsv") print("\t%s stopwords loaded" % len(stopwords)) # Read the rules from the file rules = [] for line in open("dict/rules.tsv", "r"): line = line.replace("\n", "") line = line.replace("\r", "") rules.append(line) # Build the parser, and parse rules parser = yacc.yacc() print ("\nLoading rules:") for rule in rules: result = parser.parse(rule) print("\tRule parsed succesfully: %s" % rule) tt = TreeTagger(encoding='latin-1', language=language) sentiwordnet = SentiWordnet() to_wordnet = TreetaggerToWordnet() # Init Tornado web server application = tornado.web.Application([ (r"/", MainHandler, dict(rules = compiled_rules, to_wordnet = to_wordnet, sentiwordnet = sentiwordnet, tt = tt, stopwords = stopwords, chunks = chunks, language = language)), ]) # Listen on specific port and start server application.listen(port) tornado.ioloop.IOLoop.instance().start() # -*- coding: utf-8 -*- # # tsodyks_depressing.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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. # # NEST 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 NEST. If not, see . ''' /* BeginDocumentation Name: tsodyks_depressing - python script for overall test of iaf_neuron model Derived from tsodyks_depressing.sli. Description: Script to test Tsodyks short term plasticity depressing synapses according to 'Neural Networks with Dynamic Synapses' Misha Tsodyks, Klaus Pawelzik, Henry Markram Neural computation 10, 821--853 (1998) reproduces figure 1 A author: Birgit Kriener, Moritz Helias, Markus Diesmann date: March 2006 ''' # import nest kernel: import nest import nest.voltage_trace from numpy import exp import pylab # set parameters: h = 0.1 # simulation step size (ms) Tau = 40. # membrane time constant Theta = 15. # threshold U0 = 0. # reset potential of membrane potential R = 0.1 # 100 M Ohm C = Tau/R # Tau (ms)/R in NEST units TauR = 2. # refractory time Tau_psc = 3. # time constant of PSC (= Tau_inact) Tau_rec = 800. # recovery time Tau_fac = 0. # facilitation time U = 0.5 # facilitation parameter U A = 250. # PSC weight in pA f = 20./1000. # frequency in Hz converted to 1/ms Tend = 1200. # simulation time TIstart = 50. # start time of dc TIend = 1050. # end time of dc I0 = Theta*C/Tau/(1-exp(-(1/f-TauR)/Tau)) # dc amplitude # print I0 # set up simulator: nest.ResetKernel() nest.SetKernelStatus({"resolution": h}) # set neuron parameters: neuron_param = {"tau_m" : Tau, "t_ref" : TauR, "tau_syn_ex": Tau_psc, "tau_syn_in": Tau_psc, "C_m" : C, "V_reset" : U0, "E_L" : U0, "V_m" : U0, "V_th" : Theta} # set defaults of desired neuron type with chosen parameters: nest.SetDefaults("iaf_psc_exp", neuron_param) # create two neurons of desired type: neurons = nest.Create("iaf_psc_exp",2) # set properties of dc: nest.SetDefaults("dc_generator",{"amplitude": I0, "start": TIstart, "stop": TIend}) # create dc_generator: dc_gen = nest.Create("dc_generator") # create voltmeter volts=nest.Create("voltmeter") # set properties of voltmeter nest.SetStatus(volts,[{"label": "Voltmeter", "withtime": True, "withgid": True, "interval": 1.}]) # connect dc_generator to neuron 1: nest.Connect(dc_gen,[neurons[0]]) # connect voltmeter to neuron 2: nest.Connect(volts,[neurons[1]]) # set synapse parameters: syn_param = {"tau_psc" : Tau_psc, "tau_rec" : Tau_rec, "tau_fac" : Tau_fac, "U" : U, "delay" : 0.1, "weight" : A, "u" : 0.0, "x" : 1.0} # create desired synapse type with chosen parameters: nest.CopyModel("tsodyks_synapse","syn",syn_param) # connect neuron 1 with neuron 2 via synapse model 'syn': nest.Connect([neurons[0]],[neurons[1]],syn_spec={'model': "syn"}) # simulate: nest.Simulate(Tend) # plot membrane potential of neuron nest.voltage_trace.from_device(volts) from urlparse import urlparse from django.contrib.sites.models import Site import mock import waffle from nose.tools import eq_ from kitsune.inproduct.tests import redirect from kitsune.sumo.tests import TestCase class RedirectTestCase(TestCase): test_urls = ( ('firefox/3.6.12/WINNT/en-US/', '/en-US/'), ('mobile/4.0/Android/en-US/', '/en-US/products/mobile'), ('firefox/3.6.12/MACOSX/en-US', '/en-US/'), ('firefox/3.6.12/WINNT/fr/', '/fr/'), ('firefox/3.6.12/WINNT/fr-FR/', '/fr/'), ('firefox-home/1.1/iPhone/en-US/', '/en-US/'), ('firefox/4.0/Linux/en-US/prefs-applications', '/en-US/kb/Applications'), ('firefox/4.0/Linux/en-US/prefs-applications/', '/en-US/kb/Applications'), ('firefox/5.0/NONE/en-US/', '/en-US/does-not-exist'), ('mobile/4.0/MARTIAN/en-US/', 'http://martian.com'), ('mobile/4.0/martian/en-US/', 'http://martian.com'), ('firefox/4.0/Android/en-US/foo', 404), # Make sure Basque doesn't trigger the EU ballot logic. ('firefox/29.0/Darwin/eu/', '/eu/'), ('firefox/29.0/Darwin/eu', '/eu/'), ) test_eu_urls = ( ('firefox/3.6.12/WINNT/en-US/eu/', '/en-US/'), ('mobile/4.0/Android/en-US/eu/', '/en-US/products/mobile'), ('firefox/3.6.12/MACOSX/en-US/eu', '/en-US/'), ('firefox/3.6.12/WINNT/fr/eu/', '/fr/'), ('firefox/3.6.12/WINNT/fr-FR/eu/', '/fr/'), ('firefox-home/1.1/iPhone/en-US/eu/', '/en-US/'), ('firefox/4.0/Linux/en-US/eu/prefs-applications', '/en-US/kb/Applications'), ('firefox/4.0/Linux/en-US/eu/prefs-applications/', '/en-US/kb/Applications'), ('firefox/5.0/NONE/en-US/eu/', '/en-US/does-not-exist'), ('mobile/4.0/MARTIAN/en-US/eu/', 'http://martian.com'), ('mobile/4.0/martian/en-US/eu/', 'http://martian.com'), ('firefox/4.0/Android/en-US/eu/foo', 404), # Basque is awesome. ('firefox/30.0/WINNT/eu/eu/', '/eu/'), ('firefox/4.0/Linux/eu/eu/prefs-applications', '/eu/kb/Applications'), ) def setUp(self): super(RedirectTestCase, self).setUp() # Create redirects to test with. redirect(target='kb/Applications', topic='prefs-applications', save=True) redirect(target='', save=True) redirect(product='mobile', target='products/mobile', save=True) redirect(platform='iPhone', target='', save=True) redirect(product='mobile', platform='Android', topic='foo', target='', save=True) redirect(version='5.0', target='does-not-exist', save=True) redirect(platform='martian', target='http://martian.com', save=True) def test_target(self): """Test that we can vary on any parameter and targets work.""" self._targets(self.test_urls, 'as=u&utm_source=inproduct') def test_eu_target(self): """Test that all URLs work with the extra 'eu'.""" self._targets(self.test_eu_urls, 'eu=1&as=u&utm_source=inproduct') def _targets(self, urls, querystring): for input, output in urls: response = self.client.get(u'/1/%s' % input, follow=True) if output == 404: eq_(404, response.status_code) elif output.startswith('http'): chain = [u[0] for u in response.redirect_chain] assert output in chain else: r = response.redirect_chain r.reverse() final = urlparse(r[0][0]) eq_(output, final.path) eq_(querystring, final.query) @mock.patch.object(Site.objects, 'get_current') @mock.patch.object(waffle, 'sample_is_active') def test_switch_to_https(self, sample_is_active, get_current): """Verify we switch to https when sample is active.""" get_current.return_value.domain = 'example.com' sample_is_active.return_value = True response = self.client.get( u'/1/firefox/4.0/Linux/en-US/prefs-applications') eq_(302, response.status_code) assert response['location'].startswith('https://example.com/') # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not 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 six.moves.urllib import parse as urlparse from st2common.util import isotime from st2common.util.jsonify import json_encode from st2common.exceptions import auth as exceptions from st2common import log as logging from st2common.util.auth import validate_token from st2common.constants.auth import QUERY_PARAM_ATTRIBUTE_NAME LOG = logging.getLogger(__name__) # HTTP header name format (i.e. 'X-Auth-Token') # WSGI environment variable name format (ex. 'HTTP_X_AUTH_TOKEN') HEADERS = ['HTTP_X_AUTH_TOKEN_EXPIRY', 'HTTP_X_USER_NAME'] class AuthMiddleware(object): """WSGI middleware to handle authentication""" def __init__(self, app): self.app = app def __call__(self, environ, start_response): try: self._remove_auth_headers(environ) token = self._validate_token(environ) self._add_auth_headers(environ, token) except exceptions.TokenNotProvidedError: LOG.exception('Token is not provided.') return self._abort_unauthorized(environ, start_response) except exceptions.TokenNotFoundError: LOG.exception('Token is not found.') return self._abort_unauthorized(environ, start_response) except exceptions.TokenExpiredError: LOG.exception('Token has expired.') return self._abort_unauthorized(environ, start_response) except Exception: LOG.exception('Unexpected exception.') return self._abort_other_errors(environ, start_response) else: return self.app(environ, start_response) def _abort_other_errors(self, environ, start_response): body = json_encode({ 'faultstring': 'Internal Server Error' }) headers = [('Content-Type', 'application/json')] start_response('500 INTERNAL SERVER ERROR', headers) return [body] def _abort_unauthorized(self, environ, start_response): body = json_encode({ 'faultstring': 'Unauthorized' }) headers = [('Content-Type', 'application/json')] start_response('401 UNAUTHORIZED', headers) return [body] def _remove_auth_headers(self, env): """Remove middleware generated auth headers to prevent user from supplying them.""" headers_found = [k for k in HEADERS if k in env] for header in headers_found: del env[header] def _validate_token(self, env): """Validate token""" query_string = env.get('QUERY_STRING', '') query_params = dict(urlparse.parse_qsl(query_string)) # Note: This is a WSGI environment variable name token_in_headers = env.get('HTTP_X_AUTH_TOKEN', None) token_in_query_params = query_params.get(QUERY_PARAM_ATTRIBUTE_NAME, None) return validate_token(token_in_headers=token_in_headers, token_in_query_params=token_in_query_params) def _add_auth_headers(self, env, token): """Write authenticated user data to headers Build headers that represent authenticated user: * HTTP_X_AUTH_TOKEN_EXPIRY: Token expiration datetime * HTTP_X_USER_NAME: Name of confirmed user """ env['HTTP_X_AUTH_TOKEN_EXPIRY'] = isotime.format(token.expiry) env['HTTP_X_USER_NAME'] = str(token.user) import os from .. import constants, logger from . import ( base_classes, texture, material, geometry, object as object_, utilities, io, api ) class Scene(base_classes.BaseScene): """Class that handles the contruction of a Three scene""" _defaults = { constants.METADATA: constants.DEFAULT_METADATA.copy(), constants.GEOMETRIES: [], constants.MATERIALS: [], constants.IMAGES: [], constants.TEXTURES: [] } def __init__(self, filepath, options=None): logger.debug("Scene().__init__(%s, %s)", filepath, options) base_classes.BaseScene.__init__(self, filepath, options or {}) source_file = api.scene_name() if source_file: self[constants.METADATA][constants.SOURCE_FILE] = source_file @property def valid_types(self): """ :return: list of valid node types """ valid_types = [api.constants.MESH] if self.options.get(constants.HIERARCHY, False): valid_types.append(api.constants.EMPTY) if self.options.get(constants.CAMERAS): logger.info("Adding cameras to valid object types") valid_types.append(api.constants.CAMERA) if self.options.get(constants.LIGHTS): logger.info("Adding lights to valid object types") valid_types.append(api.constants.LAMP) return valid_types def geometry(self, value): """Find a geometry node that matches either a name or uuid value. :param value: name or uuid :type value: str """ logger.debug("Scene().geometry(%s)", value) return _find_node(value, self[constants.GEOMETRIES]) def image(self, value): """Find a image node that matches either a name or uuid value. :param value: name or uuid :type value: str """ logger.debug("Scene().image%s)", value) return _find_node(value, self[constants.IMAGES]) def material(self, value): """Find a material node that matches either a name or uuid value. :param value: name or uuid :type value: str """ logger.debug("Scene().material(%s)", value) return _find_node(value, self[constants.MATERIALS]) def parse(self): """Execute the parsing of the scene""" logger.debug("Scene().parse()") if self.options.get(constants.MAPS): self._parse_textures() if self.options.get(constants.MATERIALS): self._parse_materials() self._parse_geometries() self._parse_objects() def texture(self, value): """Find a texture node that matches either a name or uuid value. :param value: name or uuid :type value: str """ logger.debug("Scene().texture(%s)", value) return _find_node(value, self[constants.TEXTURES]) def write(self): """Write the parsed scene to disk.""" logger.debug("Scene().write()") data = {} embed_anim = self.options.get(constants.EMBED_ANIMATION, True) embed = self.options.get(constants.EMBED_GEOMETRY, True) compression = self.options.get(constants.COMPRESSION) extension = constants.EXTENSIONS.get( compression, constants.EXTENSIONS[constants.JSON]) export_dir = os.path.dirname(self.filepath) for key, value in self.items(): if key == constants.GEOMETRIES: geometries = [] for geom in value: if not embed_anim: geom.write_animation(export_dir) geom_data = geom.copy() if embed: geometries.append(geom_data) continue geo_type = geom_data[constants.TYPE].lower() if geo_type == constants.GEOMETRY.lower(): geom_data.pop(constants.DATA) elif geo_type == constants.BUFFER_GEOMETRY.lower(): geom_data.pop(constants.ATTRIBUTES) geom_data.pop(constants.METADATA) url = 'geometry.%s%s' % (geom.node, extension) geometry_file = os.path.join(export_dir, url) geom.write(filepath=geometry_file) geom_data[constants.URL] = os.path.basename(url) geometries.append(geom_data) data[key] = geometries elif isinstance(value, list): data[key] = [] for each in value: data[key].append(each.copy()) elif isinstance(value, dict): data[key] = value.copy() io.dump(self.filepath, data, options=self.options) if self.options.get(constants.COPY_TEXTURES): texture_folder = self.options.get(constants.TEXTURE_FOLDER) for geo in self[constants.GEOMETRIES]: logger.info("Copying textures from %s", geo.node) geo.copy_textures(texture_folder) def _parse_geometries(self): """Locate all geometry nodes and parse them""" logger.debug("Scene()._parse_geometries()") # this is an important step. please refer to the doc string # on the function for more information api.object.prep_meshes(self.options) geometries = [] # now iterate over all the extracted mesh nodes and parse each one for mesh in api.object.extracted_meshes(): logger.info("Parsing geometry %s", mesh) geo = geometry.Geometry(mesh, self) geo.parse() geometries.append(geo) logger.info("Added %d geometry nodes", len(geometries)) self[constants.GEOMETRIES] = geometries def _parse_materials(self): """Locate all non-orphaned materials and parse them""" logger.debug("Scene()._parse_materials()") materials = [] for material_name in api.material.used_materials(): logger.info("Parsing material %s", material_name) materials.append(material.Material(material_name, parent=self)) logger.info("Added %d material nodes", len(materials)) self[constants.MATERIALS] = materials def _parse_objects(self): """Locate all valid objects in the scene and parse them""" logger.debug("Scene()._parse_objects()") try: scene_name = self[constants.METADATA][constants.SOURCE_FILE] except KeyError: scene_name = constants.SCENE self[constants.OBJECT] = object_.Object(None, parent=self) self[constants.OBJECT][constants.TYPE] = constants.SCENE.title() self[constants.UUID] = utilities.id_from_name(scene_name) objects = [] if self.options.get(constants.HIERARCHY, False): nodes = api.object.assemblies(self.valid_types, self.options) else: nodes = api.object.nodes(self.valid_types, self.options) for node in nodes: logger.info("Parsing object %s", node) obj = object_.Object(node, parent=self[constants.OBJECT]) objects.append(obj) logger.info("Added %d object nodes", len(objects)) self[constants.OBJECT][constants.CHILDREN] = objects def _parse_textures(self): """Locate all non-orphaned textures and parse them""" logger.debug("Scene()._parse_textures()") textures = [] for texture_name in api.texture.textures(): logger.info("Parsing texture %s", texture_name) tex_inst = texture.Texture(texture_name, self) textures.append(tex_inst) logger.info("Added %d texture nodes", len(textures)) self[constants.TEXTURES] = textures def _find_node(value, manifest): """Find a node that matches either a name or uuid value. :param value: name or uuid :param manifest: manifest of nodes to search :type value: str :type manifest: list """ for index in manifest: uuid = index.get(constants.UUID) == value name = index.node == value if uuid or name: return index else: logger.debug("No matching node for %s", value) #!/usr/bin/env python3 import os import json import sys from io import open from time import time from shutil import rmtree from collections import OrderedDict if len(sys.argv) == 1 or not sys.argv[1]: raise SystemExit('Build dir missing.') def mkdirs(path): try: os.makedirs(path) finally: return os.path.exists(path) pj = os.path.join build_dir = os.path.abspath(sys.argv[1]) description = '' # locales locale_dir = pj(build_dir, '_locales') for alpha2 in sorted(os.listdir(locale_dir)): locale_path = pj(locale_dir, alpha2, 'messages.json') with open(locale_path, encoding='utf-8') as f: string_data = json.load(f, object_pairs_hook=OrderedDict) if alpha2 == 'en': description = string_data['extShortDesc']['message'] for string_name in string_data: string_data[string_name] = string_data[string_name]['message'] rmtree(pj(locale_dir, alpha2)) alpha2 = alpha2.replace('_', '-') locale_path = pj(locale_dir, alpha2 + '.json') mkdirs(pj(locale_dir)) with open(locale_path, 'wb') as f: f.write(json.dumps(string_data, ensure_ascii=False).encode('utf8')) # update Info.plist proj_dir = pj(os.path.split(os.path.abspath(__file__))[0], '..') chromium_manifest = pj(proj_dir, 'platform', 'chromium', 'manifest.json') with open(chromium_manifest, encoding='utf-8') as m: manifest = json.load(m) manifest['buildNumber'] = int(time()) manifest['description'] = description info_plist = pj(build_dir, 'Info.plist') with open(info_plist, 'r+t', encoding='utf-8', newline='\n') as f: info_plist = f.read() f.seek(0) f.write(info_plist.format(**manifest)) # update Update.plist update_plist = pj(proj_dir, 'platform', 'safari', 'Update.plist') update_plist_build = pj(build_dir, '..', os.path.basename(update_plist)) with open(update_plist_build, 'wt', encoding='utf-8', newline='\n') as f: with open(update_plist, encoding='utf-8') as u: update_plist = u.read() f.write(update_plist.format(**manifest)) # -*- coding: utf-8 -*- """ *************************************************************************** ProcessingLog.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' import os import codecs import datetime from processing.tools.system import userFolder from processing.core.ProcessingConfig import ProcessingConfig from qgis.PyQt.QtCore import QCoreApplication LOG_SEPARATOR = '|~|' class ProcessingLog: DATE_FORMAT = "%Y-%m-%d %H:%M:%S" @staticmethod def logFilename(): logFilename = userFolder() + os.sep + 'processing.log' if not os.path.isfile(logFilename): with codecs.open(logFilename, 'w', encoding='utf-8') as logfile: logfile.write('Started logging at ' + datetime.datetime.now().strftime(ProcessingLog.DATE_FORMAT) + '\n') return logFilename @staticmethod def addToLog(msg): try: # It seems that this fails sometimes depending on the msg # added. To avoid it stopping the normal functioning of the # algorithm, we catch all errors, assuming that is better # to miss some log info than breaking the algorithm. line = 'ALGORITHM' + LOG_SEPARATOR + datetime.datetime.now().strftime( ProcessingLog.DATE_FORMAT) + LOG_SEPARATOR \ + msg + '\n' with codecs.open(ProcessingLog.logFilename(), 'a', encoding='utf-8') as logfile: logfile.write(line) except: pass @staticmethod def getLogEntries(): entries = [] with open(ProcessingLog.logFilename(), encoding='utf-8') as f: lines = f.readlines() for line in lines: line = line.strip('\n').strip() tokens = line.split(LOG_SEPARATOR) if len(tokens) <= 1: # try old format log separator tokens = line.split('|') text = ''.join( tokens[i] + LOG_SEPARATOR for i in range(2, len(tokens)) ) if line.startswith('ALGORITHM'): entries.append(LogEntry(tokens[1], tokens[2])) return entries @staticmethod def clearLog(): os.unlink(ProcessingLog.logFilename()) @staticmethod def saveLog(fileName): entries = ProcessingLog.getLogEntries() with codecs.open(fileName, 'w', encoding='utf-8') as f: for entry in entries: f.write('ALGORITHM{}{}{}{}\n'.format(LOG_SEPARATOR, entry.date, LOG_SEPARATOR, entry.text)) @staticmethod def tr(string, context=''): if context == '': context = 'ProcessingLog' return QCoreApplication.translate(context, string) class LogEntry: def __init__(self, date, text): self.date = date self.text = text #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # 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 copyright holder 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. """ Wrapper for gdi32.dll in ctypes. """ __revision__ = "$Id$" from winappdbg.win32.defines import * from winappdbg.win32.kernel32 import GetLastError, SetLastError #============================================================================== # This is used later on to calculate the list of exported symbols. _all = None _all = set(vars().keys()) #============================================================================== #--- Helpers ------------------------------------------------------------------ #--- Types -------------------------------------------------------------------- #--- Constants ---------------------------------------------------------------- # GDI object types OBJ_PEN = 1 OBJ_BRUSH = 2 OBJ_DC = 3 OBJ_METADC = 4 OBJ_PAL = 5 OBJ_FONT = 6 OBJ_BITMAP = 7 OBJ_REGION = 8 OBJ_METAFILE = 9 OBJ_MEMDC = 10 OBJ_EXTPEN = 11 OBJ_ENHMETADC = 12 OBJ_ENHMETAFILE = 13 OBJ_COLORSPACE = 14 GDI_OBJ_LAST = OBJ_COLORSPACE # Ternary raster operations SRCCOPY = 0x00CC0020 # dest = source SRCPAINT = 0x00EE0086 # dest = source OR dest SRCAND = 0x008800C6 # dest = source AND dest SRCINVERT = 0x00660046 # dest = source XOR dest SRCERASE = 0x00440328 # dest = source AND (NOT dest) NOTSRCCOPY = 0x00330008 # dest = (NOT source) NOTSRCERASE = 0x001100A6 # dest = (NOT src) AND (NOT dest) MERGECOPY = 0x00C000CA # dest = (source AND pattern) MERGEPAINT = 0x00BB0226 # dest = (NOT source) OR dest PATCOPY = 0x00F00021 # dest = pattern PATPAINT = 0x00FB0A09 # dest = DPSnoo PATINVERT = 0x005A0049 # dest = pattern XOR dest DSTINVERT = 0x00550009 # dest = (NOT dest) BLACKNESS = 0x00000042 # dest = BLACK WHITENESS = 0x00FF0062 # dest = WHITE NOMIRRORBITMAP = 0x80000000 # Do not Mirror the bitmap in this call CAPTUREBLT = 0x40000000 # Include layered windows # Region flags ERROR = 0 NULLREGION = 1 SIMPLEREGION = 2 COMPLEXREGION = 3 RGN_ERROR = ERROR # CombineRgn() styles RGN_AND = 1 RGN_OR = 2 RGN_XOR = 3 RGN_DIFF = 4 RGN_COPY = 5 RGN_MIN = RGN_AND RGN_MAX = RGN_COPY # StretchBlt() modes BLACKONWHITE = 1 WHITEONBLACK = 2 COLORONCOLOR = 3 HALFTONE = 4 MAXSTRETCHBLTMODE = 4 STRETCH_ANDSCANS = BLACKONWHITE STRETCH_ORSCANS = WHITEONBLACK STRETCH_DELETESCANS = COLORONCOLOR STRETCH_HALFTONE = HALFTONE # PolyFill() modes ALTERNATE = 1 WINDING = 2 POLYFILL_LAST = 2 # Layout orientation options LAYOUT_RTL = 0x00000001 # Right to left LAYOUT_BTT = 0x00000002 # Bottom to top LAYOUT_VBH = 0x00000004 # Vertical before horizontal LAYOUT_ORIENTATIONMASK = LAYOUT_RTL + LAYOUT_BTT + LAYOUT_VBH LAYOUT_BITMAPORIENTATIONPRESERVED = 0x00000008 # Stock objects WHITE_BRUSH = 0 LTGRAY_BRUSH = 1 GRAY_BRUSH = 2 DKGRAY_BRUSH = 3 BLACK_BRUSH = 4 NULL_BRUSH = 5 HOLLOW_BRUSH = NULL_BRUSH WHITE_PEN = 6 BLACK_PEN = 7 NULL_PEN = 8 OEM_FIXED_FONT = 10 ANSI_FIXED_FONT = 11 ANSI_VAR_FONT = 12 SYSTEM_FONT = 13 DEVICE_DEFAULT_FONT = 14 DEFAULT_PALETTE = 15 SYSTEM_FIXED_FONT = 16 # Metafile functions META_SETBKCOLOR = 0x0201 META_SETBKMODE = 0x0102 META_SETMAPMODE = 0x0103 META_SETROP2 = 0x0104 META_SETRELABS = 0x0105 META_SETPOLYFILLMODE = 0x0106 META_SETSTRETCHBLTMODE = 0x0107 META_SETTEXTCHAREXTRA = 0x0108 META_SETTEXTCOLOR = 0x0209 META_SETTEXTJUSTIFICATION = 0x020A META_SETWINDOWORG = 0x020B META_SETWINDOWEXT = 0x020C META_SETVIEWPORTORG = 0x020D META_SETVIEWPORTEXT = 0x020E META_OFFSETWINDOWORG = 0x020F META_SCALEWINDOWEXT = 0x0410 META_OFFSETVIEWPORTORG = 0x0211 META_SCALEVIEWPORTEXT = 0x0412 META_LINETO = 0x0213 META_MOVETO = 0x0214 META_EXCLUDECLIPRECT = 0x0415 META_INTERSECTCLIPRECT = 0x0416 META_ARC = 0x0817 META_ELLIPSE = 0x0418 META_FLOODFILL = 0x0419 META_PIE = 0x081A META_RECTANGLE = 0x041B META_ROUNDRECT = 0x061C META_PATBLT = 0x061D META_SAVEDC = 0x001E META_SETPIXEL = 0x041F META_OFFSETCLIPRGN = 0x0220 META_TEXTOUT = 0x0521 META_BITBLT = 0x0922 META_STRETCHBLT = 0x0B23 META_POLYGON = 0x0324 META_POLYLINE = 0x0325 META_ESCAPE = 0x0626 META_RESTOREDC = 0x0127 META_FILLREGION = 0x0228 META_FRAMEREGION = 0x0429 META_INVERTREGION = 0x012A META_PAINTREGION = 0x012B META_SELECTCLIPREGION = 0x012C META_SELECTOBJECT = 0x012D META_SETTEXTALIGN = 0x012E META_CHORD = 0x0830 META_SETMAPPERFLAGS = 0x0231 META_EXTTEXTOUT = 0x0a32 META_SETDIBTODEV = 0x0d33 META_SELECTPALETTE = 0x0234 META_REALIZEPALETTE = 0x0035 META_ANIMATEPALETTE = 0x0436 META_SETPALENTRIES = 0x0037 META_POLYPOLYGON = 0x0538 META_RESIZEPALETTE = 0x0139 META_DIBBITBLT = 0x0940 META_DIBSTRETCHBLT = 0x0b41 META_DIBCREATEPATTERNBRUSH = 0x0142 META_STRETCHDIB = 0x0f43 META_EXTFLOODFILL = 0x0548 META_SETLAYOUT = 0x0149 META_DELETEOBJECT = 0x01f0 META_CREATEPALETTE = 0x00f7 META_CREATEPATTERNBRUSH = 0x01F9 META_CREATEPENINDIRECT = 0x02FA META_CREATEFONTINDIRECT = 0x02FB META_CREATEBRUSHINDIRECT = 0x02FC META_CREATEREGION = 0x06FF # Metafile escape codes NEWFRAME = 1 ABORTDOC = 2 NEXTBAND = 3 SETCOLORTABLE = 4 GETCOLORTABLE = 5 FLUSHOUTPUT = 6 DRAFTMODE = 7 QUERYESCSUPPORT = 8 SETABORTPROC = 9 STARTDOC = 10 ENDDOC = 11 GETPHYSPAGESIZE = 12 GETPRINTINGOFFSET = 13 GETSCALINGFACTOR = 14 MFCOMMENT = 15 GETPENWIDTH = 16 SETCOPYCOUNT = 17 SELECTPAPERSOURCE = 18 DEVICEDATA = 19 PASSTHROUGH = 19 GETTECHNOLGY = 20 GETTECHNOLOGY = 20 SETLINECAP = 21 SETLINEJOIN = 22 SETMITERLIMIT = 23 BANDINFO = 24 DRAWPATTERNRECT = 25 GETVECTORPENSIZE = 26 GETVECTORBRUSHSIZE = 27 ENABLEDUPLEX = 28 GETSETPAPERBINS = 29 GETSETPRINTORIENT = 30 ENUMPAPERBINS = 31 SETDIBSCALING = 32 EPSPRINTING = 33 ENUMPAPERMETRICS = 34 GETSETPAPERMETRICS = 35 POSTSCRIPT_DATA = 37 POSTSCRIPT_IGNORE = 38 MOUSETRAILS = 39 GETDEVICEUNITS = 42 GETEXTENDEDTEXTMETRICS = 256 GETEXTENTTABLE = 257 GETPAIRKERNTABLE = 258 GETTRACKKERNTABLE = 259 EXTTEXTOUT = 512 GETFACENAME = 513 DOWNLOADFACE = 514 ENABLERELATIVEWIDTHS = 768 ENABLEPAIRKERNING = 769 SETKERNTRACK = 770 SETALLJUSTVALUES = 771 SETCHARSET = 772 STRETCHBLT = 2048 METAFILE_DRIVER = 2049 GETSETSCREENPARAMS = 3072 QUERYDIBSUPPORT = 3073 BEGIN_PATH = 4096 CLIP_TO_PATH = 4097 END_PATH = 4098 EXT_DEVICE_CAPS = 4099 RESTORE_CTM = 4100 SAVE_CTM = 4101 SET_ARC_DIRECTION = 4102 SET_BACKGROUND_COLOR = 4103 SET_POLY_MODE = 4104 SET_SCREEN_ANGLE = 4105 SET_SPREAD = 4106 TRANSFORM_CTM = 4107 SET_CLIP_BOX = 4108 SET_BOUNDS = 4109 SET_MIRROR_MODE = 4110 OPENCHANNEL = 4110 DOWNLOADHEADER = 4111 CLOSECHANNEL = 4112 POSTSCRIPT_PASSTHROUGH = 4115 ENCAPSULATED_POSTSCRIPT = 4116 POSTSCRIPT_IDENTIFY = 4117 POSTSCRIPT_INJECTION = 4118 CHECKJPEGFORMAT = 4119 CHECKPNGFORMAT = 4120 GET_PS_FEATURESETTING = 4121 GDIPLUS_TS_QUERYVER = 4122 GDIPLUS_TS_RECORD = 4123 SPCLPASSTHROUGH2 = 4568 #--- Structures --------------------------------------------------------------- # typedef struct _RECT { # LONG left; # LONG top; # LONG right; # LONG bottom; # }RECT, *PRECT; class RECT(Structure): _fields_ = [ ('left', LONG), ('top', LONG), ('right', LONG), ('bottom', LONG), ] PRECT = POINTER(RECT) LPRECT = PRECT # typedef struct tagPOINT { # LONG x; # LONG y; # } POINT; class POINT(Structure): _fields_ = [ ('x', LONG), ('y', LONG), ] PPOINT = POINTER(POINT) LPPOINT = PPOINT # typedef struct tagBITMAP { # LONG bmType; # LONG bmWidth; # LONG bmHeight; # LONG bmWidthBytes; # WORD bmPlanes; # WORD bmBitsPixel; # LPVOID bmBits; # } BITMAP, *PBITMAP; class BITMAP(Structure): _fields_ = [ ("bmType", LONG), ("bmWidth", LONG), ("bmHeight", LONG), ("bmWidthBytes", LONG), ("bmPlanes", WORD), ("bmBitsPixel", WORD), ("bmBits", LPVOID), ] PBITMAP = POINTER(BITMAP) LPBITMAP = PBITMAP #--- High level classes ------------------------------------------------------- #--- gdi32.dll ---------------------------------------------------------------- # HDC GetDC( # __in HWND hWnd # ); def GetDC(hWnd): _GetDC = windll.gdi32.GetDC _GetDC.argtypes = [HWND] _GetDC.restype = HDC _GetDC.errcheck = RaiseIfZero return _GetDC(hWnd) # HDC GetWindowDC( # __in HWND hWnd # ); def GetWindowDC(hWnd): _GetWindowDC = windll.gdi32.GetWindowDC _GetWindowDC.argtypes = [HWND] _GetWindowDC.restype = HDC _GetWindowDC.errcheck = RaiseIfZero return _GetWindowDC(hWnd) # int ReleaseDC( # __in HWND hWnd, # __in HDC hDC # ); def ReleaseDC(hWnd, hDC): _ReleaseDC = windll.gdi32.ReleaseDC _ReleaseDC.argtypes = [HWND, HDC] _ReleaseDC.restype = ctypes.c_int _ReleaseDC.errcheck = RaiseIfZero _ReleaseDC(hWnd, hDC) # HGDIOBJ SelectObject( # __in HDC hdc, # __in HGDIOBJ hgdiobj # ); def SelectObject(hdc, hgdiobj): _SelectObject = windll.gdi32.SelectObject _SelectObject.argtypes = [HDC, HGDIOBJ] _SelectObject.restype = HGDIOBJ _SelectObject.errcheck = RaiseIfZero return _SelectObject(hdc, hgdiobj) # HGDIOBJ GetStockObject( # __in int fnObject # ); def GetStockObject(fnObject): _GetStockObject = windll.gdi32.GetStockObject _GetStockObject.argtypes = [ctypes.c_int] _GetStockObject.restype = HGDIOBJ _GetStockObject.errcheck = RaiseIfZero return _GetStockObject(fnObject) # DWORD GetObjectType( # __in HGDIOBJ h # ); def GetObjectType(h): _GetObjectType = windll.gdi32.GetObjectType _GetObjectType.argtypes = [HGDIOBJ] _GetObjectType.restype = DWORD _GetObjectType.errcheck = RaiseIfZero return _GetObjectType(h) # int GetObject( # __in HGDIOBJ hgdiobj, # __in int cbBuffer, # __out LPVOID lpvObject # ); def GetObject(hgdiobj, cbBuffer = None, lpvObject = None): _GetObject = windll.gdi32.GetObject _GetObject.argtypes = [HGDIOBJ, ctypes.c_int, LPVOID] _GetObject.restype = ctypes.c_int _GetObject.errcheck = RaiseIfZero # Both cbBuffer and lpvObject can be omitted, the correct # size and structure to return are automatically deduced. # If lpvObject is given it must be a ctypes object, not a pointer. # Always returns a ctypes object. if cbBuffer is not None: if lpvObject is None: lpvObject = ctypes.create_string_buffer("", cbBuffer) elif lpvObject is not None: cbBuffer = sizeof(lpvObject) else: # most likely case, both are None t = GetObjectType(hgdiobj) if t == OBJ_PEN: cbBuffer = sizeof(LOGPEN) lpvObject = LOGPEN() elif t == OBJ_BRUSH: cbBuffer = sizeof(LOGBRUSH) lpvObject = LOGBRUSH() elif t == OBJ_PAL: cbBuffer = _GetObject(hgdiobj, 0, None) lpvObject = (WORD * (cbBuffer // sizeof(WORD)))() elif t == OBJ_FONT: cbBuffer = sizeof(LOGFONT) lpvObject = LOGFONT() elif t == OBJ_BITMAP: # try the two possible types of bitmap cbBuffer = sizeof(DIBSECTION) lpvObject = DIBSECTION() try: _GetObject(hgdiobj, cbBuffer, byref(lpvObject)) return lpvObject except WindowsError: cbBuffer = sizeof(BITMAP) lpvObject = BITMAP() elif t == OBJ_EXTPEN: cbBuffer = sizeof(LOGEXTPEN) lpvObject = LOGEXTPEN() else: cbBuffer = _GetObject(hgdiobj, 0, None) lpvObject = ctypes.create_string_buffer("", cbBuffer) _GetObject(hgdiobj, cbBuffer, byref(lpvObject)) return lpvObject # LONG GetBitmapBits( # __in HBITMAP hbmp, # __in LONG cbBuffer, # __out LPVOID lpvBits # ); def GetBitmapBits(hbmp): _GetBitmapBits = windll.gdi32.GetBitmapBits _GetBitmapBits.argtypes = [HBITMAP, LONG, LPVOID] _GetBitmapBits.restype = LONG _GetBitmapBits.errcheck = RaiseIfZero bitmap = GetObject(hbmp, lpvObject = BITMAP()) cbBuffer = bitmap.bmWidthBytes * bitmap.bmHeight lpvBits = ctypes.create_string_buffer("", cbBuffer) _GetBitmapBits(hbmp, cbBuffer, byref(lpvBits)) return lpvBits.raw # HBITMAP CreateBitmapIndirect( # __in const BITMAP *lpbm # ); def CreateBitmapIndirect(lpbm): _CreateBitmapIndirect = windll.gdi32.CreateBitmapIndirect _CreateBitmapIndirect.argtypes = [PBITMAP] _CreateBitmapIndirect.restype = HBITMAP _CreateBitmapIndirect.errcheck = RaiseIfZero return _CreateBitmapIndirect(lpbm) #============================================================================== # This calculates the list of exported symbols. _all = set(vars().keys()).difference(_all) __all__ = [_x for _x in _all if not _x.startswith('_')] __all__.sort() #============================================================================== #!/usr/bin/env python # coding=utf-8 import sys from datetime import * import time from elasticsearch import Elasticsearch CONST_ES_HOST="http://172.17.0.1:8081" CONST_TABLE='export_table' CONST_INDEX='stat-*' def str2timestamp(str1,formatStr='%Y-%m-%d %H:%M:%S'): _t = time.mktime(time.strptime(str1,formatStr)) return int(_t) def search_from_es(host,index,query_str,startTime,endTime,scroll=True): print('search_from_es startTime:%s,endTime:%s'%(startTime,endTime)) startTimeStamp = int(str2timestamp(startTime))*1000 endTimeStamp = int(str2timestamp(endTime))*1000+999 data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}} print('search_from_es,post_data:%s'%(data_post_search)) es = Elasticsearch(host) response={} if not scroll: response = es.search(index=index, body=data_post_search,size=10000) else: page_size=10000 scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="1m",size=page_size,_source=['op','time']) scrollId= scan_resp['_scroll_id'] response={} total = scan_resp['hits']['total'] response_list =[] for page_num in range(total/page_size + 1): print 'scroll page_num:',page_num response_tmp ={} response_tmp = es.scroll(scroll_id=scrollId, scroll= "1m") scrollId = response_tmp['_scroll_id'] response_list.append(response_tmp) if response.has_key('hits'): _hits = response['hits'] _hits['hits']+=response_tmp['hits']['hits'] response['hits'] = _hits else: response['hits'] = response_tmp['hits'] return response def fetch_es(startTime,endTime,scroll=True,condition='all'): host = CONST_ES_HOST index = CONST_INDEX query_str='*' if condition!='all': query_str="op:case_submit_patient_info OR op:case_submit_payee_info OR op:case_submit_treatment_info OR op:case_finish OR op:case_draw_cash_apply OR op:case_submit_for_review OR op:share" res = search_from_es(host,index,query_str,startTime,endTime,scroll=scroll) return res if __name__=='__main__': startTime='2017-04-13 16:00:00' endTime='2017-04-13 17:00:00' print '---scroll True--' res = fetch_es(startTime,endTime,scroll=True) total = res['hits']['total'] count = len(res['hits']['hits']) #print 198704 198704 print total,count print '---scroll False--' res = fetch_es(startTime,endTime,scroll=False) total = res['hits']['total'] count = len(res['hits']['hits']) #print 198704 198704 print total,count """ The CustomPermissionsUser users email as the identifier, but uses the normal Django permissions model. This allows us to check that the PermissionsMixin includes everything that is needed to interact with the ModelBackend. """ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.contrib.auth.tests.custom_user import ( CustomUserManager, RemoveGroupsAndPermissions, ) from django.db import models from django.utils.encoding import python_2_unicode_compatible class CustomPermissionsUserManager(CustomUserManager): def create_superuser(self, email, password, date_of_birth): u = self.create_user(email, password=password, date_of_birth=date_of_birth) u.is_superuser = True u.save(using=self._db) return u with RemoveGroupsAndPermissions(): @python_2_unicode_compatible class CustomPermissionsUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) date_of_birth = models.DateField() custom_objects = CustomPermissionsUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] class Meta: app_label = 'auth' def get_full_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email # -*- coding: utf-8 -*- import unittest from cwpoliticl.extensions.base_parser import BaseParser from cwpoliticl.items import WDPost class BaseParseTest(unittest.TestCase): def setUp(self): self.base_parse = BaseParser() # def test_post_page(self): # self.base_parse.get_all_value_response() # pass # def test_new_wdpost(self): # self.url_from = 'url_from' # url = 'http://www.google.com' # title = 'title' # image_src = '' # thumbnail_url = 'http://thumbnail/1.jpg' # content = 'content' # tags = [] # # item = WDPost.get_default(url, self.url_from, title, image_src, thumbnail_url, content, tags) # # self.assertEqual(item['url'], url) def test_css_background_image_for_dailyo(self): image_style = "background-image:url('http://media2.intoday.in/dailyo//story/header/201607/priyankag-sheila-ab_071416102045.jpg')" url = self.base_parse.get_image_src_from_style(image_style) self.assertEqual( 'http://media2.intoday.in/dailyo//story/header/201607/priyankag-sheila-ab_071416102045.jpg', url) def test_css_background_image_for_theindianeconomist(self): image_style = 'background-image: url(http://i2.wp.com/theindianeconomist.com/wp-content/uploads/2016/07/16344930632_f89cc36a46_o.jpg?fit=1280%2C850); opacity: 0.3;' url = self.base_parse.get_image_src_from_style(image_style) self.assertEqual( 'http://i2.wp.com/theindianeconomist.com/wp-content/uploads/2016/07/16344930632_f89cc36a46_o.jpg?fit=1280%2C850', url) # flake8: noqa # SKIP this file when reformatting. # The rest of this file was generated by South. # encoding: utf-8 import datetime from django.db import models from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'NodeCommissionResult' db.create_table('metadataserver_nodecommissionresult', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('node', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['maasserver.Node'])), ('name', self.gf('django.db.models.fields.CharField')(max_length=100)), ('data', self.gf('django.db.models.fields.CharField')(max_length=1048576)), )) db.send_create_signal('metadataserver', ['NodeCommissionResult']) # Adding unique constraint on 'NodeCommissionResult', fields ['node', 'name'] db.create_unique('metadataserver_nodecommissionresult', ['node_id', 'name']) def backwards(self, orm): # Removing unique constraint on 'NodeCommissionResult', fields ['node', 'name'] db.delete_unique('metadataserver_nodecommissionresult', ['node_id', 'name']) # Deleting model 'NodeCommissionResult' db.delete_table('metadataserver_nodecommissionresult') 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', [], {'unique': 'True', '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'}) }, 'maasserver.node': { 'Meta': {'object_name': 'Node'}, 'after_commissioning_action': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'architecture': ('django.db.models.fields.CharField', [], {'default': "u'i386'", 'max_length': '10'}), 'created': ('django.db.models.fields.DateField', [], {}), 'error': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'power_type': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '10', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0', 'max_length': '10'}), 'system_id': ('django.db.models.fields.CharField', [], {'default': "u'node-b9edb888-839c-11e1-965e-002215205ce8'", 'unique': 'True', 'max_length': '41'}), 'token': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['piston.Token']", 'null': 'True'}), 'updated': ('django.db.models.fields.DateTimeField', [], {}) }, 'metadataserver.nodecommissionresult': { 'Meta': {'unique_together': "((u'node', u'name'),)", 'object_name': 'NodeCommissionResult'}, 'data': ('django.db.models.fields.CharField', [], {'max_length': '1048576'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'node': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['maasserver.Node']"}) }, 'metadataserver.nodekey': { 'Meta': {'object_name': 'NodeKey'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '18'}), 'node': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['maasserver.Node']", 'unique': 'True'}), 'token': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['piston.Token']", 'unique': 'True'}) }, 'metadataserver.nodeuserdata': { 'Meta': {'object_name': 'NodeUserData'}, 'data': ('metadataserver.fields.BinaryField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'node': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['maasserver.Node']", 'unique': 'True'}) }, 'piston.consumer': { 'Meta': {'object_name': 'Consumer'}, 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '18'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'secret': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'pending'", 'max_length': '16'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'consumers'", 'null': 'True', 'to': "orm['auth.User']"}) }, 'piston.token': { 'Meta': {'object_name': 'Token'}, 'callback': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'callback_confirmed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'consumer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['piston.Consumer']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '18'}), 'secret': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'timestamp': ('django.db.models.fields.IntegerField', [], {'default': '1334124495L'}), 'token_type': ('django.db.models.fields.IntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'tokens'", 'null': 'True', 'to': "orm['auth.User']"}), 'verifier': ('django.db.models.fields.CharField', [], {'max_length': '10'}) } } complete_apps = ['metadataserver'] # coding: utf-8 '''Tests for CrashManager get_auth_token management command @author: Jesse Schwartzentruber (:truber) @license: 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/. ''' import re from django.contrib.auth.models import User from django.core.management import call_command, CommandError from rest_framework.authtoken.models import Token import pytest pytestmark = pytest.mark.django_db() # pylint: disable=invalid-name def test_args(): with pytest.raises(CommandError, match=r"Error: Enter at least one label."): call_command("get_auth_token") def test_no_such_user(): with pytest.raises(User.DoesNotExist): call_command("get_auth_token", "user") def test_one_user(capsys): user = User.objects.create_user("test", "test@example.com", "test") call_command("get_auth_token", "test") out, _ = capsys.readouterr() key = out.strip() tkn = Token.objects.get(user=user) assert tkn.key == key assert re.match(r"^[A-Fa-f0-9]+$", key) is not None assert len(key) > 32 # just check that it's reasonably long def test_two_users(capsys): users = (User.objects.create_user("test", "test@example.com", "test"), User.objects.create_user("test2", "test2@example.com", "test2")) call_command("get_auth_token", "test", "test2") out, _ = capsys.readouterr() keys = set(out.strip().split()) assert len(keys) == len(users) tkns = set(tkn.key for tkn in Token.objects.all()) assert tkns == keys for key in keys: assert re.match(r"^[A-Fa-f0-9]+$", key) is not None assert len(key) > 32 # just check that it's reasonably long # TC, 7/25/16 import itertools import numpy as np import random import tqdm from scipy.misc import logsumexp ######################### # Bootstrap and Pseudo-R2 Code ######################### def load_words_to_array(i_f, rare_base='A', discard_base='-', del_as_misinc=False): """ Input a word file object. Return a KxM {0,1} array representing the M-length words contained in one of the word.txt files you've been using """ txt_data = [line.strip() for line in i_f.readlines() if discard_base not in line] if del_as_misinc: rare_base_list = [rare_base, 'd'] else: rare_base_list = [rare_base] return np.array([np.where([c in rare_base_list for c in s], 0, 1) for s in txt_data]) def load_controls(A_D_0, A_D_1): """ Given word arrays for the 0 and 1 condition (A_D_0, A_D_1), returns an array suitable for use as the control array in likelihood functions. """ p1 = np.sum(A_D_0, axis=0) / float(A_D_0.shape[0]) p2 = np.sum(A_D_1, axis=0) / float(A_D_1.shape[0]) return np.array([p1, p2]).T ######################### # Signal Allocation Code ######################### def is_monotonic(vec): """ Return True if items in list do not decrease, otherwise return False """ return all([(vec[m+1] - vec[m]) >= 0 for m in range(len(vec) - 1)]) def get_monotonic_allocations(length_d, length_s): """ Return a list of possible ways the strand D could have be written during some signal S. Inputs: length_d - The length of the DNA analysis strand length_s - The number of signal "phases" Output: I_L - A list of lists, I. Individual I's are of length D, with each element being an index of an element of S, indicating that the nucleotide was written during that portion of the signal. """ return [list(I) for I in itertools.product(range(length_s), repeat=length_d) if is_monotonic(I)] ######################### # Single-Sequence Likelihood Code ######################### def seq_alloc_log_lhood(D, S, I, P): """ Get the likelihood of strand D under signal S, given positional probabilities P. I is an "allocation" that indexes D to S. Input: D - A 1-d M-length array composed of {0,1}, representing errors on a DNA strand S - A 1-d N-length array composed of {0,1}, representing the signal delivered at each phase of the signal I - An M-length list, providing indexing of each element of D to an element of S P - A numpy Nx2 array, each row composed of error rates [p_{m,0}, p_{m,1}] Output: ll - The log-likelihood of the strand given S, I, and P """ # Get the vector of error rates # First get the right S_n index for the d_m's # Then use where to get the right probabilities from P ers = np.where(S[I], P[:, 1], P[:, 0]) lhood_components = D*ers + (1-D)*(1-ers) return np.sum(np.log(lhood_components)) def seq_log_lhood(D, S, L_I, P, prior=None, method='map'): """ Return the MAP log-likelihood of a sequence over all possible allocations of that sequence over the signal. Input: D - A numpy Mx1 array composed of {0,1}, representing errors on a DNA strand S - A numpy Nx1 array composed of {0,1}, representing the signal delivered at each phase of the signal L_I - A list of M-length lists, providing indexing of each element of D to an element of S P - A numpy Nx2 array, each row composed of error rates [p_{m,0}, p_{m,1}] prior - A numpy array the length of L_I. The likelihood of each allocation, defaults to a uniform prior Output: ll - The maximum log-likelihood of the strand given S, I, and P """ if prior is None: # i.e. it's uniform prior = np.ones(len(L_I), dtype=float) / len(L_I) if method is 'map': out = np.max([seq_alloc_log_lhood(D,S,I,P) + np.log(p) for I, p in zip(L_I, prior)]) elif method is 'sum': out = logsumexp([seq_alloc_log_lhood(D,S,I,P) for I in L_I], b=prior) else: raise ValueError('Unrecognized method `%s`' % method) return out ######################### # Population Likelihood Code ######################### def pop_log_lhood(A_D, S, P, **kwargs): """ Return the log-likelihood of a population of sequences. Input: A_D - A numpy KxM array composed of {0,1}, representing errors on a M-length DNA strand for K strands S - A numpy Nx1 array composed of {0,1}, representing the signal delivered at each phase of the signal P - A numpy Nx2 array, each row composed of error rates [p_{m,0}, p_{m,1}] Output: ll - The log-likelihood of the population given S and P """ assert A_D.size L_I = get_monotonic_allocations(A_D.shape[1], len(S)) return np.sum(np.apply_along_axis(seq_log_lhood, 1, A_D, S, L_I, P, **kwargs)) def all_log_lhood_fast(A_D, S, P, **kwargs): """ Return a 1-d array of the log-likelihoods of the sequences in A_D Input: A_D - A numpy KxM array composed of {0,1}, representing errors on a M-length DNA strand for K strands S - A 1-d N-length array composed of {0,1}, representing the signal delivered at each phase of the signal P - A numpy Nx2 array, each row composed of error rates [p_{m,0}, p_{m,1}] Output: ll - The log-likelihood of the population given S and P """ assert A_D.size L_I = get_monotonic_allocations(A_D.shape[1], len(S)) # Get all possible D's possible_Ds = list(itertools.product([0,1], repeat=len(A_D[0]))) prob_Ds = {D: seq_log_lhood(np.array(D), S, L_I, P, **kwargs) for D in possible_Ds} return np.apply_along_axis(lambda x: prob_Ds[tuple(x)], 1, A_D) # return [np.apply_along_axis(lambda x: (x == D).all(), 1, A_D) for D in possible_Ds] # return np.array([ct * p for ct, p in zip(count_Ds, prob_Ds)]) def pop_log_lhood_fast(A_D, S, P, **kwargs): """ Return the log-likelihood of a population, using a method in kwargs. """ return np.sum(all_log_lhood_fast(A_D, S, P, **kwargs)) def multi_pop_log_lhood_fast(l_A_D, S, P, **kwargs): """ Return the log-likelihood of a multi-sample population. """ return np.sum([np.sum(all_log_lhood_fast(A_D, S, P, **kwargs)) for A_D in l_A_D]) ######################### # Bootstrap and Pseudo-R2 Code ######################### def rel_pseudo_r2_pop(L_D, S1, S2, P1, P2=None, **kwargs): """ Return McFadden's Pseudo-R^2 (1-\frac{logL_S1}{logL_S2} of sequences under signal S1 over signal S2. """ if not P2: P2 = P1 logL_1 = pop_log_lhood_fast(L_D, S1, P1, **kwargs) logL_2 = pop_log_lhood_fast(L_D, S2, P2, **kwargs) return 1 - (logL_1/logL_2) def multi_rel_pseudo_r2_pop(L_D_list, S1, S2, P1, P2=None, **kwargs): """ Return McFadden's Pseudo-R^2 (1-\frac{logL_S1}{logL_S2} of sequences under signal S1 over signal S2. """ if not P2: P2 = P1 logL_1 = multi_pop_log_lhood_fast(L_D_list, S1, P1, **kwargs) logL_2 = multi_pop_log_lhood_fast(L_D_list, S2, P2, **kwargs) return 1 - (logL_1/logL_2) def bootstr_ci(func, X, alpha=0.05, args=None, kwargs=None, n_iter=1000, samp_size=None, verbose=False): if args and kwargs: f = lambda data: func(data, *args, **kwargs) elif args: f = lambda data: func(data, *args) elif kwargs: f = lambda data: func(data, **kwargs) else: f = func if not samp_size: samp_size = len(X) Fstar_lo, Fstar_hi = np.floor(n_iter * np.array([alpha/2., 1-alpha/2.])).astype(int) f_mu = f(X) bootstrap_stats = np.zeros((n_iter,) + f_mu.shape) if verbose: for i in tqdm.tqdm(range(n_iter)): resampled_idx = np.random.randint(X.shape[0], size=(samp_size,1)) resampled_X = X[resampled_idx,...].squeeze() bootstrap_stats[i,...] = f(resampled_X) else: for i in range(n_iter): resampled_idx = np.random.randint(X.shape[0], size=(samp_size,1)) resampled_X = X[resampled_idx,...].squeeze() bootstrap_stats[i,...] = f(resampled_X) srt_bootstrap_stats = np.sort(bootstrap_stats, axis=0) ci = (srt_bootstrap_stats[Fstar_lo], srt_bootstrap_stats[Fstar_hi]) return ci def bootstr_ci_pseudo_r2(L_D, S1, S2, P1, P2=None, alpha=0.05, n_iter=1000, samp_size=None, verbose=False, **kwargs): """ Does bootstrap for pseudo-r2. Gets significant speedups as we can precompute the log-likelihood of all the sequences first, then just bootstrap over the sum. """ if not P2: # This might be better handled by *args... P2 = P1 if not samp_size: samp_size = L_D.shape[0] if verbose: iterator = tqdm.tqdm(range(n_iter)) else: iterator = range(n_iter) Fstar_lo, Fstar_hi = np.floor(n_iter * np.array([alpha/2., 1-alpha/2.])).astype(int) # Pre-calculate log-likelihoods logLs_1 = all_log_lhood_fast(L_D, S1, P1, **kwargs) logLs_2 = all_log_lhood_fast(L_D, S2, P2, **kwargs) bootstrap_stats = np.zeros((n_iter)) for i in iterator: resampled_idx = np.random.randint(L_D.shape[0], size=(samp_size,1)) bootstrap_stats[i] = 1 - (np.sum(logLs_1[resampled_idx].squeeze()) / np.sum(logLs_2[resampled_idx].squeeze())) srt_bootstrap_stats = np.sort(bootstrap_stats.squeeze()) ci = (srt_bootstrap_stats[Fstar_lo], srt_bootstrap_stats[Fstar_hi]) return ci def multi_bootstr_ci_pseudo_r2(L_D_list, S1, S2, P1, P2=None, alpha=0.05, n_iter=1000, verbose=False, **kwargs): """ Does bootstrap for pseudo-r2. Gets significant speedups as we can precompute the log-likelihood of all the sequences first, then just bootstrap over the sum. Inputs: - L_D_list: list of arrays denoting errors for each strand in each sample - S1: array denoting the first signal - S2: array denoting the second signal - P1: array denoting the error rates at each site for each condition in S1 or S2 Output: - ci: a tuple containing the lower and upper pseudo-R2 bound """ if not P2: # This might be better handled by *args... P2 = P1 if verbose: iterator = tqdm.tqdm(range(n_iter)) else: iterator = range(n_iter) Fstar_lo, Fstar_hi = np.floor(n_iter * np.array([alpha/2., 1-alpha/2.])).astype(int) # Pre-calculate log-likelihoods logLs_1 = [all_log_lhood_fast(L_D, S1, P1, **kwargs) for L_D in L_D_list] logLs_2 = [all_log_lhood_fast(L_D, S2, P2, **kwargs) for L_D in L_D_list] bootstrap_stats = np.zeros((n_iter)) for i in iterator: boot_idx = [np.random.randint(L_D.shape[0], size=(L_D.shape[0], 1)) for L_D in L_D_list] boot_L1 = [np.sum(logL[bix].squeeze()) for logL, bix in zip(logLs_1, boot_idx)] boot_L2 = [np.sum(logL[bix].squeeze()) for logL, bix in zip(logLs_2, boot_idx)] bootstrap_stats[i] = 1 - (np.sum(boot_L1) / np.sum(boot_L2)) srt_bootstrap_stats = np.sort(bootstrap_stats.squeeze()) ci = (srt_bootstrap_stats[Fstar_lo], srt_bootstrap_stats[Fstar_hi]) return ci def model_softmax(L_D, S_list, P1, **kwargs): """ Calculates softmax of models based on model likelihood """ x = np.array([pop_log_lhood_fast(L_D, S, P1, **kwargs) for S in S_List]) return np.exp(x) / np.sum(np.exp(x), axis=0) # -*- coding: utf-8 -*- # # Copyright (C) 2013 Vinay Sajip. # Licensed to the Python Software Foundation under a contributor agreement. # See LICENSE.txt and CONTRIBUTORS.txt. # import hashlib import logging import os import shutil import subprocess import tempfile try: from threading import Thread except ImportError: from dummy_threading import Thread from . import DistlibException from .compat import (HTTPBasicAuthHandler, Request, HTTPPasswordMgr, urlparse, build_opener, string_types) from .util import cached_property, zip_dir, ServerProxy logger = logging.getLogger(__name__) DEFAULT_INDEX = 'https://pypi.python.org/pypi' DEFAULT_REALM = 'pypi' class PackageIndex(object): """ This class represents a package index compatible with PyPI, the Python Package Index. """ boundary = b'----------ThIs_Is_tHe_distlib_index_bouNdaRY_$' def __init__(self, url=None): """ Initialise an instance. :param url: The URL of the index. If not specified, the URL for PyPI is used. """ self.url = url or DEFAULT_INDEX self.read_configuration() scheme, netloc, path, params, query, frag = urlparse(self.url) if params or query or frag or scheme not in ('http', 'https'): raise DistlibException('invalid repository: %s' % self.url) self.password_handler = None self.ssl_verifier = None self.gpg = None self.gpg_home = None self.rpc_proxy = None with open(os.devnull, 'w') as sink: for s in ('gpg2', 'gpg'): try: rc = subprocess.check_call([s, '--version'], stdout=sink, stderr=sink) if rc == 0: self.gpg = s break except OSError: pass def _get_pypirc_command(self): """ Get the distutils command for interacting with PyPI configurations. :return: the command. """ from distutils.core import Distribution from distutils.config import PyPIRCCommand d = Distribution() return PyPIRCCommand(d) def read_configuration(self): """ Read the PyPI access configuration as supported by distutils, getting PyPI to do the acutal work. This populates ``username``, ``password``, ``realm`` and ``url`` attributes from the configuration. """ # get distutils to do the work c = self._get_pypirc_command() c.repository = self.url cfg = c._read_pypirc() self.username = cfg.get('username') self.password = cfg.get('password') self.realm = cfg.get('realm', 'pypi') self.url = cfg.get('repository', self.url) def save_configuration(self): """ Save the PyPI access configuration. You must have set ``username`` and ``password`` attributes before calling this method. Again, distutils is used to do the actual work. """ self.check_credentials() # get distutils to do the work c = self._get_pypirc_command() c._store_pypirc(self.username, self.password) def check_credentials(self): """ Check that ``username`` and ``password`` have been set, and raise an exception if not. """ if self.username is None or self.password is None: raise DistlibException('username and password must be set') pm = HTTPPasswordMgr() _, netloc, _, _, _, _ = urlparse(self.url) pm.add_password(self.realm, netloc, self.username, self.password) self.password_handler = HTTPBasicAuthHandler(pm) def register(self, metadata): """ Register a distribution on PyPI, using the provided metadata. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the distribution to be registered. :return: The HTTP response received from PyPI upon submission of the request. """ self.check_credentials() metadata.validate() d = metadata.todict() d[':action'] = 'verify' request = self.encode_request(d.items(), []) response = self.send_request(request) d[':action'] = 'submit' request = self.encode_request(d.items(), []) return self.send_request(request) def _reader(self, name, stream, outbuf): """ Thread runner for reading lines of from a subprocess into a buffer. :param name: The logical name of the stream (used for logging only). :param stream: The stream to read from. This will typically a pipe connected to the output stream of a subprocess. :param outbuf: The list to append the read lines to. """ while True: s = stream.readline() if not s: break s = s.decode('utf-8').rstrip() outbuf.append(s) logger.debug('%s: %s' % (name, s)) stream.close() def get_sign_command(self, filename, signer, sign_password): """ Return a suitable command for signing a file. :param filename: The pathname to the file to be signed. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :return: The signing command as a list suitable to be passed to :class:`subprocess.Popen`. """ cmd = [self.gpg, '--status-fd', '2', '--no-tty'] if self.gpg_home: cmd.extend(['--homedir', self.gpg_home]) if sign_password is not None: cmd.extend(['--batch', '--passphrase-fd', '0']) td = tempfile.mkdtemp() sf = os.path.join(td, os.path.basename(filename) + '.asc') cmd.extend(['--detach-sign', '--armor', '--local-user', signer, '--output', sf, filename]) logger.debug('invoking: %s', ' '.join(cmd)) return cmd, sf def run_command(self, cmd, input_data=None): """ Run a command in a child process , passing it any input data specified. :param cmd: The command to run. :param input_data: If specified, this must be a byte string containing data to be sent to the child process. :return: A tuple consisting of the subprocess' exit code, a list of lines read from the subprocess' ``stdout``, and a list of lines read from the subprocess' ``stderr``. """ kwargs = { 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, } if input_data is not None: kwargs['stdin'] = subprocess.PIPE stdout = [] stderr = [] p = subprocess.Popen(cmd, **kwargs) # We don't use communicate() here because we may need to # get clever with interacting with the command t1 = Thread(target=self._reader, args=('stdout', p.stdout, stdout)) t1.start() t2 = Thread(target=self._reader, args=('stderr', p.stderr, stderr)) t2.start() if input_data is not None: p.stdin.write(input_data) p.stdin.close() p.wait() t1.join() t2.join() return p.returncode, stdout, stderr def sign_file(self, filename, signer, sign_password): """ Sign a file. :param filename: The pathname to the file to be signed. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :return: The absolute pathname of the file where the signature is stored. """ cmd, sig_file = self.get_sign_command(filename, signer, sign_password) rc, stdout, stderr = self.run_command(cmd, sign_password.encode('utf-8')) if rc != 0: raise DistlibException('sign command failed with error ' 'code %s' % rc) return sig_file def upload_file(self, metadata, filename, signer=None, sign_password=None, filetype='sdist', pyversion='source'): """ Upload a release file to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the file to be uploaded. :param filename: The pathname of the file to be uploaded. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :param filetype: The type of the file being uploaded. This is the distutils command which produced that file, e.g. ``sdist`` or ``bdist_wheel``. :param pyversion: The version of Python which the release relates to. For code compatible with any Python, this would be ``source``, otherwise it would be e.g. ``3.2``. :return: The HTTP response received from PyPI upon submission of the request. """ self.check_credentials() if not os.path.exists(filename): raise DistlibException('not found: %s' % filename) metadata.validate() d = metadata.todict() sig_file = None if signer: if not self.gpg: logger.warning('no signing program available - not signed') else: sig_file = self.sign_file(filename, signer, sign_password) with open(filename, 'rb') as f: file_data = f.read() md5_digest = hashlib.md5(file_data).hexdigest() sha256_digest = hashlib.sha256(file_data).hexdigest() d.update({ ':action': 'file_upload', 'protcol_version': '1', 'filetype': filetype, 'pyversion': pyversion, 'md5_digest': md5_digest, 'sha256_digest': sha256_digest, }) files = [('content', os.path.basename(filename), file_data)] if sig_file: with open(sig_file, 'rb') as f: sig_data = f.read() files.append(('gpg_signature', os.path.basename(sig_file), sig_data)) shutil.rmtree(os.path.dirname(sig_file)) request = self.encode_request(d.items(), files) return self.send_request(request) def upload_documentation(self, metadata, doc_dir): """ Upload documentation to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the documentation to be uploaded. :param doc_dir: The pathname of the directory which contains the documentation. This should be the directory that contains the ``index.html`` for the documentation. :return: The HTTP response received from PyPI upon submission of the request. """ self.check_credentials() if not os.path.isdir(doc_dir): raise DistlibException('not a directory: %r' % doc_dir) fn = os.path.join(doc_dir, 'index.html') if not os.path.exists(fn): raise DistlibException('not found: %r' % fn) metadata.validate() name, version = metadata.name, metadata.version zip_data = zip_dir(doc_dir).getvalue() fields = [(':action', 'doc_upload'), ('name', name), ('version', version)] files = [('content', name, zip_data)] request = self.encode_request(fields, files) return self.send_request(request) def get_verify_command(self, signature_filename, data_filename): """ Return a suitable command for verifying a file. :param signature_filename: The pathname to the file containing the signature. :param data_filename: The pathname to the file containing the signed data. :return: The verifying command as a list suitable to be passed to :class:`subprocess.Popen`. """ cmd = [self.gpg, '--status-fd', '2', '--no-tty'] if self.gpg_home: cmd.extend(['--homedir', self.gpg_home]) cmd.extend(['--verify', signature_filename, data_filename]) logger.debug('invoking: %s', ' '.join(cmd)) return cmd def verify_signature(self, signature_filename, data_filename): """ Verify a signature for a file. :param signature_filename: The pathname to the file containing the signature. :param data_filename: The pathname to the file containing the signed data. :return: True if the signature was verified, else False. """ if not self.gpg: raise DistlibException('verification unavailable because gpg ' 'unavailable') cmd = self.get_verify_command(signature_filename, data_filename) rc, stdout, stderr = self.run_command(cmd) if rc not in (0, 1): raise DistlibException('verify command failed with error ' 'code %s' % rc) return rc == 0 def download_file(self, url, destfile, digest=None, reporthook=None): """ This is a convenience method for downloading a file from an URL. Normally, this will be a file from the index, though currently no check is made for this (i.e. a file can be downloaded from anywhere). The method is just like the :func:`urlretrieve` function in the standard library, except that it allows digest computation to be done during download and checking that the downloaded data matched any expected value. :param url: The URL of the file to be downloaded (assumed to be available via an HTTP GET request). :param destfile: The pathname where the downloaded file is to be saved. :param digest: If specified, this must be a (hasher, value) tuple, where hasher is the algorithm used (e.g. ``'md5'``) and ``value`` is the expected value. :param reporthook: The same as for :func:`urlretrieve` in the standard library. """ if digest is None: digester = None logger.debug('No digest specified') else: if isinstance(digest, (list, tuple)): hasher, digest = digest else: hasher = 'md5' digester = getattr(hashlib, hasher)() logger.debug('Digest specified: %s' % digest) # The following code is equivalent to urlretrieve. # We need to do it this way so that we can compute the # digest of the file as we go. with open(destfile, 'wb') as dfp: # addinfourl is not a context manager on 2.x # so we have to use try/finally sfp = self.send_request(Request(url)) try: headers = sfp.info() blocksize = 8192 size = -1 read = 0 blocknum = 0 if "content-length" in headers: size = int(headers["Content-Length"]) if reporthook: reporthook(blocknum, blocksize, size) while True: block = sfp.read(blocksize) if not block: break read += len(block) dfp.write(block) if digester: digester.update(block) blocknum += 1 if reporthook: reporthook(blocknum, blocksize, size) finally: sfp.close() # check that we got the whole file, if we can if size >= 0 and read < size: raise DistlibException( 'retrieval incomplete: got only %d out of %d bytes' % (read, size)) # if we have a digest, it must match. if digester: actual = digester.hexdigest() if digest != actual: raise DistlibException('%s digest mismatch for %s: expected ' '%s, got %s' % (hasher, destfile, digest, actual)) logger.debug('Digest verified: %s', digest) def send_request(self, req): """ Send a standard library :class:`Request` to PyPI and return its response. :param req: The request to send. :return: The HTTP response from PyPI (a standard library HTTPResponse). """ handlers = [] if self.password_handler: handlers.append(self.password_handler) if self.ssl_verifier: handlers.append(self.ssl_verifier) opener = build_opener(*handlers) return opener.open(req) def encode_request(self, fields, files): """ Encode fields and files for posting to an HTTP server. :param fields: The fields to send as a list of (fieldname, value) tuples. :param files: The files to send as a list of (fieldname, filename, file_bytes) tuple. """ # Adapted from packaging, which in turn was adapted from # http://code.activestate.com/recipes/146306 parts = [] boundary = self.boundary for k, values in fields: if not isinstance(values, (list, tuple)): values = [values] for v in values: parts.extend(( b'--' + boundary, ('Content-Disposition: form-data; name="%s"' % k).encode('utf-8'), b'', v.encode('utf-8'))) for key, filename, value in files: parts.extend(( b'--' + boundary, ('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)).encode('utf-8'), b'', value)) parts.extend((b'--' + boundary + b'--', b'')) body = b'\r\n'.join(parts) ct = b'multipart/form-data; boundary=' + boundary headers = { 'Content-type': ct, 'Content-length': str(len(body)) } return Request(self.url, body, headers) def search(self, terms, operator=None): if isinstance(terms, string_types): terms = {'name': terms} if self.rpc_proxy is None: self.rpc_proxy = ServerProxy(self.url, timeout=3.0) return self.rpc_proxy.search(terms, operator or 'and') #!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * class ZapWalletTXesTest (BitcoinTestFramework): def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 3) def setup_network(self, split=False): self.nodes = start_nodes(3, self.options.tmpdir) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) self.is_network_split=False self.sync_all() def run_test (self): print "Mining blocks..." self.nodes[0].generate(1) self.sync_all() self.nodes[1].generate(101) self.sync_all() assert_equal(self.nodes[0].getbalance(), 500) txid0 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11) txid1 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10) self.sync_all() self.nodes[0].generate(1) self.sync_all() txid2 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11) txid3 = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10) tx0 = self.nodes[0].gettransaction(txid0) assert_equal(tx0['txid'], txid0) #tx0 must be available (confirmed) tx1 = self.nodes[0].gettransaction(txid1) assert_equal(tx1['txid'], txid1) #tx1 must be available (confirmed) tx2 = self.nodes[0].gettransaction(txid2) assert_equal(tx2['txid'], txid2) #tx2 must be available (unconfirmed) tx3 = self.nodes[0].gettransaction(txid3) assert_equal(tx3['txid'], txid3) #tx3 must be available (unconfirmed) #restart bitcoind self.nodes[0].stop() bitcoind_processes[0].wait() self.nodes[0] = start_node(0,self.options.tmpdir) tx3 = self.nodes[0].gettransaction(txid3) assert_equal(tx3['txid'], txid3) #tx must be available (unconfirmed) self.nodes[0].stop() bitcoind_processes[0].wait() #restart bitcoind with zapwallettxes self.nodes[0] = start_node(0,self.options.tmpdir, ["-zapwallettxes=1"]) assert_raises(JSONRPCException, self.nodes[0].gettransaction, [txid3]) #there must be a expection because the unconfirmed wallettx0 must be gone by now tx0 = self.nodes[0].gettransaction(txid0) assert_equal(tx0['txid'], txid0) #tx0 (confirmed) must still be available because it was confirmed if __name__ == '__main__': ZapWalletTXesTest ().main () #-*- coding: utf-8 -*- ########################################################################### ## ## ## Copyrights Frederic Rodrigo 2012 ## ## ## ## This program is free software: you can redistribute it and/or modify ## ## it under the terms of the GNU General Public License as published by ## ## the Free Software Foundation, either version 3 of the License, or ## ## (at your option) any later version. ## ## ## ## This program is distributed in the hope that it will be useful, ## ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 . ## ## ## ########################################################################### from modules.OsmoseTranslation import T_ from plugins.Plugin import Plugin import sqlite3 as lite class Wiki(Plugin): def init(self, logger): Plugin.init(self, logger) self.errors[3140] = self.def_class(item = 3140, level = 2, tags = ['tag'], title = T_('Object taggin type')) # Taginfo wiki extract database # http://taginfo.openstreetmap.org/download/taginfo-wiki.db.bz2 con = lite.connect('taginfo-wiki.db') with con: cur = con.cursor() cur.execute("select tag, on_node, on_way, on_area, on_relation from wikipages where lang='en' and (on_node or on_way or on_area or on_relation)") rows = cur.fetchall() self.tag_supported = set() self.tag_node = set() self.tag_way = set() self.tag_area = set() self.tag_relation = set() for row in rows: if not "=" in row[0]: self.tag_supported.add(row[0]) if row[1]: self.tag_node.add(row[0]) if row[2]: self.tag_way.add(row[0]) if row[3]: self.tag_area.add(row[0]) if row[4]: self.tag_relation.add(row[0]) def node(self, data, tags): ret = [] for tag in tags: if tag in self.tag_supported and tag not in self.tag_node: ret.append((3140, 1, {"fr": "Le tag \"{0}\" ne s'applique pas aux nœuds".format(tag), "en": "Tag \"{0}\" not for nodes".format(tag)})) return ret def way(self, data, tags, nds): ret = [] for tag in tags: if tag in self.tag_supported and tag not in self.tag_way and tag not in self.tag_area: ret.append((3140, 2, {"fr": "Le tag \"{0}\" ne s'applique pas aux ways".format(tag), "en": "Tag \"{0}\" not for ways".format(tag)})) return ret def relation(self, data, tags, members): ret = [] for tag in tags: if tag in self.tag_supported and tag not in self.tag_relation: ret.append((3140, 3, {"fr": "Le tag \"{0}\" ne s'applique pas aux relations".format(tag), "en": "Tag \"{0}\" not for relations".format(tag)})) return ret if __name__ == "__main__": a = Wiki(None) a.init(None) for d in [u"fsdkfjdklsfkleqnhkflerklg", u"sport"]: if a.node(None, {d:"a"}): print("fail: {0}".format(d)) for d in [u"building"]: if not a.node(None, {d:"a"}): print("nofail: {0}".format(d)) import json from allauth.socialaccount.providers.oauth.client import OAuth from allauth.socialaccount.providers.oauth.views import (OAuthAdapter, OAuthLoginView, OAuthCallbackView) from .provider import VimeoProvider class VimeoAPI(OAuth): url = 'http://vimeo.com/api/rest/v2?method=vimeo.people.getInfo' def get_user_info(self): url = self.url data = json.loads(self.query(url, params=dict(format='json'))) return data['person'] class VimeoOAuthAdapter(OAuthAdapter): provider_id = VimeoProvider.id request_token_url = 'https://vimeo.com/oauth/request_token' access_token_url = 'https://vimeo.com/oauth/access_token' authorize_url = 'https://vimeo.com/oauth/authorize' def complete_login(self, request, app, token, response): client = VimeoAPI(request, app.client_id, app.secret, self.request_token_url) extra_data = client.get_user_info() return self.get_provider().sociallogin_from_response(request, extra_data) oauth_login = OAuthLoginView.adapter_view(VimeoOAuthAdapter) oauth_callback = OAuthCallbackView.adapter_view(VimeoOAuthAdapter) # Copyright (C) 2014 LiuLang # Use of this source code is governed by GPLv3 license that can be found # in http://www.gnu.org/licenses/gpl-3.0.html import json import multiprocessing import os from queue import Queue import re import threading import time import traceback from urllib import request from gi.repository import GLib from gi.repository import GObject from bcloud.const import State, DownloadMode from bcloud import net from bcloud import pcs from bcloud import util from bcloud.log import logger CHUNK_SIZE = 131072 # 128K RETRIES = 3 # 连接失败时的重试次数 DOWNLOAD_RETRIES = 10 # 下载线程的重试次数 THRESHOLD_TO_FLUSH = 500 # 磁盘写入数据次数超过这个值时, 就进行一次同步. SMALL_FILE_SIZE = 1048576 # 1M, 下载小文件时用单线程下载 (NAME_COL, PATH_COL, FSID_COL, SIZE_COL, CURRSIZE_COL, LINK_COL, ISDIR_COL, SAVENAME_COL, SAVEDIR_COL, STATE_COL, STATENAME_COL, HUMANSIZE_COL, PERCENT_COL) = list(range(13)) BATCH_FINISISHED, BATCH_ERROR = -1, -2 def get_tmp_filepath(dir_name, save_name): '''返回最终路径名及临时路径名''' filepath = os.path.join(dir_name, save_name) return filepath, filepath + '.part', filepath + '.bcloud-stat' class DownloadBatch(threading.Thread): def __init__(self, id_, queue, url, lock, start_size, end_size, fh, timeout): super().__init__() self.id_ = id_ self.queue = queue self.url = url self.lock = lock self.start_size = start_size self.end_size = end_size self.fh = fh self.timeout = timeout self.stop_flag = False def run(self): self.download() def stop(self): self.stop_flag = True def get_req(self, start_size, end_size): '''打开socket''' logger.debug('DownloadBatch.get_req: %s, %s' % (start_size, end_size)) opener = request.build_opener() content_range = 'bytes={0}-{1}'.format(start_size, end_size) opener.addheaders = [('Range', content_range)] for i in range(RETRIES): try: return opener.open(self.url, timeout=self.timeout) except OSError: logger.error(traceback.format_exc()) else: return None def download(self): offset = self.start_size req = self.get_req(offset, self.end_size) if not req: self.queue.put((self.id_, BATCH_ERROR), block=False) return while not self.stop_flag: for i in range(DOWNLOAD_RETRIES): if not req: req = self.get_req(offset, self.end_size) logger.debug('DownloadBatch.download: socket reconnected') try: block = req.read(CHUNK_SIZE) if block: break except (OSError, AttributeError): logger.error(traceback.format_exc()) req = None else: logger.error('DownloadBatch, block is empty: %s, %s, %s, %s' % (offset, self.start_size, self.end_size, block)) self.queue.put((self.id_, BATCH_ERROR), block=False) return with self.lock: if self.fh.closed: return self.fh.seek(offset) self.fh.write(block) self.queue.put((self.id_, len(block)), block=False) offset = offset + len(block) # 下载完成 if offset >= self.end_size: self.queue.put((self.id_, BATCH_FINISISHED), block=False) return class Downloader(threading.Thread, GObject.GObject): '''管理每个下载任务, 使用了多线程下载. 当程序退出时, 下载线程会保留现场, 以后可以继续下载. 断点续传功能基于HTTP/1.1 的Range, 百度网盘对它有很好的支持. ''' __gsignals__ = { 'started': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (str, )), 'received': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (str, GObject.TYPE_INT64, GObject.TYPE_INT64)), 'downloaded': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (str, )), # FSID, tmp-filepath 'disk-error': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (str, str)), 'network-error': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (str, )), } def __init__(self, parent, row): threading.Thread.__init__(self) self.daemon = True GObject.GObject.__init__(self) self.cookie = parent.app.cookie self.tokens = parent.app.tokens self.default_threads = int(parent.app.profile['download-segments']) self.timeout = int(parent.app.profile['download-timeout']) self.download_mode = parent.app.profile['download-mode'] self.row = row[:] def download(self): row = self.row if not os.path.exists(row[SAVEDIR_COL]): os.makedirs(row[SAVEDIR_COL], exist_ok=True) filepath, tmp_filepath, conf_filepath = get_tmp_filepath( row[SAVEDIR_COL], row[SAVENAME_COL]) if os.path.exists(filepath): if self.download_mode == DownloadMode.IGNORE: self.emit('downloaded', row[FSID_COL]) logger.debug('File exists, ignored!') return elif self.download_mode == DownloadMode.NEWCOPY: name, ext = os.path.splitext(filepath) filepath = '{0}_{1}{2}'.format(name, util.curr_time(), ext) url = pcs.get_download_link(self.cookie, self.tokens, row[PATH_COL]) if not url: row[STATE_COL] = State.ERROR self.emit('network-error', row[FSID_COL]) logger.warn('Failed to get url to download') return if os.path.exists(conf_filepath) and os.path.exists(tmp_filepath): with open(conf_filepath) as conf_fh: status = json.load(conf_fh) threads = len(status) file_exists = True fh = open(tmp_filepath, 'rb+') fh.seek(0) else: req = net.urlopen_simple(url) if not req: logger.warn('Failed to get url to download') self.emit('network-error', row[FSID_COL]) return content_length = req.getheader('Content-Length') # Fixed: baiduPCS using non iso-8859-1 codec in http headers if not content_length: match = re.search('\sContent-Length:\s*(\d+)', str(req.headers)) if not match: logger.warn('Failed to get url to download') self.emit('network-error', row[FSID_COL]) return content_length = match.group(1) size = int(content_length) if size == 0: open(filepath, 'a').close() self.emit('downloaded', row[FSID_COL]) return elif size <= SMALL_FILE_SIZE: threads = 1 else: threads = self.default_threads average_size, pad_size = divmod(size, threads) file_exists = False status = [] fh = open(tmp_filepath, 'wb') try: fh.truncate(size) except (OSError, IOError): e = truncate.format_exc() logger.error(e) self.emit('disk-error', row[FSID_COL], tmp_filepath) return # task list tasks = [] # message queue queue = Queue() # threads lock lock = threading.RLock() for id_ in range(threads): if file_exists: start_size, end_size, received = status[id_] if start_size + received >= end_size: # part of file has been downloaded continue start_size += received else: start_size = id_ * average_size end_size = start_size + average_size - 1 if id_ == threads - 1: end_size = end_size + pad_size + 1 status.append([start_size, end_size, 0]) task = DownloadBatch(id_, queue, url, lock, start_size, end_size, fh, self.timeout) tasks.append(task) for task in tasks: task.start() try: conf_count = 0 done = 0 self.emit('started', row[FSID_COL]) while row[STATE_COL] == State.DOWNLOADING: id_, received = queue.get() # FINISHED if received == BATCH_FINISISHED: done += 1 if done == len(tasks): row[STATE_COL] = State.FINISHED break else: continue # error occurs elif received == BATCH_ERROR: row[STATE_COL] = State.ERROR break status[id_][2] += received conf_count += 1 # flush data and status to disk if conf_count > THRESHOLD_TO_FLUSH: with lock: if not fh.closed: fh.flush() with open(conf_filepath, 'w') as fh: json.dump(status, fh) conf_count = 0 received_total = sum(t[2] for t in status) self.emit('received', row[FSID_COL], received, received_total) except Exception: logger.error(traceback.format_exc()) row[STATE_COL] = State.ERROR with lock: if not fh.closed: fh.close() for task in tasks: if task.isAlive(): task.stop() with open(conf_filepath, 'w') as fh: json.dump(status, fh) if row[STATE_COL] == State.CANCELED: os.remove(tmp_filepath) if os.path.exists(conf_filepath): os.remove(conf_filepath) elif row[STATE_COL] == State.ERROR: self.emit('network-error', row[FSID_COL]) elif row[STATE_COL] == State.FINISHED: self.emit('downloaded', row[FSID_COL]) os.rename(tmp_filepath, filepath) if os.path.exists(conf_filepath): os.remove(conf_filepath) def destroy(self): '''自毁''' self.pause() def run(self): '''实现了Thread的方法, 线程启动入口''' self.download() def pause(self): '''暂停下载任务''' self.row[STATE_COL] = State.PAUSED def stop(self): '''停止下载, 并删除之前下载的片段''' self.row[STATE_COL] = State.CANCELED GObject.type_register(Downloader) from bika.lims import enum from bika.lims import PMF from bika.lims.browser import ulocalized_time from bika.lims.interfaces import IJSONReadExtender from bika.lims.jsonapi import get_include_fields from bika.lims.utils import changeWorkflowState from bika.lims.utils import t from Products.CMFCore.interfaces import IContentish from Products.CMFCore.utils import getToolByName from Products.CMFCore.WorkflowCore import WorkflowException from Products.CMFPlone.interfaces import IWorkflowChain from Products.CMFPlone.workflow import ToolWorkflowChain from zope.component import adapts from zope.interface import implementer from zope.interface import implements from zope.interface import Interface def skip(instance, action, peek=False, unskip=False): """Returns True if the transition is to be SKIPPED peek - True just checks the value, does not set. unskip - remove skip key (for manual overrides). called with only (instance, action_id), this will set the request variable preventing the cascade's from re-transitioning the object and return None. """ uid = callable(instance.UID) and instance.UID() or instance.UID skipkey = "%s_%s" % (uid, action) if 'workflow_skiplist' not in instance.REQUEST: if not peek and not unskip: instance.REQUEST['workflow_skiplist'] = [skipkey, ] else: if skipkey in instance.REQUEST['workflow_skiplist']: if unskip: instance.REQUEST['workflow_skiplist'].remove(skipkey) else: return True else: if not peek and not unskip: instance.REQUEST["workflow_skiplist"].append(skipkey) def doActionFor(instance, action_id): actionperformed = False message = '' workflow = getToolByName(instance, "portal_workflow") if not skip(instance, action_id, peek=True): try: workflow.doActionFor(instance, action_id) actionperformed = True except WorkflowException as e: message = str(e) pass return actionperformed, message def BeforeTransitionEventHandler(instance, event): """This will run the workflow_before_* on any content type that has one. """ # creation doesn't have a 'transition' if not event.transition: return key = 'workflow_before_' + event.transition.id method = getattr(instance, key, False) if method: method() def AfterTransitionEventHandler(instance, event): """This will run the workflow_script_* on any content type that has one. """ # creation doesn't have a 'transition' if not event.transition: return key = 'workflow_script_' + event.transition.id method = getattr(instance, key, False) if method: method() def get_workflow_actions(obj): """ Compile a list of possible workflow transitions for this object """ def translate(id): return t(PMF(id + "_transition_title")) workflow = getToolByName(obj, 'portal_workflow') actions = [{"id": it["id"], "title": translate(it["id"])} for it in workflow.getTransitionsFor(obj)] return actions def isBasicTransitionAllowed(context, permission=None): """Most transition guards need to check the same conditions: - Is the object active (cancelled or inactive objects can't transition) - Has the user a certain permission, required for transition. This should normally be set in the guard_permission in workflow definition. """ workflow = getToolByName(context, "portal_workflow") mtool = getToolByName(context, "portal_membership") if workflow.getInfoFor(context, "cancellation_state", "") == "cancelled" \ or workflow.getInfoFor(context, "inactive_state", "") == "inactive" \ or (permission and mtool.checkPermission(permission, context)): return False return True def getCurrentState(obj, stateflowid): """ The current state of the object for the state flow id specified Return empty if there's no workflow state for the object and flow id """ wf = getToolByName(obj, 'portal_workflow') return wf.getInfoFor(obj, stateflowid, '') def getTransitionDate(obj, action_id): workflow = getToolByName(obj, 'portal_workflow') review_history = list(workflow.getInfoFor(obj, 'review_history')) # invert the list, so we always see the most recent matching event review_history.reverse() for event in review_history: if event['action'] == action_id: value = ulocalized_time(event['time'], long_format=True, time_only=False, context=obj) return value return None # Enumeration of the available status flows StateFlow = enum(review='review_state', inactive='inactive_state', cancellation='cancellation_state') # Enumeration of the different available states from the inactive flow InactiveState = enum(active='active') # Enumeration of the different states can have a batch BatchState = enum(open='open', closed='closed', cancelled='cancelled') BatchTransitions = enum(open='open', close='close') CancellationState = enum(active='active', cancelled='cancelled') CancellationTransitions = enum(cancel='cancel', reinstate='reinstate') class JSONReadExtender(object): """- Adds the list of possible transitions to each object, if 'transitions' is specified in the include_fields. """ implements(IJSONReadExtender) def __init__(self, context): self.context = context def __call__(self, request, data): include_fields = get_include_fields(request) if not include_fields or "transitions" in include_fields: data['transitions'] = get_workflow_actions(self.context) @implementer(IWorkflowChain) def SamplePrepWorkflowChain(ob, wftool): """Responsible for inserting the optional sampling preparation workflow into the workflow chain for objects with ISamplePrepWorkflow This is only done if the object is in 'sample_prep' state in the primary workflow (review_state). """ # use catalog to retrieve review_state: getInfoFor causes recursion loop chain = list(ToolWorkflowChain(ob, wftool)) bc = getToolByName(ob, 'bika_catalog') proxies = bc(UID=ob.UID()) if not proxies or proxies[0].review_state != 'sample_prep': return chain sampleprep_workflow = ob.getPreparationWorkflow() if sampleprep_workflow: chain.append(sampleprep_workflow) return tuple(chain) def SamplePrepTransitionEventHandler(instance, event): """Sample preparation is considered complete when the sampleprep workflow reaches a state which has no exit transitions. If the stateis state's ID is the same as any AnalysisRequest primary workflow ID, then the AnalysisRequest will be sent directly to that state. If the final state's ID is not found in the AR workflow, the AR will be transitioned to 'sample_received'. """ if not event.transition: # creation doesn't have a 'transition' return if not event.new_state.getTransitions(): # Is this the final (No exit transitions) state? wftool = getToolByName(instance, 'portal_workflow') primary_wf_name = list(ToolWorkflowChain(instance, wftool))[0] primary_wf = wftool.getWorkflowById(primary_wf_name) primary_wf_states = primary_wf.states.keys() if event.new_state.id in primary_wf_states: # final state name matches review_state in primary workflow: dst_state = event.new_state.id else: # fallback state: dst_state = 'sample_received' changeWorkflowState(instance, primary_wf_name, dst_state) #!/usr/bin/env python """ Take the test runner log output from the stdin, looking for the magic line nose runner prints when the test run was successful. In an ideal world, this should be done directly in runtests.py using the nose API, some failure modes are fooling nose to terminate the python process with zero exit code, see, eg, https://github.com/scipy/scipy/issues/4736 In short, lapack's xerbla can terminate the process with a fortran level STOP command, which (i) aborts the py process so that runtests.py does not finish, and (ii) the exit code is implementation-defined. Also check that the number of tests run is larger than some baseline number (taken from the state of the master branch at some random point in time.) This probably could/should be made less brittle. """ from __future__ import print_function import sys import re if __name__ == "__main__": # full or fast test suite? try: testmode = sys.argv[1] if testmode not in ('fast', 'full'): raise IndexError except IndexError: raise ValueError("Usage: validate.py {full|fast} < logfile.") # fetch the expected number of tests # these numbers are for 6abad09 # XXX: this should probably track the commit hash or commit date expected_size = {'full': 19055, 'fast': 17738} # read in the log, parse for the nose printout: # Ran NNN tests in MMMs # # OK (SKIP=X, KNOWNFAIL=Y) or FAILED (errors=X, failures=Y) r = re.compile("Ran (?P\d+) tests in (?P