repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
MFoster/breeze
django/db/models/options.py
99
23148
from __future__ import unicode_literals import re from bisect import bisect from django.conf import settings from django.db.models.related import RelatedObject from django.db.models.fields.related import ManyToManyRel from django.db.models.fields import AutoField, FieldDoesNotExist from django.db.models.fields.proxy import OrderWrt from django.db.models.loading import get_models, app_cache_ready from django.utils import six from django.utils.datastructures import SortedDict from django.utils.encoding import force_text, smart_text, python_2_unicode_compatible from django.utils.translation import activate, deactivate_all, get_language, string_concat # Calculate the verbose_name by converting from InitialCaps to "lowercase with spaces". get_verbose_name = lambda class_name: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', class_name).lower().strip() DEFAULT_NAMES = ('verbose_name', 'verbose_name_plural', 'db_table', 'ordering', 'unique_together', 'permissions', 'get_latest_by', 'order_with_respect_to', 'app_label', 'db_tablespace', 'abstract', 'managed', 'proxy', 'swappable', 'auto_created', 'index_together') @python_2_unicode_compatible class Options(object): def __init__(self, meta, app_label=None): self.local_fields, self.local_many_to_many = [], [] self.virtual_fields = [] self.module_name, self.verbose_name = None, None self.verbose_name_plural = None self.db_table = '' self.ordering = [] self.unique_together = [] self.index_together = [] self.permissions = [] self.object_name, self.app_label = None, app_label self.get_latest_by = None self.order_with_respect_to = None self.db_tablespace = settings.DEFAULT_TABLESPACE self.admin = None self.meta = meta self.pk = None self.has_auto_field, self.auto_field = False, None self.abstract = False self.managed = True self.proxy = False # For any class that is a proxy (including automatically created # classes for deferred object loading), proxy_for_model tells us # which class this model is proxying. Note that proxy_for_model # can create a chain of proxy models. For non-proxy models, the # variable is always None. self.proxy_for_model = None # For any non-abstract class, the concrete class is the model # in the end of the proxy_for_model chain. In particular, for # concrete models, the concrete_model is always the class itself. self.concrete_model = None self.swappable = None self.parents = SortedDict() self.duplicate_targets = {} self.auto_created = False # To handle various inheritance situations, we need to track where # managers came from (concrete or abstract base classes). self.abstract_managers = [] self.concrete_managers = [] # List of all lookups defined in ForeignKey 'limit_choices_to' options # from *other* models. Needed for some admin checks. Internal use only. self.related_fkey_lookups = [] def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.util import truncate_name cls._meta = self self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS # First, construct the default values for these options. self.object_name = cls.__name__ self.module_name = self.object_name.lower() self.verbose_name = get_verbose_name(self.object_name) # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) # unique_together can be either a tuple of tuples, or a single # tuple of two strings. Normalize it to a tuple of tuples, so that # calling code can uniformly expect that. ut = meta_attrs.pop('unique_together', self.unique_together) if ut and not isinstance(ut[0], (tuple, list)): ut = (ut,) self.unique_together = ut # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = string_concat(self.verbose_name, 's') # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) else: self.verbose_name_plural = string_concat(self.verbose_name, 's') del self.meta # If the db_table wasn't provided, use the app_label + module_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.module_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) def _prepare(self, model): if self.order_with_respect_to: self.order_with_respect_to = self.get_field(self.order_with_respect_to) self.ordering = ('_order',) model.add_to_class('_order', OrderWrt()) else: self.order_with_respect_to = None if self.pk is None: if self.parents: # Promote the first parent link in lieu of adding yet another # field. field = next(six.itervalues(self.parents)) # Look for a local field with the same name as the # first parent link. If a local field has already been # created, use it instead of promoting the parent already_created = [fld for fld in self.local_fields if fld.name == field.name] if already_created: field = already_created[0] field.primary_key = True self.setup_pk(field) else: auto = AutoField(verbose_name='ID', primary_key=True, auto_created=True) model.add_to_class('id', auto) # Determine any sets of fields that are pointing to the same targets # (e.g. two ForeignKeys to the same remote model). The query # construction code needs to know this. At the end of this, # self.duplicate_targets will map each duplicate field column to the # columns it duplicates. collections = {} for column, target in six.iteritems(self.duplicate_targets): try: collections[target].add(column) except KeyError: collections[target] = set([column]) self.duplicate_targets = {} for elt in six.itervalues(collections): if len(elt) == 1: continue for column in elt: self.duplicate_targets[column] = elt.difference(set([column])) def add_field(self, field): # Insert the given field in the order in which it was created, using # the "creation_counter" attribute of the field. # Move many-to-many related fields from self.fields into # self.many_to_many. if field.rel and isinstance(field.rel, ManyToManyRel): self.local_many_to_many.insert(bisect(self.local_many_to_many, field), field) if hasattr(self, '_m2m_cache'): del self._m2m_cache else: self.local_fields.insert(bisect(self.local_fields, field), field) self.setup_pk(field) if hasattr(self, '_field_cache'): del self._field_cache del self._field_name_cache if hasattr(self, '_name_map'): del self._name_map def add_virtual_field(self, field): self.virtual_fields.append(field) def setup_pk(self, field): if not self.pk and field.primary_key: self.pk = field field.serialize = False def pk_index(self): """ Returns the index of the primary key field in the self.fields list. """ return self.fields.index(self.pk) def setup_proxy(self, target): """ Does the internal setup so that the current model is a proxy for "target". """ self.pk = target._meta.pk self.proxy_for_model = target self.db_table = target._meta.db_table def __repr__(self): return '<Options for %s>' % self.object_name def __str__(self): return "%s.%s" % (smart_text(self.app_label), smart_text(self.module_name)) def verbose_name_raw(self): """ There are a few places where the untranslated verbose name is needed (so that we get the same value regardless of currently active locale). """ lang = get_language() deactivate_all() raw = force_text(self.verbose_name) activate(lang) return raw verbose_name_raw = property(verbose_name_raw) def _swapped(self): """ Has this model been swapped out for another? If so, return the model name of the replacement; otherwise, return None. For historical reasons, model name lookups using get_model() are case insensitive, so we make sure we are case insensitive here. """ if self.swappable: model_label = '%s.%s' % (self.app_label, self.object_name.lower()) swapped_for = getattr(settings, self.swappable, None) if swapped_for: try: swapped_label, swapped_object = swapped_for.split('.') except ValueError: # setting not in the format app_label.model_name # raising ImproperlyConfigured here causes problems with # test cleanup code - instead it is raised in get_user_model # or as part of validation. return swapped_for if '%s.%s' % (swapped_label, swapped_object.lower()) not in (None, model_label): return swapped_for return None swapped = property(_swapped) def _fields(self): """ The getter for self.fields. This returns the list of field objects available to this model (including through parent models). Callers are not permitted to modify this list, since it's a reference to this instance (not a copy). """ try: self._field_name_cache except AttributeError: self._fill_fields_cache() return self._field_name_cache fields = property(_fields) def get_fields_with_model(self): """ Returns a sequence of (field, model) pairs for all fields. The "model" element is None for fields on the current model. Mostly of use when constructing queries so that we know which model a field belongs to. """ try: self._field_cache except AttributeError: self._fill_fields_cache() return self._field_cache def _fill_fields_cache(self): cache = [] for parent in self.parents: for field, model in parent._meta.get_fields_with_model(): if model: cache.append((field, model)) else: cache.append((field, parent)) cache.extend([(f, None) for f in self.local_fields]) self._field_cache = tuple(cache) self._field_name_cache = [x for x, _ in cache] def _many_to_many(self): try: self._m2m_cache except AttributeError: self._fill_m2m_cache() return list(self._m2m_cache) many_to_many = property(_many_to_many) def get_m2m_with_model(self): """ The many-to-many version of get_fields_with_model(). """ try: self._m2m_cache except AttributeError: self._fill_m2m_cache() return list(six.iteritems(self._m2m_cache)) def _fill_m2m_cache(self): cache = SortedDict() for parent in self.parents: for field, model in parent._meta.get_m2m_with_model(): if model: cache[field] = model else: cache[field] = parent for field in self.local_many_to_many: cache[field] = None self._m2m_cache = cache def get_field(self, name, many_to_many=True): """ Returns the requested field by name. Raises FieldDoesNotExist on error. """ to_search = many_to_many and (self.fields + self.many_to_many) or self.fields for f in to_search: if f.name == name: return f raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name)) def get_field_by_name(self, name): """ Returns the (field_object, model, direct, m2m), where field_object is the Field instance for the given name, model is the model containing this field (None for local fields), direct is True if the field exists on this model, and m2m is True for many-to-many relations. When 'direct' is False, 'field_object' is the corresponding RelatedObject for this field (since the field doesn't have an instance associated with it). Uses a cache internally, so after the first access, this is very fast. """ try: try: return self._name_map[name] except AttributeError: cache = self.init_name_map() return cache[name] except KeyError: raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name)) def get_all_field_names(self): """ Returns a list of all field names that are possible for this model (including reverse relation names). This is used for pretty printing debugging output (a list of choices), so any internal-only field names are not included. """ try: cache = self._name_map except AttributeError: cache = self.init_name_map() names = sorted(cache.keys()) # Internal-only names end with "+" (symmetrical m2m related names being # the main example). Trim them. return [val for val in names if not val.endswith('+')] def init_name_map(self): """ Initialises the field name -> field object mapping. """ cache = {} # We intentionally handle related m2m objects first so that symmetrical # m2m accessor names can be overridden, if necessary. for f, model in self.get_all_related_m2m_objects_with_model(): cache[f.field.related_query_name()] = (f, model, False, True) for f, model in self.get_all_related_objects_with_model(): cache[f.field.related_query_name()] = (f, model, False, False) for f, model in self.get_m2m_with_model(): cache[f.name] = (f, model, True, True) for f, model in self.get_fields_with_model(): cache[f.name] = (f, model, True, False) if app_cache_ready(): self._name_map = cache return cache def get_add_permission(self): return 'add_%s' % self.object_name.lower() def get_change_permission(self): return 'change_%s' % self.object_name.lower() def get_delete_permission(self): return 'delete_%s' % self.object_name.lower() def get_all_related_objects(self, local_only=False, include_hidden=False, include_proxy_eq=False): return [k for k, v in self.get_all_related_objects_with_model( local_only=local_only, include_hidden=include_hidden, include_proxy_eq=include_proxy_eq)] def get_all_related_objects_with_model(self, local_only=False, include_hidden=False, include_proxy_eq=False): """ Returns a list of (related-object, model) pairs. Similar to get_fields_with_model(). """ try: self._related_objects_cache except AttributeError: self._fill_related_objects_cache() predicates = [] if local_only: predicates.append(lambda k, v: not v) if not include_hidden: predicates.append(lambda k, v: not k.field.rel.is_hidden()) cache = (self._related_objects_proxy_cache if include_proxy_eq else self._related_objects_cache) return [t for t in cache.items() if all(p(*t) for p in predicates)] def _fill_related_objects_cache(self): cache = SortedDict() parent_list = self.get_parent_list() for parent in self.parents: for obj, model in parent._meta.get_all_related_objects_with_model(include_hidden=True): if (obj.field.creation_counter < 0 or obj.field.rel.parent_link) and obj.model not in parent_list: continue if not model: cache[obj] = parent else: cache[obj] = model # Collect also objects which are in relation to some proxy child/parent of self. proxy_cache = cache.copy() for klass in get_models(include_auto_created=True, only_installed=False): if not klass._meta.swapped: for f in klass._meta.local_fields: if f.rel and not isinstance(f.rel.to, six.string_types): if self == f.rel.to._meta: cache[RelatedObject(f.rel.to, klass, f)] = None proxy_cache[RelatedObject(f.rel.to, klass, f)] = None elif self.concrete_model == f.rel.to._meta.concrete_model: proxy_cache[RelatedObject(f.rel.to, klass, f)] = None self._related_objects_cache = cache self._related_objects_proxy_cache = proxy_cache def get_all_related_many_to_many_objects(self, local_only=False): try: cache = self._related_many_to_many_cache except AttributeError: cache = self._fill_related_many_to_many_cache() if local_only: return [k for k, v in cache.items() if not v] return list(cache) def get_all_related_m2m_objects_with_model(self): """ Returns a list of (related-m2m-object, model) pairs. Similar to get_fields_with_model(). """ try: cache = self._related_many_to_many_cache except AttributeError: cache = self._fill_related_many_to_many_cache() return list(six.iteritems(cache)) def _fill_related_many_to_many_cache(self): cache = SortedDict() parent_list = self.get_parent_list() for parent in self.parents: for obj, model in parent._meta.get_all_related_m2m_objects_with_model(): if obj.field.creation_counter < 0 and obj.model not in parent_list: continue if not model: cache[obj] = parent else: cache[obj] = model for klass in get_models(only_installed=False): if not klass._meta.swapped: for f in klass._meta.local_many_to_many: if (f.rel and not isinstance(f.rel.to, six.string_types) and self == f.rel.to._meta): cache[RelatedObject(f.rel.to, klass, f)] = None if app_cache_ready(): self._related_many_to_many_cache = cache return cache def get_base_chain(self, model): """ Returns a list of parent classes leading to 'model' (order from closet to most distant ancestor). This has to handle the case were 'model' is a granparent or even more distant relation. """ if not self.parents: return if model in self.parents: return [model] for parent in self.parents: res = parent._meta.get_base_chain(model) if res: res.insert(0, parent) return res raise TypeError('%r is not an ancestor of this model' % model._meta.module_name) def get_parent_list(self): """ Returns a list of all the ancestor of this model as a list. Useful for determining if something is an ancestor, regardless of lineage. """ result = set() for parent in self.parents: result.add(parent) result.update(parent._meta.get_parent_list()) return result def get_ancestor_link(self, ancestor): """ Returns the field on the current model which points to the given "ancestor". This is possible an indirect link (a pointer to a parent model, which points, eventually, to the ancestor). Used when constructing table joins for model inheritance. Returns None if the model isn't an ancestor of this one. """ if ancestor in self.parents: return self.parents[ancestor] for parent in self.parents: # Tries to get a link field from the immediate parent parent_link = parent._meta.get_ancestor_link(ancestor) if parent_link: # In case of a proxied model, the first link # of the chain to the ancestor is that parent # links return self.parents[parent] or parent_link def get_ordered_objects(self): "Returns a list of Options objects that are ordered with respect to this object." if not hasattr(self, '_ordered_objects'): objects = [] # TODO #for klass in get_models(get_app(self.app_label)): # opts = klass._meta # if opts.order_with_respect_to and opts.order_with_respect_to.rel \ # and self == opts.order_with_respect_to.rel.to._meta: # objects.append(opts) self._ordered_objects = objects return self._ordered_objects
bsd-3-clause
rcocetta/kano-profile
kano_profile/apps.py
1
3777
#!/usr/bin/env python # apps.py # # Copyright (C) 2014, 2015 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 # import os from kano.utils import read_json, write_json, get_date_now, ensure_dir, \ chown_path, run_print_output_error from kano.logging import logger from .paths import apps_dir, xp_file, kanoprofile_dir, app_profiles_file def get_app_dir(app_name): app_dir = os.path.join(apps_dir, app_name) return app_dir def get_app_data_dir(app_name): data_str = 'data' app_data_dir = os.path.join(get_app_dir(app_name), data_str) return app_data_dir def get_app_state_file(app_name): app_state_str = 'state.json' app_state_file = os.path.join(get_app_dir(app_name), app_state_str) return app_state_file def load_app_state(app_name): app_state_file = get_app_state_file(app_name) app_state = read_json(app_state_file) if not app_state: app_state = dict() return app_state def load_app_state_variable(app_name, variable): data = load_app_state(app_name) if variable in data: return data[variable] def save_app_state(app_name, data): """ Save a state of an application to the user's Kano profile. :param app_name: The application that this data are associated with. :type app_name: str :param data: The data to be stored. :type data: dict """ logger.debug('save_app_state {}'.format(app_name)) app_state_file = get_app_state_file(app_name) data['save_date'] = get_date_now() ensure_dir(get_app_dir(app_name)) write_json(app_state_file, data) if 'SUDO_USER' in os.environ: chown_path(kanoprofile_dir) chown_path(apps_dir) chown_path(get_app_dir(app_name)) chown_path(app_state_file) def save_app_state_variable(app_name, variable, value): """ Save a state variable to the user's Kano profile. :param app_name: The application that this variable is associated with. :type app_name: str :param variable: The name of the variable. :type data: str :param data: The variable data to be stored. :type data: any """ msg = 'save_app_state_variable {} {} {}'.format(app_name, variable, value) logger.debug(msg) data = load_app_state(app_name) data[variable] = value save_app_state(app_name, data) def increment_app_state_variable(app_name, variable, value): logger.debug( 'increment_app_state_variable {} {} {}'.format( app_name, variable, value)) data = load_app_state(app_name) if variable not in data: data[variable] = 0 data[variable] += value save_app_state(app_name, data) def get_app_list(): if not os.path.exists(apps_dir): return [] else: return [p for p in os.listdir(apps_dir) if os.path.isdir(os.path.join(apps_dir, p))] def get_gamestate_variables(app_name): allrules = read_json(xp_file) if not allrules: return list() groups = allrules[app_name] for group, rules in groups.iteritems(): if group == 'multipliers': return [str(key) for key in rules.keys()] def launch_project(app, filename, data_dir): logger.info('launch_project: {} {} {}'.format(app, filename, data_dir)) app_profiles = read_json(app_profiles_file) fullpath = os.path.join(data_dir, filename) cmd = app_profiles[app]['cmd'].format(fullpath=fullpath, filename=filename) _, _, rc = run_print_output_error(cmd) return rc def get_app_xp_for_challenge(app, challenge_no): xp_file_json = read_json(xp_file) try: return xp_file_json[app]['level'][challenge_no] except KeyError: return 0
gpl-2.0
ThirdProject/android_external_chromium_org
tools/perf/measurements/endure.py
23
6579
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import re import time from metrics import v8_object_stats from telemetry.page import page_measurement _V8_BYTES_COMMITTED = [ 'V8.MemoryNewSpaceBytesCommitted', 'V8.MemoryOldPointerSpaceBytesCommitted', 'V8.MemoryOldDataSpaceBytesCommitted', 'V8.MemoryCodeSpaceBytesCommitted', 'V8.MemoryMapSpaceBytesCommitted', 'V8.MemoryCellSpaceBytesCommitted', 'V8.MemoryPropertyCellSpaceBytesCommitted', 'V8.MemoryLoSpaceBytesCommitted' ] _V8_BYTES_USED = [ 'V8.MemoryNewSpaceBytesUsed', 'V8.MemoryOldPointerSpaceBytesUsed', 'V8.MemoryOldDataSpaceBytesUsed', 'V8.MemoryCodeSpaceBytesUsed', 'V8.MemoryMapSpaceBytesUsed', 'V8.MemoryCellSpaceBytesUsed', 'V8.MemoryPropertyCellSpaceBytesUsed', 'V8.MemoryLoSpaceBytesUsed' ] _V8_MEMORY_ALLOCATED = [ 'V8.OsMemoryAllocated' ] class Endure(page_measurement.PageMeasurement): def __init__(self): super(Endure, self).__init__('endure') # Browser object, saved so that memory stats can be gotten later. self._browser = None # Timestamp for the time when the test starts. self._start_time = None # Timestamp of the last statistics sample. self._last_sample_time = 0 # Number of page repetitions that have currently been done. self._iterations = 0 # Number of page repetitions at the point of the last statistics sample. self._last_sample_iterations = 0 # One of these variables will be set when the perf stats interval option # is parsed, and the other shall remain as None. self._interval_seconds = None self._interval_iterations = None def AddCommandLineOptions(self, parser): # TODO(tdu): When ProcessCommandLine is added to replace this method, # move the logic in _ParseIntervalOption there to ProcessCommandLine. group = optparse.OptionGroup(parser, 'Endure options') group.add_option('--perf-stats-interval', dest='perf_stats_interval', default='20s', type='string', help='Interval between sampling of statistics, either in ' 'seconds (specified by appending \'s\') or in number ' 'of iterations') parser.add_option_group(group) def DidStartBrowser(self, browser): # Save the Browser object so that memory_stats can be gotten later. self._browser = browser def CustomizeBrowserOptions(self, options): v8_object_stats.V8ObjectStatsMetric.CustomizeBrowserOptions(options) def CanRunForPage(self, page): return hasattr(page, 'endure') def WillRunPageRepeats(self, page): """Set-up before starting a new page.""" # Reset the starting time for each new page. self._start_time = time.time() # Prefix the page name so it can be picked up by the buildbot script that # parses Endure output. if page.name and not page.display_name.startswith('endure_'): page.name = 'endure_' + page.name def MeasurePage(self, page, tab, results): """Sample perf information if enough seconds or iterations have passed.""" # Parse the interval option, setting either or seconds or iterations. # This is done here because self.options is not set when any of the above # methods are run. self._ParseIntervalOption() # Check whether the sample interval is specified in seconds or iterations, # and take a sample if it's time. self._iterations += 1 if self._interval_seconds: now = time.time() seconds_elapsed = int(round(now - self._last_sample_time)) # Note: the time since last sample must be at least as many seconds # as specified; it will usually be more, it will never be less. if seconds_elapsed >= self._interval_seconds: total_seconds = int(round(now - self._start_time)) self._SampleStats(tab, results, seconds=total_seconds) self._last_sample_time = now else: iterations_elapsed = self._iterations - self._last_sample_iterations if iterations_elapsed >= self._interval_iterations: self._SampleStats(tab, results, iterations=self._iterations) self._last_sample_iterations = self._iterations def _ParseIntervalOption(self): """Parse the perf stats interval option that was passed in.""" if self._interval_seconds or self._interval_iterations: return interval = self.options.perf_stats_interval match = re.match('([0-9]+)([sS]?)$', interval) assert match, ('Invalid value for --perf-stats-interval: %s' % interval) if match.group(2): self._interval_seconds = int(match.group(1)) else: self._interval_iterations = int(match.group(1)) assert self._interval_seconds or self._interval_iterations def _SampleStats(self, tab, results, seconds=None, iterations=None): """Record memory information and add it to the results.""" def AddPoint(trace_name, units_y, value_y): """Add one data point to the results object.""" if seconds: results.Add(trace_name + '_X', 'seconds', seconds) else: assert iterations, 'Neither seconds nor iterations given.' results.Add(trace_name + '_X', 'iterations', iterations) results.Add(trace_name + '_Y', units_y, value_y) # DOM nodes and event listeners dom_stats = tab.dom_stats dom_node_count = dom_stats['node_count'] event_listener_count = dom_stats['event_listener_count'] AddPoint('dom_nodes', 'count', dom_node_count) AddPoint('event_listeners', 'count', event_listener_count) # Browser and renderer virtual memory stats memory_stats = self._browser.memory_stats def BrowserVMStats(statistic_name): """Get VM stats from the Browser object in KB.""" return memory_stats[statistic_name].get('VM', 0) / 1024.0 AddPoint('browser_vm', 'KB', BrowserVMStats('Browser')) AddPoint('renderer_vm', 'KB', BrowserVMStats('Renderer')) AddPoint('gpu_vm', 'KB', BrowserVMStats('Gpu')) # V8 stats def V8StatsSum(counters): """Given a list of V8 counter names, get the sum of the values in KB.""" stats = v8_object_stats.V8ObjectStatsMetric.GetV8StatsTable(tab, counters) return sum(stats.values()) / 1024.0 AddPoint('v8_memory_committed', 'KB', V8StatsSum(_V8_BYTES_COMMITTED)) AddPoint('v8_memory_used', 'KB', V8StatsSum(_V8_BYTES_USED)) AddPoint('v8_memory_allocated', 'KB', V8StatsSum(_V8_MEMORY_ALLOCATED))
bsd-3-clause
wolfram74/numerical_methods_iserles_notes
venv/lib/python2.7/site-packages/sympy/combinatorics/group_constructs.py
25
2032
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 xrange _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 xrange(len(gens_count)): for j in xrange(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)
mit
ff94315/hiwifi-openwrt-HC5661-HC5761
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/usr/lib/python2.7/ctypes/test/test_init.py
113
1045
from ctypes import * import unittest class X(Structure): _fields_ = [("a", c_int), ("b", c_int)] new_was_called = False def __new__(cls): result = super(X, cls).__new__(cls) result.new_was_called = True return result def __init__(self): self.a = 9 self.b = 12 class Y(Structure): _fields_ = [("x", X)] class InitTest(unittest.TestCase): def test_get(self): # make sure the only accessing a nested structure # doesn't call the structure's __new__ and __init__ y = Y() self.assertEqual((y.x.a, y.x.b), (0, 0)) self.assertEqual(y.x.new_was_called, False) # But explicitly creating an X structure calls __new__ and __init__, of course. x = X() self.assertEqual((x.a, x.b), (9, 12)) self.assertEqual(x.new_was_called, True) y.x = x self.assertEqual((y.x.a, y.x.b), (9, 12)) self.assertEqual(y.x.new_was_called, False) if __name__ == "__main__": unittest.main()
gpl-2.0
nicky-ji/edx-nicky
lms/djangoapps/bulk_email/migrations/0004_migrate_optout_user.py
182
6009
# -*- coding: utf-8 -*- from south.db import db from south.v2 import DataMigration from django.core.exceptions import ObjectDoesNotExist class Migration(DataMigration): def forwards(self, orm): # forwards data migration to copy over existing emails to associated ids if not db.dry_run: for optout in orm.Optout.objects.all(): try: user = orm['auth.User'].objects.get(email=optout.email) optout.user = user optout.save() except ObjectDoesNotExist: # if user is not found (because they have already changed their email) # then delete the optout, as it's no longer useful. optout.delete() def backwards(self, orm): # backwards data migration to copy over emails of students to old email slot if not db.dry_run: for optout in orm.Optout.objects.all(): if optout.user is not None: optout.email = optout.user.email optout.save() models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'bulk_email.courseemail': { 'Meta': {'object_name': 'CourseEmail'}, 'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'html_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'sender': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '128', 'db_index': 'True'}), 'subject': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'text_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'to_option': ('django.db.models.fields.CharField', [], {'default': "'myself'", 'max_length': '64'}) }, 'bulk_email.optout': { 'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'Optout'}, 'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'email': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}) }, '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'}) } } complete_apps = ['bulk_email']
agpl-3.0
ConPaaS-team/conpaas
conpaas-services/contrib/memcache.py
3
45957
#!/usr/bin/env python """ client module for memcached (memory cache daemon) Overview ======== See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached. Usage summary ============= This should give you a feel for how this module operates:: import memcache mc = memcache.Client(['127.0.0.1:11211'], debug=0) mc.set("some_key", "Some value") value = mc.get("some_key") mc.set("another_key", 3) mc.delete("another_key") mc.set("key", "1") # note that the key used for incr/decr must be a string. mc.incr("key") mc.decr("key") The standard way to use memcache with a database is like this:: key = derive_key(obj) obj = mc.get(key) if not obj: obj = backend_api.get(...) mc.set(key, obj) # we now have obj, and future passes through this code # will use the object from the cache. Detailed Documentation ====================== More detailed documentation is available in the L{Client} class. """ import sys import socket import time import os import re try: import cPickle as pickle except ImportError: import pickle from binascii import crc32 # zlib version is not cross-platform def cmemcache_hash(key): return((((crc32(key) & 0xffffffff) >> 16) & 0x7fff) or 1) serverHashFunction = cmemcache_hash def useOldServerHashFunction(): """Use the old python-memcache server hash function.""" global serverHashFunction serverHashFunction = crc32 try: from zlib import compress, decompress _supports_compress = True except ImportError: _supports_compress = False # quickly define a decompress just in case we recv compressed data. def decompress(val): raise _Error("received compressed data but I don't support compression (import error)") try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # Original author: Evan Martin of Danga Interactive __author__ = "Sean Reifschneider <jafo-memcached@tummy.com>" __version__ = "1.47" __copyright__ = "Copyright (C) 2003 Danga Interactive" # http://en.wikipedia.org/wiki/Python_Software_Foundation_License __license__ = "Python Software Foundation License" SERVER_MAX_KEY_LENGTH = 250 # Storing values larger than 1MB requires recompiling memcached. If you do, # this value can be changed by doing "memcache.SERVER_MAX_VALUE_LENGTH = N" # after importing this module. SERVER_MAX_VALUE_LENGTH = 1024*1024 class _Error(Exception): pass try: # Only exists in Python 2.4+ from threading import local except ImportError: # TODO: add the pure-python local implementation class local(object): pass class Client(local): """ Object representing a pool of memcache servers. See L{memcache} for an overview. In all cases where a key is used, the key can be either: 1. A simple hashable type (string, integer, etc.). 2. A tuple of C{(hashvalue, key)}. This is useful if you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @group Setup: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog @group Insertion: set, add, replace, set_multi @group Retrieval: get, get_multi @group Integers: incr, decr @group Removal: delete, delete_multi @sort: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog,\ set, set_multi, add, replace, get, get_multi, incr, decr, delete, delete_multi """ _FLAG_PICKLE = 1<<0 _FLAG_INTEGER = 1<<1 _FLAG_LONG = 1<<2 _FLAG_COMPRESSED = 1<<3 _SERVER_RETRIES = 10 # how many times to try finding a free server. # exceptions for Client class MemcachedKeyError(Exception): pass class MemcachedKeyLengthError(MemcachedKeyError): pass class MemcachedKeyCharacterError(MemcachedKeyError): pass class MemcachedKeyNoneError(MemcachedKeyError): pass class MemcachedKeyTypeError(MemcachedKeyError): pass class MemcachedStringEncodingError(Exception): pass def __init__(self, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None, server_max_key_length=SERVER_MAX_KEY_LENGTH, server_max_value_length=SERVER_MAX_VALUE_LENGTH): """ Create a new Client object with the given list of servers. @param servers: C{servers} is passed to L{set_servers}. @param debug: whether to display error messages when a server can't be contacted. @param pickleProtocol: number to mandate protocol used by (c)Pickle. @param pickler: optional override of default Pickler to allow subclassing. @param unpickler: optional override of default Unpickler to allow subclassing. @param pload: optional persistent_load function to call on pickle loading. Useful for cPickle since subclassing isn't allowed. @param pid: optional persistent_id function to call on pickle storing. Useful for cPickle since subclassing isn't allowed. """ local.__init__(self) self.debug = debug self.set_servers(servers) self.stats = {} self.cas_ids = {} # Allow users to modify pickling/unpickling behavior self.pickleProtocol = pickleProtocol self.pickler = pickler self.unpickler = unpickler self.persistent_load = pload self.persistent_id = pid self.server_max_key_length = server_max_key_length self.server_max_value_length = server_max_value_length # figure out the pickler style file = StringIO() try: pickler = self.pickler(file, protocol = self.pickleProtocol) self.picklerIsKeyword = True except TypeError: self.picklerIsKeyword = False def set_servers(self, servers): """ Set the pool of servers used by this client. @param servers: an array of servers. Servers can be passed in two forms: 1. Strings of the form C{"host:port"}, which implies a default weight of 1. 2. Tuples of the form C{("host:port", weight)}, where C{weight} is an integer weight value. """ self.servers = [_Host(s, self.debug) for s in servers] self._init_buckets() def get_stats(self, stat_args = None): '''Get statistics from each of the servers. @param stat_args: Additional arguments to pass to the memcache "stats" command. @return: A list of tuples ( server_identifier, stats_dictionary ). The dictionary contains a number of name/value pairs specifying the name of the status field and the string value associated with it. The values are not converted from strings. ''' data = [] for s in self.servers: if not s.connect(): continue if s.family == socket.AF_INET: name = '%s:%s (%s)' % ( s.ip, s.port, s.weight ) else: name = 'unix:%s (%s)' % ( s.address, s.weight ) if not stat_args: s.send_cmd('stats') else: s.send_cmd('stats ' + stat_args) serverData = {} data.append(( name, serverData )) readline = s.readline while 1: line = readline() if not line or line.strip() == 'END': break stats = line.split(' ', 2) serverData[stats[1]] = stats[2] return(data) def get_slabs(self): data = [] for s in self.servers: if not s.connect(): continue if s.family == socket.AF_INET: name = '%s:%s (%s)' % ( s.ip, s.port, s.weight ) else: name = 'unix:%s (%s)' % ( s.address, s.weight ) serverData = {} data.append(( name, serverData )) s.send_cmd('stats items') readline = s.readline while 1: line = readline() if not line or line.strip() == 'END': break item = line.split(' ', 2) #0 = STAT, 1 = ITEM, 2 = Value slab = item[1].split(':', 2) #0 = items, 1 = Slab #, 2 = Name if slab[1] not in serverData: serverData[slab[1]] = {} serverData[slab[1]][slab[2]] = item[2] return data def flush_all(self): 'Expire all data currently in the memcache servers.' for s in self.servers: if not s.connect(): continue s.send_cmd('flush_all') s.expect("OK") def debuglog(self, str): if self.debug: sys.stderr.write("MemCached: %s\n" % str) def _statlog(self, func): if func not in self.stats: self.stats[func] = 1 else: self.stats[func] += 1 def forget_dead_hosts(self): """ Reset every host in the pool to an "alive" state. """ for s in self.servers: s.deaduntil = 0 def _init_buckets(self): self.buckets = [] for server in self.servers: for i in range(server.weight): self.buckets.append(server) def _get_server(self, key): if isinstance(key, tuple): serverhash, key = key else: serverhash = serverHashFunction(key) for i in range(Client._SERVER_RETRIES): server = self.buckets[serverhash % len(self.buckets)] if server.connect(): #print "(using server %s)" % server, return server, key serverhash = serverHashFunction(str(serverhash) + str(i)) return None, None def disconnect_all(self): for s in self.servers: s.close_socket() def delete_multi(self, keys, time=0, key_prefix=''): ''' Delete multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'} 1 >>> mc.delete_multi(['key1', 'key2']) 1 >>> mc.get_multi(['key1', 'key2']) == {} 1 This method is recommended over iterated regular L{delete}s as it reduces total latency, since your app doesn't have to wait for each round-trip of L{delete} before sending the next one. @param keys: An iterable of keys to clear @param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay. @param key_prefix: Optional string to prepend to each key when sending to memcache. See docs for L{get_multi} and L{set_multi}. @return: 1 if no failure in communication with any memcacheds. @rtype: int ''' self._statlog('delete_multi') server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix) # send out all requests on each server before reading anything dead_servers = [] rc = 1 for server in server_keys.iterkeys(): bigcmd = [] write = bigcmd.append if time != None: for key in server_keys[server]: # These are mangled keys write("delete %s %d\r\n" % (key, time)) else: for key in server_keys[server]: # These are mangled keys write("delete %s\r\n" % key) try: server.send_cmds(''.join(bigcmd)) except socket.error, msg: rc = 0 if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) dead_servers.append(server) # if any servers died on the way, don't expect them to respond. for server in dead_servers: del server_keys[server] for server, keys in server_keys.iteritems(): try: for key in keys: server.expect("DELETED") except socket.error, msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) rc = 0 return rc def delete(self, key, time=0): '''Deletes a key from the memcache. @return: Nonzero on success. @param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay. @rtype: int ''' self.check_key(key) server, key = self._get_server(key) if not server: return 0 self._statlog('delete') if time != None: cmd = "delete %s %d" % (key, time) else: cmd = "delete %s" % key try: server.send_cmd(cmd) line = server.readline() if line and line.strip() in ['DELETED', 'NOT_FOUND']: return 1 self.debuglog('Delete expected DELETED or NOT_FOUND, got: %s' % repr(line)) except socket.error, msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return 0 def incr(self, key, delta=1): """ Sends a command to the server to atomically increment the value for C{key} by C{delta}, or by 1 if C{delta} is unspecified. Returns None if C{key} doesn't exist on server, otherwise it returns the new value after incrementing. Note that the value for C{key} must already exist in the memcache, and it must be the string representation of an integer. >>> mc.set("counter", "20") # returns 1, indicating success 1 >>> mc.incr("counter") 21 >>> mc.incr("counter") 22 Overflow on server is not checked. Be aware of values approaching 2**32. See L{decr}. @param delta: Integer amount to increment by (should be zero or greater). @return: New value after incrementing. @rtype: int """ return self._incrdecr("incr", key, delta) def decr(self, key, delta=1): """ Like L{incr}, but decrements. Unlike L{incr}, underflow is checked and new values are capped at 0. If server value is 1, a decrement of 2 returns 0, not -1. @param delta: Integer amount to decrement by (should be zero or greater). @return: New value after decrementing. @rtype: int """ return self._incrdecr("decr", key, delta) def _incrdecr(self, cmd, key, delta): self.check_key(key) server, key = self._get_server(key) if not server: return 0 self._statlog(cmd) cmd = "%s %s %d" % (cmd, key, delta) try: server.send_cmd(cmd) line = server.readline() if line == None or line.strip() =='NOT_FOUND': return None return int(line) except socket.error, msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return None def add(self, key, val, time = 0, min_compress_len = 0): ''' Add new key with value. Like L{set}, but only stores in memcache if the key doesn't already exist. @return: Nonzero on success. @rtype: int ''' return self._set("add", key, val, time, min_compress_len) def append(self, key, val, time=0, min_compress_len=0): '''Append the value to the end of the existing key's value. Only stores in memcache if key already exists. Also see L{prepend}. @return: Nonzero on success. @rtype: int ''' return self._set("append", key, val, time, min_compress_len) def prepend(self, key, val, time=0, min_compress_len=0): '''Prepend the value to the beginning of the existing key's value. Only stores in memcache if key already exists. Also see L{append}. @return: Nonzero on success. @rtype: int ''' return self._set("prepend", key, val, time, min_compress_len) def replace(self, key, val, time=0, min_compress_len=0): '''Replace existing key with value. Like L{set}, but only stores in memcache if the key already exists. The opposite of L{add}. @return: Nonzero on success. @rtype: int ''' return self._set("replace", key, val, time, min_compress_len) def set(self, key, val, time=0, min_compress_len=0): '''Unconditionally sets a key to a given value in the memcache. The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @return: Nonzero on success. @rtype: int @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param min_compress_len: The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. ''' return self._set("set", key, val, time, min_compress_len) def cas(self, key, val, time=0, min_compress_len=0): '''Sets a key to a given value in the memcache if it hasn't been altered since last fetched. (See L{gets}). The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @return: Nonzero on success. @rtype: int @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param min_compress_len: The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. ''' return self._set("cas", key, val, time, min_compress_len) def _map_and_prefix_keys(self, key_iterable, key_prefix): """Compute the mapping of server (_Host instance) -> list of keys to stuff onto that server, as well as the mapping of prefixed key -> original key. """ # Check it just once ... key_extra_len=len(key_prefix) if key_prefix: self.check_key(key_prefix) # server (_Host) -> list of unprefixed server keys in mapping server_keys = {} prefixed_to_orig_key = {} # build up a list for each server of all the keys we want. for orig_key in key_iterable: if isinstance(orig_key, tuple): # Tuple of hashvalue, key ala _get_server(). Caller is essentially telling us what server to stuff this on. # Ensure call to _get_server gets a Tuple as well. str_orig_key = str(orig_key[1]) server, key = self._get_server((orig_key[0], key_prefix + str_orig_key)) # Gotta pre-mangle key before hashing to a server. Returns the mangled key. else: str_orig_key = str(orig_key) # set_multi supports int / long keys. server, key = self._get_server(key_prefix + str_orig_key) # Now check to make sure key length is proper ... self.check_key(str_orig_key, key_extra_len=key_extra_len) if not server: continue if server not in server_keys: server_keys[server] = [] server_keys[server].append(key) prefixed_to_orig_key[key] = orig_key return (server_keys, prefixed_to_orig_key) def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0): ''' Sets multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'} 1 This method is recommended over regular L{set} as it lowers the number of total packets flying around your network, reducing total latency, since your app doesn't have to wait for each round-trip of L{set} before sending the next one. @param mapping: A dict of key/value pairs to set. @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param key_prefix: Optional string to prepend to each key when sending to memcache. Allows you to efficiently stuff these keys into a pseudo-namespace in memcache: >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}, key_prefix='subspace_') >>> len(notset_keys) == 0 True >>> mc.get_multi(['subspace_key1', 'subspace_key2']) == {'subspace_key1' : 'val1', 'subspace_key2' : 'val2'} True Causes key 'subspace_key1' and 'subspace_key2' to be set. Useful in conjunction with a higher-level layer which applies namespaces to data in memcache. In this case, the return result would be the list of notset original keys, prefix not applied. @param min_compress_len: The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. @return: List of keys which failed to be stored [ memcache out of memory, etc. ]. @rtype: list ''' self._statlog('set_multi') server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(mapping.iterkeys(), key_prefix) # send out all requests on each server before reading anything dead_servers = [] notstored = [] # original keys. for server in server_keys.iterkeys(): bigcmd = [] write = bigcmd.append try: for key in server_keys[server]: # These are mangled keys store_info = self._val_to_store_info( mapping[prefixed_to_orig_key[key]], min_compress_len) if store_info: write("set %s %d %d %d\r\n%s\r\n" % (key, store_info[0], time, store_info[1], store_info[2])) else: notstored.append(prefixed_to_orig_key[key]) server.send_cmds(''.join(bigcmd)) except socket.error, msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) dead_servers.append(server) # if any servers died on the way, don't expect them to respond. for server in dead_servers: del server_keys[server] # short-circuit if there are no servers, just return all keys if not server_keys: return(mapping.keys()) for server, keys in server_keys.iteritems(): try: for key in keys: line = server.readline() if line == 'STORED': continue else: notstored.append(prefixed_to_orig_key[key]) #un-mangle. except (_Error, socket.error), msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return notstored def _val_to_store_info(self, val, min_compress_len): """ Transform val to a storable representation, returning a tuple of the flags, the length of the new value, and the new value itself. """ flags = 0 if isinstance(val, str): pass elif isinstance(val, int): flags |= Client._FLAG_INTEGER val = "%d" % val # force no attempt to compress this silly string. min_compress_len = 0 elif isinstance(val, long): flags |= Client._FLAG_LONG val = "%d" % val # force no attempt to compress this silly string. min_compress_len = 0 else: flags |= Client._FLAG_PICKLE file = StringIO() if self.picklerIsKeyword: pickler = self.pickler(file, protocol = self.pickleProtocol) else: pickler = self.pickler(file, self.pickleProtocol) if self.persistent_id: pickler.persistent_id = self.persistent_id pickler.dump(val) val = file.getvalue() lv = len(val) # We should try to compress if min_compress_len > 0 and we could # import zlib and this string is longer than our min threshold. if min_compress_len and _supports_compress and lv > min_compress_len: comp_val = compress(val) # Only retain the result if the compression result is smaller # than the original. if len(comp_val) < lv: flags |= Client._FLAG_COMPRESSED val = comp_val # silently do not store if value length exceeds maximum if self.server_max_value_length != 0 and \ len(val) >= self.server_max_value_length: return(0) return (flags, len(val), val) def _set(self, cmd, key, val, time, min_compress_len = 0): self.check_key(key) server, key = self._get_server(key) if not server: return 0 self._statlog(cmd) store_info = self._val_to_store_info(val, min_compress_len) if not store_info: return(0) if cmd == 'cas': if key not in self.cas_ids: return self._set('set', key, val, time, min_compress_len) fullcmd = "%s %s %d %d %d %d\r\n%s" % ( cmd, key, store_info[0], time, store_info[1], self.cas_ids[key], store_info[2]) else: fullcmd = "%s %s %d %d %d\r\n%s" % ( cmd, key, store_info[0], time, store_info[1], store_info[2]) try: server.send_cmd(fullcmd) return(server.expect("STORED") == "STORED") except socket.error, msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return 0 def _get(self, cmd, key): self.check_key(key) server, key = self._get_server(key) if not server: return None self._statlog(cmd) try: server.send_cmd("%s %s" % (cmd, key)) rkey = flags = rlen = cas_id = None if cmd == 'gets': rkey, flags, rlen, cas_id, = self._expect_cas_value(server) if rkey: self.cas_ids[rkey] = cas_id else: rkey, flags, rlen, = self._expectvalue(server) if not rkey: return None value = self._recv_value(server, flags, rlen) server.expect("END") except (_Error, socket.error), msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return None return value def get(self, key): '''Retrieves a key from the memcache. @return: The value or None. ''' return self._get('get', key) def gets(self, key): '''Retrieves a key from the memcache. Used in conjunction with 'cas'. @return: The value or None. ''' return self._get('gets', key) def get_multi(self, keys, key_prefix=''): ''' Retrieves multiple keys from the memcache doing just one query. >>> success = mc.set("foo", "bar") >>> success = mc.set("baz", 42) >>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42} 1 >>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == [] 1 This looks up keys 'pfx_k1', 'pfx_k2', ... . Returned dict will just have unprefixed keys 'k1', 'k2'. >>> mc.get_multi(['k1', 'k2', 'nonexist'], key_prefix='pfx_') == {'k1' : 1, 'k2' : 2} 1 get_mult [ and L{set_multi} ] can take str()-ables like ints / longs as keys too. Such as your db pri key fields. They're rotored through str() before being passed off to memcache, with or without the use of a key_prefix. In this mode, the key_prefix could be a table name, and the key itself a db primary key number. >>> mc.set_multi({42: 'douglass adams', 46 : 'and 2 just ahead of me'}, key_prefix='numkeys_') == [] 1 >>> mc.get_multi([46, 42], key_prefix='numkeys_') == {42: 'douglass adams', 46 : 'and 2 just ahead of me'} 1 This method is recommended over regular L{get} as it lowers the number of total packets flying around your network, reducing total latency, since your app doesn't have to wait for each round-trip of L{get} before sending the next one. See also L{set_multi}. @param keys: An array of keys. @param key_prefix: A string to prefix each key when we communicate with memcache. Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix. @return: A dictionary of key/value pairs that were available. If key_prefix was provided, the keys in the retured dictionary will not have it present. ''' self._statlog('get_multi') server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix) # send out all requests on each server before reading anything dead_servers = [] for server in server_keys.iterkeys(): try: server.send_cmd("get %s" % " ".join(server_keys[server])) except socket.error, msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) dead_servers.append(server) # if any servers died on the way, don't expect them to respond. for server in dead_servers: del server_keys[server] retvals = {} for server in server_keys.iterkeys(): try: line = server.readline() while line and line != 'END': rkey, flags, rlen = self._expectvalue(server, line) # Bo Yang reports that this can sometimes be None if rkey is not None: val = self._recv_value(server, flags, rlen) retvals[prefixed_to_orig_key[rkey]] = val # un-prefix returned key. line = server.readline() except (_Error, socket.error), msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return retvals def _expect_cas_value(self, server, line=None): if not line: line = server.readline() if line and line[:5] == 'VALUE': resp, rkey, flags, len, cas_id = line.split() return (rkey, int(flags), int(len), int(cas_id)) else: return (None, None, None, None) def _expectvalue(self, server, line=None): if not line: line = server.readline() if line and line[:5] == 'VALUE': resp, rkey, flags, len = line.split() flags = int(flags) rlen = int(len) return (rkey, flags, rlen) else: return (None, None, None) def _recv_value(self, server, flags, rlen): rlen += 2 # include \r\n buf = server.recv(rlen) if len(buf) != rlen: raise _Error("received %d bytes when expecting %d" % (len(buf), rlen)) if len(buf) == rlen: buf = buf[:-2] # strip \r\n if flags & Client._FLAG_COMPRESSED: buf = decompress(buf) if flags == 0 or flags == Client._FLAG_COMPRESSED: # Either a bare string or a compressed string now decompressed... val = buf elif flags & Client._FLAG_INTEGER: val = int(buf) elif flags & Client._FLAG_LONG: val = long(buf) elif flags & Client._FLAG_PICKLE: try: file = StringIO(buf) unpickler = self.unpickler(file) if self.persistent_load: unpickler.persistent_load = self.persistent_load val = unpickler.load() except Exception, e: self.debuglog('Pickle error: %s\n' % e) val = None else: self.debuglog("unknown flags on get: %x\n" % flags) return val def check_key(self, key, key_extra_len=0): """Checks sanity of key. Fails if: Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength). Contains control characters (Raises MemcachedKeyCharacterError). Is not a string (Raises MemcachedStringEncodingError) Is an unicode string (Raises MemcachedStringEncodingError) Is not a string (Raises MemcachedKeyError) Is None (Raises MemcachedKeyError) """ if isinstance(key, tuple): key = key[1] if not key: raise Client.MemcachedKeyNoneError("Key is None") if isinstance(key, unicode): raise Client.MemcachedStringEncodingError( "Keys must be str()'s, not unicode. Convert your unicode " "strings using mystring.encode(charset)!") if not isinstance(key, str): raise Client.MemcachedKeyTypeError("Key must be str()'s") if isinstance(key, basestring): if self.server_max_key_length != 0 and \ len(key) + key_extra_len > self.server_max_key_length: raise Client.MemcachedKeyLengthError("Key length is > %s" % self.server_max_key_length) for char in key: if ord(char) < 33 or ord(char) == 127: raise Client.MemcachedKeyCharacterError( "Control characters not allowed") class _Host(object): _DEAD_RETRY = 30 # number of seconds before retrying a dead server. _SOCKET_TIMEOUT = 3 # number of seconds before sockets timeout. def __init__(self, host, debug=0): self.debug = debug if isinstance(host, tuple): host, self.weight = host else: self.weight = 1 # parse the connection string m = re.match(r'^(?P<proto>unix):(?P<path>.*)$', host) if not m: m = re.match(r'^(?P<proto>inet):' r'(?P<host>[^:]+)(:(?P<port>[0-9]+))?$', host) if not m: m = re.match(r'^(?P<host>[^:]+)(:(?P<port>[0-9]+))?$', host) if not m: raise ValueError('Unable to parse connection string: "%s"' % host) hostData = m.groupdict() if hostData.get('proto') == 'unix': self.family = socket.AF_UNIX self.address = hostData['path'] else: self.family = socket.AF_INET self.ip = hostData['host'] self.port = int(hostData.get('port', 11211)) self.address = ( self.ip, self.port ) self.deaduntil = 0 self.socket = None self.buffer = '' def debuglog(self, str): if self.debug: sys.stderr.write("MemCached: %s\n" % str) def _check_dead(self): if self.deaduntil and self.deaduntil > time.time(): return 1 self.deaduntil = 0 return 0 def connect(self): if self._get_socket(): return 1 return 0 def mark_dead(self, reason): self.debuglog("MemCache: %s: %s. Marking dead." % (self, reason)) self.deaduntil = time.time() + _Host._DEAD_RETRY self.close_socket() def _get_socket(self): if self._check_dead(): return None if self.socket: return self.socket s = socket.socket(self.family, socket.SOCK_STREAM) if hasattr(s, 'settimeout'): s.settimeout(self._SOCKET_TIMEOUT) try: s.connect(self.address) except socket.timeout, msg: self.mark_dead("connect: %s" % msg) return None except socket.error, msg: if isinstance(msg, tuple): msg = msg[1] self.mark_dead("connect: %s" % msg[1]) return None self.socket = s self.buffer = '' return s def close_socket(self): if self.socket: self.socket.close() self.socket = None def send_cmd(self, cmd): self.socket.sendall(cmd + '\r\n') def send_cmds(self, cmds): """ cmds already has trailing \r\n's applied """ self.socket.sendall(cmds) def readline(self): buf = self.buffer recv = self.socket.recv while True: index = buf.find('\r\n') if index >= 0: break data = recv(4096) if not data: self.mark_dead('Connection closed while reading from %s' % repr(self)) self.buffer = '' return '' buf += data self.buffer = buf[index+2:] return buf[:index] def expect(self, text): line = self.readline() if line != text: self.debuglog("while expecting '%s', got unexpected response '%s'" % (text, line)) return line def recv(self, rlen): self_socket_recv = self.socket.recv buf = self.buffer while len(buf) < rlen: foo = self_socket_recv(max(rlen - len(buf), 4096)) buf += foo if not foo: raise _Error( 'Read %d bytes, expecting %d, ' 'read returned 0 length bytes' % ( len(buf), rlen )) self.buffer = buf[rlen:] return buf[:rlen] def __str__(self): d = '' if self.deaduntil: d = " (dead until %d)" % self.deaduntil if self.family == socket.AF_INET: return "inet:%s:%d%s" % (self.address[0], self.address[1], d) else: return "unix:%s%s" % (self.address, d) def _doctest(): import doctest servers = ["127.0.0.1:11211"] mc = Client(servers, debug=1) globs = {"mc": mc} return doctest.testmod(globs=globs) if __name__ == "__main__": failures = 0 print "Testing docstrings..." _doctest() print "Running tests:" print serverList = [["127.0.0.1:11211"]] if '--do-unix' in sys.argv: serverList.append([os.path.join(os.getcwd(), 'memcached.socket')]) for servers in serverList: mc = Client(servers, debug=1) def to_s(val): if not isinstance(val, basestring): return "%s (%s)" % (val, type(val)) return "%s" % val def test_setget(key, val): print "Testing set/get {'%s': %s} ..." % (to_s(key), to_s(val)), mc.set(key, val) newval = mc.get(key) if newval == val: print "OK" return 1 else: print "FAIL"; failures = failures + 1 return 0 class FooStruct(object): def __init__(self): self.bar = "baz" def __str__(self): return "A FooStruct" def __eq__(self, other): if isinstance(other, FooStruct): return self.bar == other.bar return 0 test_setget("a_string", "some random string") test_setget("an_integer", 42) if test_setget("long", long(1<<30)): print "Testing delete ...", if mc.delete("long"): print "OK" else: print "FAIL"; failures = failures + 1 print "Checking results of delete ..." if mc.get("long") == None: print "OK" else: print "FAIL"; failures = failures + 1 print "Testing get_multi ...", print mc.get_multi(["a_string", "an_integer"]) print "Testing get(unknown value) ...", print to_s(mc.get("unknown_value")) f = FooStruct() test_setget("foostruct", f) print "Testing incr ...", x = mc.incr("an_integer", 1) if x == 43: print "OK" else: print "FAIL"; failures = failures + 1 print "Testing decr ...", x = mc.decr("an_integer", 1) if x == 42: print "OK" else: print "FAIL"; failures = failures + 1 sys.stdout.flush() # sanity tests print "Testing sending spaces...", sys.stdout.flush() try: x = mc.set("this has spaces", 1) except Client.MemcachedKeyCharacterError, msg: print "OK" else: print "FAIL"; failures = failures + 1 print "Testing sending control characters...", try: x = mc.set("this\x10has\x11control characters\x02", 1) except Client.MemcachedKeyCharacterError, msg: print "OK" else: print "FAIL"; failures = failures + 1 print "Testing using insanely long key...", try: x = mc.set('a'*SERVER_MAX_KEY_LENGTH + 'aaaa', 1) except Client.MemcachedKeyLengthError, msg: print "OK" else: print "FAIL"; failures = failures + 1 print "Testing sending a unicode-string key...", try: x = mc.set(u'keyhere', 1) except Client.MemcachedStringEncodingError, msg: print "OK", else: print "FAIL",; failures = failures + 1 try: x = mc.set((u'a'*SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1) except: print "FAIL",; failures = failures + 1 else: print "OK", import pickle s = pickle.loads('V\\u4f1a\np0\n.') try: x = mc.set((s*SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1) except Client.MemcachedKeyLengthError: print "OK" else: print "FAIL"; failures = failures + 1 print "Testing using a value larger than the memcached value limit...", x = mc.set('keyhere', 'a'*SERVER_MAX_VALUE_LENGTH) if mc.get('keyhere') == None: print "OK", else: print "FAIL",; failures = failures + 1 x = mc.set('keyhere', 'a'*SERVER_MAX_VALUE_LENGTH + 'aaa') if mc.get('keyhere') == None: print "OK" else: print "FAIL"; failures = failures + 1 print "Testing set_multi() with no memcacheds running", mc.disconnect_all() errors = mc.set_multi({'keyhere' : 'a', 'keythere' : 'b'}) if errors != []: print "FAIL"; failures = failures + 1 else: print "OK" print "Testing delete_multi() with no memcacheds running", mc.disconnect_all() ret = mc.delete_multi({'keyhere' : 'a', 'keythere' : 'b'}) if ret != 1: print "FAIL"; failures = failures + 1 else: print "OK" if failures > 0: print '*** THERE WERE FAILED TESTS' sys.exit(1) sys.exit(0) # vim: ts=4 sw=4 et :
bsd-3-clause
BT-ojossen/l10n-switzerland
l10n_ch_base_bank/tests/test_bank.py
2
5651
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2014 Camptocamp SA # # 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 <http://www.gnu.org/licenses/>. # ############################################################################## import openerp.tests.common as test_common from openerp.tools import mute_logger from openerp import exceptions class TestBank(test_common.TransactionCase): def test_ccp_at_bank(self): company = self.env.ref('base.main_company') self.assertTrue(company) partner = self.env.ref('base.main_partner') self.assertTrue(partner) self.bank = self.env['res.bank'].create( { 'name': 'BCV', 'ccp': '01-1234-1', 'bic': '23423456', 'clearing': '234234', } ) self.bank_account = self.env['res.partner.bank'].create( { 'partner_id': partner.id, 'owner_name': partner.name, 'street': partner.street, 'city': partner.city, 'zip': partner.zip, 'state': 'bvr', 'bank': self.bank.id, 'bank_name': self.bank.name, 'bank_bic': self.bank.bic, 'acc_number': 'R 12312123', 'bvr_adherent_num': '1234567', } ) def test_faulty_ccp_at_bank(self): company = self.env.ref('base.main_company') self.assertTrue(company) partner = self.env.ref('base.main_partner') self.assertTrue(partner) with self.assertRaises(exceptions.ValidationError): with mute_logger(): self.bank = self.env['res.bank'].create( { 'name': 'BCV', 'ccp': '2342342343423', 'bic': '23423456', 'clearing': '234234', } ) self.bank_account = self.env['res.partner.bank'].create( { 'partner_id': partner.id, 'owner_name': partner.name, 'street': partner.street, 'city': partner.city, 'zip': partner.zip, 'state': 'bvr', 'bank': self.bank.id, 'bank_name': self.bank.name, 'bank_bic': self.bank.bic, 'acc_number': 'R 12312123', 'bvr_adherent_num': '1234567', } ) def test_non_bvr_bank(self): company = self.env.ref('base.main_company') self.assertTrue(company) partner = self.env.ref('base.main_partner') self.assertTrue(partner) self.bank = self.env['res.bank'].create( { 'name': 'BCV', 'bic': '23423456', 'clearing': '234234', } ) self.bank_account = self.env['res.partner.bank'].create( { 'partner_id': partner.id, 'owner_name': partner.name, 'street': partner.street, 'city': partner.city, 'zip': partner.zip, 'state': 'bank', 'bank': self.bank.id, 'bank_name': self.bank.name, 'bank_bic': self.bank.bic, 'acc_number': 'R 12312123', 'bvr_adherent_num': '1234567', } ) # Commented du to issue odoo#3422 # def test_duplicate_ccp(self): # company = self.env.ref('base.main_company') # self.assertTrue(company) # partner = self.env.ref('base.main_partner') # self.assertTrue(partner) # self.bank = self.env['res.bank'].create( # { # 'name': 'BCV', # 'bic': '234234', # 'clearing': '234234', # 'ccp': '01-1234-1', # 'bvr_adherent_num': '1234567', # } # ) # with self.assertRaises(exceptions.ValidationError): # with mute_logger(): # self.bank_account = self.env['res.partner.bank'].create( # { # 'partner_id': partner.id, # 'owner_name': partner.name, # 'street': partner.street, # 'city': partner.city, # 'zip': partner.zip, # 'state': 'bvr', # 'bank': self.bank.id, # 'bank_name': self.bank.name, # 'bank_bic': self.bank.bic, # 'acc_number': '01-1234-1', # 'bvr_adherent_num': '1234567', # } # )
agpl-3.0
sbkro/alc
src/tests/unit/test_formatter.py
1
2802
# -*- coding:utf-8 -*- import calendar from mock import patch from datetime import datetime from alc.formatter import CalendarFormatter class TestDatetime: ''' Unit test for *CalendarFormatter.datetime()*. ''' def test_default(self): ''' :type: normal :case: *datetime_format* is None. :expect: convert datetime using default format (%Y/%m/%d). ''' cf = CalendarFormatter(datetime(2014, 7, 24, 23, 18, 00)) expect = '2014/07/24' actual = cf.datetime() assert expect == actual def test_datetime_format_is_specified(self): ''' :type: normal :case: *datetime_format* is specified. :expect: convert datetime using specified format. ''' cf = CalendarFormatter(datetime(2014, 7, 24, 23, 18, 00)) expect = '2014/07/24 23:18:00' actual = cf.datetime('%Y/%m/%d %H:%M:%S') assert expect == actual class TestWeekheader: ''' Unit test for *CalendarFormatter.weekheader()*. ''' def test_default(self): ''' :type: normal :case: call this method. :expect: get a week header. ''' expect = 'Mo\tTu\tWe\tTh\tFr\tSa\tSu' actual = CalendarFormatter.weekheader() assert expect == actual def test_first_weekday_is_specified(self): ''' :type: normal :case: set the first week day in advance. (Sunday) :expect: get a week header of start Sunday. ''' calendar.setfirstweekday(calendar.SUNDAY) expect = 'Su\tMo\tTu\tWe\tTh\tFr\tSa' actual = CalendarFormatter.weekheader() assert expect == actual class TestWeekdays: ''' Unit test for *CalendarFormatter.weekdays()*. ''' def test_default(self): ''' :type: normal :case: call this method. datetime is '2014/07'. :expect: get a calendar for '2014/07'. ''' cf = CalendarFormatter(datetime(2014, 7, 24, 23, 18, 00)) expect = [ '\t01\t02\t03\t04\t05\t06\t', '07\t08\t09\t10\t11\t12\t13\t', '14\t15\t16\t17\t18\t19\t20\t', '21\t22\t23\t24\t25\t26\t27\t', '28\t29\t30\t31\t\t\t\t' ] for i, w in enumerate(cf.weekdays()): assert expect[i] == w class TestSetfirstweekday: ''' Unit test for *CalendarFormatter.setfirstweekday()*. ''' @patch('calendar.setfirstweekday') def test_default(self, m_setfirstweekday): ''' :type: normal :case: call this method. :expect: call *calendar.setfirstweekday*. ''' CalendarFormatter.setfirstweekday(calendar.MONDAY) m_setfirstweekday.assert_called_once_with(calendar.MONDAY)
bsd-3-clause
mF2C/COMPSs
tests/sources/python/1_decorator_mpi/src/modules/testMpiDecorator.py
1
4569
#!/usr/bin/python # -*- coding: utf-8 -*- """ PyCOMPSs Testbench Tasks ======================== """ # Imports import unittest import os from pycompss.api.task import task from pycompss.api.parameter import * from pycompss.api.api import compss_barrier, compss_open, compss_wait_on from pycompss.api.mpi import mpi from pycompss.api.constraint import constraint @mpi(binary="date", working_dir="/tmp", runner="mpirun") @task() def myDate(dprefix, param): pass @constraint(computing_units="2") @mpi(binary="date", working_dir="/tmp", runner="mpirun", computing_nodes=2) @task() def myDateConstrained(dprefix, param): pass @constraint(computing_units="$CUS") @mpi(binary="date", working_dir="/tmp", runner="mpirun", computing_nodes="$CUS") @task() def myDateConstrainedWithEnvVar(dprefix, param): pass @mpi(binary="sed", working_dir=".", runner="mpirun", computing_nodes="4") @task(file=FILE_IN) def mySedIN(expression, file): pass @mpi(binary="date", working_dir=".", runner="mpirun", computing_nodes=1) @task(returns=int) def myReturn(): pass @mpi(binary="./private.sh", working_dir=os.getcwd() + '/src/scripts/', runner="mpirun", computing_nodes=1) @task(returns=int) def failedBinary(code): pass @mpi(binary="sed", working_dir=".", runner="mpirun") @task(file=FILE_INOUT) def mySedINOUT(flag, expression, file): pass @mpi(binary="grep", working_dir=".", runner="mpirun") # @task(infile=Parameter(TYPE.FILE, DIRECTION.IN, STREAM.STDIN), result=Parameter(TYPE.FILE, DIRECTION.OUT, STREAM.STDOUT)) # @task(infile={Type:FILE_IN, Stream:STDIN}, result={Type:FILE_OUT, Stream:STDOUT}) @task(infile={Type: FILE_IN_STDIN}, result={Type: FILE_OUT_STDOUT}) def myGrepper(keyword, infile, result): pass @mpi(binary="ls", runner="mpirun", computing_nodes=2) @task(hide={Type: FILE_IN, Prefix: "--hide="}, sort={Type: IN, Prefix: "--sort="}) def myLs(flag, hide, sort): pass @mpi(binary="ls", runner="mpirun", computing_nodes=2) @task(hide={Type: FILE_IN, Prefix: "--hide="}, sort={Prefix: "--sort="}) def myLsWithoutType(flag, hide, sort): pass @mpi(binary="./checkNames.sh", working_dir=os.getcwd() + '/src/scripts/', runner="mpirun", computing_nodes=1) @task(f=FILE_IN, fp={Type: FILE_IN, Prefix: "--prefix="}, fout={Type: FILE_OUT}, returns=int) def checkFileNames(f, fp, name, fout): pass class testMpiDecorator(unittest.TestCase): def testFunctionalUsage(self): myDate("-d", "next friday") compss_barrier() def testFunctionalUsageWithConstraint(self): myDateConstrained("-d", "next monday") compss_barrier() def testFunctionalUsageWithEnvVarConstraint(self): myDateConstrainedWithEnvVar("-d", "next tuesday") compss_barrier() def testFileManagementIN(self): infile = "src/infile" mySedIN('s/Hi/HELLO/g', infile) compss_barrier() def testReturn(self): ev = myReturn() ev = compss_wait_on(ev) self.assertEqual(ev, 0) def testFailedBinaryExitValue(self): ev = failedBinary(123) ev = compss_wait_on(ev) self.assertEqual(ev, 123) @unittest.skip("UNSUPPORTED WITH GAT") def testFileManagementINOUT(self): inoutfile = "src/inoutfile" mySedINOUT('-i', 's/Hi/HELLO/g', inoutfile) with compss_open(inoutfile, "r") as finout_r: content_r = finout_r.read() # Check if there are no Hi words, and instead there is HELLO if 'Hi' in content_r: self.fail("INOUT File failed.") def testFileManagement(self): infile = "src/infile" outfile = "src/grepoutfile" myGrepper("Hi", infile, outfile) compss_barrier() def testFilesAndPrefix(self): flag = '-l' infile = "src/infile" sort = "size" myLs(flag, infile, sort) compss_barrier() def testFilesAndPrefixWithoutType(self): flag = '-l' infile = "src/inoutfile" sort = "time" myLsWithoutType(flag, infile, sort) compss_barrier() def testCheckFileNames(self): f = "src/infile" fp = "src/infile" name = "infile" fout = "checkFileNamesResult.txt" exit_value = checkFileNames(f, fp, name, fout) exit_value = compss_wait_on(exit_value) with compss_open(fout) as result: data = result.read() print("CheckFileNamesResult: " + str(data)) self.assertEqual(exit_value, 0, "At least one file name is NOT as expected: {}, {}, {}".format(f, fp, name))
apache-2.0
s34rching/python_classes
tests/test_contact_data.py
1
2053
import re import random def test_contact_data_from_home_page(app): r_index = random.randrange(len(app.contact.get_contact_list())) data_from_home_page = app.contact.get_contact_list()[r_index] data_from_edit_page = app.contact.get_contact_info_from_edit_page(r_index) assert data_from_home_page.firstname == data_from_edit_page.firstname assert data_from_home_page.lastname == data_from_edit_page.lastname assert data_from_home_page.address == data_from_edit_page.address assert data_from_home_page.all_phones_from_homepage == merge_phones_like_on_homepage(data_from_edit_page) assert data_from_home_page.all_emails_from_homepage == merge_emails_like_on_homepage(data_from_edit_page) assert data_from_home_page.id == data_from_edit_page.id def test_phones_from_view_page(app): r_index = random.randrange(len(app.contact.get_contact_list())) data_from_view_page = app.contact.get_contact_info_from_view_page(r_index) data_from_edit_page = app.contact.get_contact_info_from_edit_page(r_index) assert data_from_view_page.home_number == data_from_edit_page.home_number assert data_from_view_page.mobile_number == data_from_edit_page.mobile_number assert data_from_view_page.work_number == data_from_edit_page.work_number assert data_from_view_page.secondary_number == data_from_edit_page.secondary_number def clear(s): return re.sub('[() -]', '', s) def merge_phones_like_on_homepage(contact): return '\n'.join(filter(lambda x: x!= '', map(lambda x: clear(x), filter(lambda x: x is not None, [contact.home_number, contact.work_number, contact.mobile_number, contact.secondary_number])))) def merge_emails_like_on_homepage(contact): return '\n'.join(filter(lambda x: x!= '', map(lambda x: clear(x), filter(lambda x: x is not None, [contact.email, contact.email2, contact.email3]))))
apache-2.0
AdmiralNemo/ansible-modules-extras
monitoring/logentries.py
22
4548
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Ivan Vanderbyl <ivan@app.io> # # This module 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 software 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 software. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: logentries author: Ivan Vanderbyl short_description: Module for tracking logs via logentries.com description: - Sends logs to LogEntries in realtime version_added: "1.6" options: path: description: - path to a log file required: true state: description: - following state of the log choices: [ 'present', 'absent' ] required: false default: present name: description: - name of the log required: false logtype: description: - type of the log required: false notes: - Requires the LogEntries agent which can be installed following the instructions at logentries.com ''' EXAMPLES = ''' - logentries: path=/var/log/nginx/access.log state=present name=nginx-access-log - logentries: path=/var/log/nginx/error.log state=absent ''' def query_log_status(module, le_path, path, state="present"): """ Returns whether a log is followed or not. """ if state == "present": rc, out, err = module.run_command("%s followed %s" % (le_path, path)) if rc == 0: return True return False def follow_log(module, le_path, logs, name=None, logtype=None): """ Follows one or more logs if not already followed. """ followed_count = 0 for log in logs: if query_log_status(module, le_path, log): continue if module.check_mode: module.exit_json(changed=True) cmd = [le_path, 'follow', log] if name: cmd.extend(['--name',name]) if logtype: cmd.extend(['--type',logtype]) rc, out, err = module.run_command(' '.join(cmd)) if not query_log_status(module, le_path, log): module.fail_json(msg="failed to follow '%s': %s" % (log, err.strip())) followed_count += 1 if followed_count > 0: module.exit_json(changed=True, msg="followed %d log(s)" % (followed_count,)) module.exit_json(changed=False, msg="logs(s) already followed") def unfollow_log(module, le_path, logs): """ Unfollows one or more logs if followed. """ removed_count = 0 # Using a for loop incase of error, we can report the package that failed for log in logs: # Query the log first, to see if we even need to remove. if not query_log_status(module, le_path, log): continue if module.check_mode: module.exit_json(changed=True) rc, out, err = module.run_command([le_path, 'rm', log]) if query_log_status(module, le_path, log): module.fail_json(msg="failed to remove '%s': %s" % (log, err.strip())) removed_count += 1 if removed_count > 0: module.exit_json(changed=True, msg="removed %d package(s)" % removed_count) module.exit_json(changed=False, msg="logs(s) already unfollowed") def main(): module = AnsibleModule( argument_spec = dict( path = dict(required=True), state = dict(default="present", choices=["present", "followed", "absent", "unfollowed"]), name = dict(required=False, default=None, type='str'), logtype = dict(required=False, default=None, type='str', aliases=['type']) ), supports_check_mode=True ) le_path = module.get_bin_path('le', True, ['/usr/local/bin']) p = module.params # Handle multiple log files logs = p["path"].split(",") logs = filter(None, logs) if p["state"] in ["present", "followed"]: follow_log(module, le_path, logs, name=p['name'], logtype=p['logtype']) elif p["state"] in ["absent", "unfollowed"]: unfollow_log(module, le_path, logs) # import module snippets from ansible.module_utils.basic import * main()
gpl-3.0
ywcui1990/nupic
examples/opf/clients/hotgym/prediction/one_gym/nupic_output.py
17
6193
# ---------------------------------------------------------------------- # 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 Affero 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ Provides two classes with the same signature for writing data out of NuPIC models. (This is a component of the One Hot Gym Prediction Tutorial.) """ import csv from collections import deque from abc import ABCMeta, abstractmethod # Try to import matplotlib, but we don't have to. try: import matplotlib matplotlib.use('TKAgg') import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.dates import date2num except ImportError: pass WINDOW = 100 class NuPICOutput(object): __metaclass__ = ABCMeta def __init__(self, names, showAnomalyScore=False): self.names = names self.showAnomalyScore = showAnomalyScore @abstractmethod def write(self, timestamps, actualValues, predictedValues, predictionStep=1): pass @abstractmethod def close(self): pass class NuPICFileOutput(NuPICOutput): def __init__(self, *args, **kwargs): super(NuPICFileOutput, self).__init__(*args, **kwargs) self.outputFiles = [] self.outputWriters = [] self.lineCounts = [] headerRow = ['timestamp', 'kw_energy_consumption', 'prediction'] for name in self.names: self.lineCounts.append(0) outputFileName = "%s_out.csv" % name print "Preparing to output %s data to %s" % (name, outputFileName) outputFile = open(outputFileName, "w") self.outputFiles.append(outputFile) outputWriter = csv.writer(outputFile) self.outputWriters.append(outputWriter) outputWriter.writerow(headerRow) def write(self, timestamps, actualValues, predictedValues, predictionStep=1): assert len(timestamps) == len(actualValues) == len(predictedValues) for index in range(len(self.names)): timestamp = timestamps[index] actual = actualValues[index] prediction = predictedValues[index] writer = self.outputWriters[index] if timestamp is not None: outputRow = [timestamp, actual, prediction] writer.writerow(outputRow) self.lineCounts[index] += 1 def close(self): for index, name in enumerate(self.names): self.outputFiles[index].close() print "Done. Wrote %i data lines to %s." % (self.lineCounts[index], name) class NuPICPlotOutput(NuPICOutput): def __init__(self, *args, **kwargs): super(NuPICPlotOutput, self).__init__(*args, **kwargs) # Turn matplotlib interactive mode on. plt.ion() self.dates = [] self.convertedDates = [] self.actualValues = [] self.predictedValues = [] self.actualLines = [] self.predictedLines = [] self.linesInitialized = False self.graphs = [] plotCount = len(self.names) plotHeight = max(plotCount * 3, 6) fig = plt.figure(figsize=(14, plotHeight)) gs = gridspec.GridSpec(plotCount, 1) for index in range(len(self.names)): self.graphs.append(fig.add_subplot(gs[index, 0])) plt.title(self.names[index]) plt.ylabel('KW Energy Consumption') plt.xlabel('Date') plt.tight_layout() def initializeLines(self, timestamps): for index in range(len(self.names)): print "initializing %s" % self.names[index] # graph = self.graphs[index] self.dates.append(deque([timestamps[index]] * WINDOW, maxlen=WINDOW)) self.convertedDates.append(deque( [date2num(date) for date in self.dates[index]], maxlen=WINDOW )) self.actualValues.append(deque([0.0] * WINDOW, maxlen=WINDOW)) self.predictedValues.append(deque([0.0] * WINDOW, maxlen=WINDOW)) actualPlot, = self.graphs[index].plot( self.dates[index], self.actualValues[index] ) self.actualLines.append(actualPlot) predictedPlot, = self.graphs[index].plot( self.dates[index], self.predictedValues[index] ) self.predictedLines.append(predictedPlot) self.linesInitialized = True def write(self, timestamps, actualValues, predictedValues, predictionStep=1): assert len(timestamps) == len(actualValues) == len(predictedValues) # We need the first timestamp to initialize the lines at the right X value, # so do that check first. if not self.linesInitialized: self.initializeLines(timestamps) for index in range(len(self.names)): self.dates[index].append(timestamps[index]) self.convertedDates[index].append(date2num(timestamps[index])) self.actualValues[index].append(actualValues[index]) self.predictedValues[index].append(predictedValues[index]) # Update data self.actualLines[index].set_xdata(self.convertedDates[index]) self.actualLines[index].set_ydata(self.actualValues[index]) self.predictedLines[index].set_xdata(self.convertedDates[index]) self.predictedLines[index].set_ydata(self.predictedValues[index]) self.graphs[index].relim() self.graphs[index].autoscale_view(True, True, True) plt.draw() plt.legend(('actual','predicted'), loc=3) def refreshGUI(self): """Give plot a pause, so data is drawn and GUI's event loop can run. """ plt.pause(0.0001) def close(self): plt.ioff() plt.show() NuPICOutput.register(NuPICFileOutput) NuPICOutput.register(NuPICPlotOutput)
agpl-3.0
deeplook/bokeh
bokeh/charts/builder/timeseries_builder.py
26
6252
"""This is the Bokeh charts interface. It gives you a high level API to build complex plot is a simple way. This is the TimeSeries class which lets you build your TimeSeries charts just passing the arguments to the Chart class and calling the proper functions. """ #----------------------------------------------------------------------------- # Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import absolute_import from six import string_types try: import pandas as pd except ImportError: pd = None from ..utils import chunk, cycle_colors from .._builder import Builder, create_and_build from ...models import ColumnDataSource, DataRange1d, GlyphRenderer, Range1d from ...models.glyphs import Line from ...properties import Any #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- def TimeSeries(values, index=None, xscale='datetime', **kws): """ Create a timeseries chart using :class:`TimeSeriesBuilder <bokeh.charts.builder.timeseries_builder.TimeSeriesBuilder>` to render the lines from values and index. Args: values (iterable): a 2d iterable containing the values. Can be anything that can be converted to a 2d array, and which is the x (time) axis is determined by ``index``, while the others are interpreted as y values. index (str|1d iterable, optional): can be used to specify a common custom index for all data series as an **1d iterable** of any sort that will be used as series common index or a **string** that corresponds to the key of the mapping to be used as index (and not as data series) if area.values is a mapping (like a dict, an OrderedDict or a pandas DataFrame) In addition the the parameters specific to this chart, :ref:`userguide_charts_generic_arguments` are also accepted as keyword parameters. Returns: a new :class:`Chart <bokeh.charts.Chart>` Examples: .. bokeh-plot:: :source-position: above from collections import OrderedDict import datetime from bokeh.charts import TimeSeries, output_file, show # (dict, OrderedDict, lists, arrays and DataFrames are valid inputs) now = datetime.datetime.now() delta = datetime.timedelta(minutes=1) dts = [now + delta*i for i in range(5)] xyvalues = OrderedDict({'Date': dts}) y_python = xyvalues['python'] = [2, 3, 7, 5, 26] y_pypy = xyvalues['pypy'] = [12, 33, 47, 15, 126] y_jython = xyvalues['jython'] = [22, 43, 10, 25, 26] ts = TimeSeries(xyvalues, index='Date', title="TimeSeries", legend="top_left", ylabel='Languages') output_file('timeseries.html') show(ts) """ return create_and_build( TimeSeriesBuilder, values, index=index, xscale=xscale, **kws ) class TimeSeriesBuilder(Builder): """This is the TimeSeries class and it is in charge of plotting TimeSeries charts in an easy and intuitive way. Essentially, we provide a way to ingest the data, make the proper calculations and push the references into a source object. We additionally make calculations for the ranges. And finally add the needed lines taking the references from the source. """ index = Any(help=""" An index to be used for all data series as follows: - A 1d iterable of any sort that will be used as series common index - As a string that corresponds to the key of the mapping to be used as index (and not as data series) if area.values is a mapping (like a dict, an OrderedDict or a pandas DataFrame) """) def _process_data(self): """Take the x/y data from the timeseries values. It calculates the chart properties accordingly. Then build a dict containing references to all the points to be used by the line glyph inside the ``_yield_renderers`` method. """ self._data = dict() # list to save all the attributes we are going to create self._attr = [] # necessary to make all formats and encoder happy with array, blaze, ... xs = list([x for x in self._values_index]) for col, values in self._values.items(): if isinstance(self.index, string_types) \ and col == self.index: continue # save every the groups available in the incomming input self._groups.append(col) self.set_and_get("x_", col, xs) self.set_and_get("y_", col, values) def _set_sources(self): """Push the TimeSeries data into the ColumnDataSource and calculate the proper ranges. """ self._source = ColumnDataSource(self._data) self.x_range = DataRange1d() y_names = self._attr[1::2] endy = max(max(self._data[i]) for i in y_names) starty = min(min(self._data[i]) for i in y_names) self.y_range = Range1d( start=starty - 0.1 * (endy - starty), end=endy + 0.1 * (endy - starty) ) def _yield_renderers(self): """Use the line glyphs to connect the xy points in the time series. Takes reference points from the data loaded at the ColumnDataSource. """ self._duplet = list(chunk(self._attr, 2)) colors = cycle_colors(self._duplet, self.palette) for i, (x, y) in enumerate(self._duplet, start=1): glyph = Line(x=x, y=y, line_color=colors[i - 1]) renderer = GlyphRenderer(data_source=self._source, glyph=glyph) self._legends.append((self._groups[i-1], [renderer])) yield renderer
bsd-3-clause
IITBinterns13/edx-platform-dev
common/djangoapps/student/management/commands/pearson_import_conf_zip.py
10
5989
import csv from zipfile import ZipFile, is_zipfile from time import strptime, strftime from datetime import datetime from dogapi import dog_http_api from django.core.management.base import BaseCommand, CommandError from django.conf import settings from student.models import TestCenterUser, TestCenterRegistration from pytz import UTC class Command(BaseCommand): dog_http_api.api_key = settings.DATADOG_API args = '<input zip file>' help = """ Import Pearson confirmation files and update TestCenterUser and TestCenterRegistration tables with status. """ @staticmethod def datadog_error(string, tags): dog_http_api.event("Pearson Import", string, alert_type='error', tags=[tags]) def handle(self, *args, **kwargs): if len(args) < 1: print Command.help return source_zip = args[0] if not is_zipfile(source_zip): error = "Input file is not a zipfile: \"{}\"".format(source_zip) Command.datadog_error(error, source_zip) raise CommandError(error) # loop through all files in zip, and process them based on filename prefix: with ZipFile(source_zip, 'r') as zipfile: for fileinfo in zipfile.infolist(): with zipfile.open(fileinfo) as zipentry: if fileinfo.filename.startswith("eac-"): self.process_eac(zipentry) elif fileinfo.filename.startswith("vcdc-"): self.process_vcdc(zipentry) else: error = "Unrecognized confirmation file type\"{}\" in confirmation zip file \"{}\"".format(fileinfo.filename, zipfile) Command.datadog_error(error, source_zip) raise CommandError(error) def process_eac(self, eacfile): print "processing eac" reader = csv.DictReader(eacfile, delimiter="\t") for row in reader: client_authorization_id = row['ClientAuthorizationID'] if not client_authorization_id: if row['Status'] == 'Error': Command.datadog_error("Error in EAD file processing ({}): {}".format(row['Date'], row['Message']), eacfile.name) else: Command.datadog_error("Encountered bad record: {}".format(row), eacfile.name) else: try: registration = TestCenterRegistration.objects.get(client_authorization_id=client_authorization_id) Command.datadog_error("Found authorization record for user {}".format(registration.testcenter_user.user.username), eacfile.name) # now update the record: registration.upload_status = row['Status'] registration.upload_error_message = row['Message'] try: registration.processed_at = strftime('%Y-%m-%d %H:%M:%S', strptime(row['Date'], '%Y/%m/%d %H:%M:%S')) except ValueError as ve: Command.datadog_error("Bad Date value found for {}: message {}".format(client_authorization_id, ve), eacfile.name) # store the authorization Id if one is provided. (For debugging) if row['AuthorizationID']: try: registration.authorization_id = int(row['AuthorizationID']) except ValueError as ve: Command.datadog_error("Bad AuthorizationID value found for {}: message {}".format(client_authorization_id, ve), eacfile.name) registration.confirmed_at = datetime.now(UTC) registration.save() except TestCenterRegistration.DoesNotExist: Command.datadog_error("Failed to find record for client_auth_id {}".format(client_authorization_id), eacfile.name) def process_vcdc(self, vcdcfile): print "processing vcdc" reader = csv.DictReader(vcdcfile, delimiter="\t") for row in reader: client_candidate_id = row['ClientCandidateID'] if not client_candidate_id: if row['Status'] == 'Error': Command.datadog_error("Error in CDD file processing ({}): {}".format(row['Date'], row['Message']), vcdcfile.name) else: Command.datadog_error("Encountered bad record: {}".format(row), vcdcfile.name) else: try: tcuser = TestCenterUser.objects.get(client_candidate_id=client_candidate_id) Command.datadog_error("Found demographics record for user {}".format(tcuser.user.username), vcdcfile.name) # now update the record: tcuser.upload_status = row['Status'] tcuser.upload_error_message = row['Message'] try: tcuser.processed_at = strftime('%Y-%m-%d %H:%M:%S', strptime(row['Date'], '%Y/%m/%d %H:%M:%S')) except ValueError as ve: Command.datadog_error("Bad Date value found for {}: message {}".format(client_candidate_id, ve), vcdcfile.name) # store the candidate Id if one is provided. (For debugging) if row['CandidateID']: try: tcuser.candidate_id = int(row['CandidateID']) except ValueError as ve: Command.datadog_error("Bad CandidateID value found for {}: message {}".format(client_candidate_id, ve), vcdcfile.name) tcuser.confirmed_at = datetime.utcnow() tcuser.save() except TestCenterUser.DoesNotExist: Command.datadog_error(" Failed to find record for client_candidate_id {}".format(client_candidate_id), vcdcfile.name)
agpl-3.0
msebire/intellij-community
python/lib/Lib/encodings/koi8_r.py
593
14035
""" Python Character Mapping Codec koi8_r generated from 'MAPPINGS/VENDORS/MISC/KOI8-R.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='koi8-r', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> NULL u'\x01' # 0x01 -> START OF HEADING u'\x02' # 0x02 -> START OF TEXT u'\x03' # 0x03 -> END OF TEXT u'\x04' # 0x04 -> END OF TRANSMISSION u'\x05' # 0x05 -> ENQUIRY u'\x06' # 0x06 -> ACKNOWLEDGE u'\x07' # 0x07 -> BELL u'\x08' # 0x08 -> BACKSPACE u'\t' # 0x09 -> HORIZONTAL TABULATION u'\n' # 0x0A -> LINE FEED u'\x0b' # 0x0B -> VERTICAL TABULATION u'\x0c' # 0x0C -> FORM FEED u'\r' # 0x0D -> CARRIAGE RETURN u'\x0e' # 0x0E -> SHIFT OUT u'\x0f' # 0x0F -> SHIFT IN u'\x10' # 0x10 -> DATA LINK ESCAPE u'\x11' # 0x11 -> DEVICE CONTROL ONE u'\x12' # 0x12 -> DEVICE CONTROL TWO u'\x13' # 0x13 -> DEVICE CONTROL THREE u'\x14' # 0x14 -> DEVICE CONTROL FOUR u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x16 -> SYNCHRONOUS IDLE u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK u'\x18' # 0x18 -> CANCEL u'\x19' # 0x19 -> END OF MEDIUM u'\x1a' # 0x1A -> SUBSTITUTE u'\x1b' # 0x1B -> ESCAPE u'\x1c' # 0x1C -> FILE SEPARATOR u'\x1d' # 0x1D -> GROUP SEPARATOR u'\x1e' # 0x1E -> RECORD SEPARATOR u'\x1f' # 0x1F -> UNIT SEPARATOR u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> DELETE u'\u2500' # 0x80 -> BOX DRAWINGS LIGHT HORIZONTAL u'\u2502' # 0x81 -> BOX DRAWINGS LIGHT VERTICAL u'\u250c' # 0x82 -> BOX DRAWINGS LIGHT DOWN AND RIGHT u'\u2510' # 0x83 -> BOX DRAWINGS LIGHT DOWN AND LEFT u'\u2514' # 0x84 -> BOX DRAWINGS LIGHT UP AND RIGHT u'\u2518' # 0x85 -> BOX DRAWINGS LIGHT UP AND LEFT u'\u251c' # 0x86 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT u'\u2524' # 0x87 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT u'\u252c' # 0x88 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL u'\u2534' # 0x89 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL u'\u253c' # 0x8A -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL u'\u2580' # 0x8B -> UPPER HALF BLOCK u'\u2584' # 0x8C -> LOWER HALF BLOCK u'\u2588' # 0x8D -> FULL BLOCK u'\u258c' # 0x8E -> LEFT HALF BLOCK u'\u2590' # 0x8F -> RIGHT HALF BLOCK u'\u2591' # 0x90 -> LIGHT SHADE u'\u2592' # 0x91 -> MEDIUM SHADE u'\u2593' # 0x92 -> DARK SHADE u'\u2320' # 0x93 -> TOP HALF INTEGRAL u'\u25a0' # 0x94 -> BLACK SQUARE u'\u2219' # 0x95 -> BULLET OPERATOR u'\u221a' # 0x96 -> SQUARE ROOT u'\u2248' # 0x97 -> ALMOST EQUAL TO u'\u2264' # 0x98 -> LESS-THAN OR EQUAL TO u'\u2265' # 0x99 -> GREATER-THAN OR EQUAL TO u'\xa0' # 0x9A -> NO-BREAK SPACE u'\u2321' # 0x9B -> BOTTOM HALF INTEGRAL u'\xb0' # 0x9C -> DEGREE SIGN u'\xb2' # 0x9D -> SUPERSCRIPT TWO u'\xb7' # 0x9E -> MIDDLE DOT u'\xf7' # 0x9F -> DIVISION SIGN u'\u2550' # 0xA0 -> BOX DRAWINGS DOUBLE HORIZONTAL u'\u2551' # 0xA1 -> BOX DRAWINGS DOUBLE VERTICAL u'\u2552' # 0xA2 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE u'\u0451' # 0xA3 -> CYRILLIC SMALL LETTER IO u'\u2553' # 0xA4 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE u'\u2554' # 0xA5 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT u'\u2555' # 0xA6 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE u'\u2556' # 0xA7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE u'\u2557' # 0xA8 -> BOX DRAWINGS DOUBLE DOWN AND LEFT u'\u2558' # 0xA9 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE u'\u2559' # 0xAA -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE u'\u255a' # 0xAB -> BOX DRAWINGS DOUBLE UP AND RIGHT u'\u255b' # 0xAC -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE u'\u255c' # 0xAD -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE u'\u255d' # 0xAE -> BOX DRAWINGS DOUBLE UP AND LEFT u'\u255e' # 0xAF -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE u'\u255f' # 0xB0 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE u'\u2560' # 0xB1 -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT u'\u2561' # 0xB2 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE u'\u0401' # 0xB3 -> CYRILLIC CAPITAL LETTER IO u'\u2562' # 0xB4 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE u'\u2563' # 0xB5 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT u'\u2564' # 0xB6 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE u'\u2565' # 0xB7 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE u'\u2566' # 0xB8 -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL u'\u2567' # 0xB9 -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE u'\u2568' # 0xBA -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE u'\u2569' # 0xBB -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL u'\u256a' # 0xBC -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE u'\u256b' # 0xBD -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE u'\u256c' # 0xBE -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL u'\xa9' # 0xBF -> COPYRIGHT SIGN u'\u044e' # 0xC0 -> CYRILLIC SMALL LETTER YU u'\u0430' # 0xC1 -> CYRILLIC SMALL LETTER A u'\u0431' # 0xC2 -> CYRILLIC SMALL LETTER BE u'\u0446' # 0xC3 -> CYRILLIC SMALL LETTER TSE u'\u0434' # 0xC4 -> CYRILLIC SMALL LETTER DE u'\u0435' # 0xC5 -> CYRILLIC SMALL LETTER IE u'\u0444' # 0xC6 -> CYRILLIC SMALL LETTER EF u'\u0433' # 0xC7 -> CYRILLIC SMALL LETTER GHE u'\u0445' # 0xC8 -> CYRILLIC SMALL LETTER HA u'\u0438' # 0xC9 -> CYRILLIC SMALL LETTER I u'\u0439' # 0xCA -> CYRILLIC SMALL LETTER SHORT I u'\u043a' # 0xCB -> CYRILLIC SMALL LETTER KA u'\u043b' # 0xCC -> CYRILLIC SMALL LETTER EL u'\u043c' # 0xCD -> CYRILLIC SMALL LETTER EM u'\u043d' # 0xCE -> CYRILLIC SMALL LETTER EN u'\u043e' # 0xCF -> CYRILLIC SMALL LETTER O u'\u043f' # 0xD0 -> CYRILLIC SMALL LETTER PE u'\u044f' # 0xD1 -> CYRILLIC SMALL LETTER YA u'\u0440' # 0xD2 -> CYRILLIC SMALL LETTER ER u'\u0441' # 0xD3 -> CYRILLIC SMALL LETTER ES u'\u0442' # 0xD4 -> CYRILLIC SMALL LETTER TE u'\u0443' # 0xD5 -> CYRILLIC SMALL LETTER U u'\u0436' # 0xD6 -> CYRILLIC SMALL LETTER ZHE u'\u0432' # 0xD7 -> CYRILLIC SMALL LETTER VE u'\u044c' # 0xD8 -> CYRILLIC SMALL LETTER SOFT SIGN u'\u044b' # 0xD9 -> CYRILLIC SMALL LETTER YERU u'\u0437' # 0xDA -> CYRILLIC SMALL LETTER ZE u'\u0448' # 0xDB -> CYRILLIC SMALL LETTER SHA u'\u044d' # 0xDC -> CYRILLIC SMALL LETTER E u'\u0449' # 0xDD -> CYRILLIC SMALL LETTER SHCHA u'\u0447' # 0xDE -> CYRILLIC SMALL LETTER CHE u'\u044a' # 0xDF -> CYRILLIC SMALL LETTER HARD SIGN u'\u042e' # 0xE0 -> CYRILLIC CAPITAL LETTER YU u'\u0410' # 0xE1 -> CYRILLIC CAPITAL LETTER A u'\u0411' # 0xE2 -> CYRILLIC CAPITAL LETTER BE u'\u0426' # 0xE3 -> CYRILLIC CAPITAL LETTER TSE u'\u0414' # 0xE4 -> CYRILLIC CAPITAL LETTER DE u'\u0415' # 0xE5 -> CYRILLIC CAPITAL LETTER IE u'\u0424' # 0xE6 -> CYRILLIC CAPITAL LETTER EF u'\u0413' # 0xE7 -> CYRILLIC CAPITAL LETTER GHE u'\u0425' # 0xE8 -> CYRILLIC CAPITAL LETTER HA u'\u0418' # 0xE9 -> CYRILLIC CAPITAL LETTER I u'\u0419' # 0xEA -> CYRILLIC CAPITAL LETTER SHORT I u'\u041a' # 0xEB -> CYRILLIC CAPITAL LETTER KA u'\u041b' # 0xEC -> CYRILLIC CAPITAL LETTER EL u'\u041c' # 0xED -> CYRILLIC CAPITAL LETTER EM u'\u041d' # 0xEE -> CYRILLIC CAPITAL LETTER EN u'\u041e' # 0xEF -> CYRILLIC CAPITAL LETTER O u'\u041f' # 0xF0 -> CYRILLIC CAPITAL LETTER PE u'\u042f' # 0xF1 -> CYRILLIC CAPITAL LETTER YA u'\u0420' # 0xF2 -> CYRILLIC CAPITAL LETTER ER u'\u0421' # 0xF3 -> CYRILLIC CAPITAL LETTER ES u'\u0422' # 0xF4 -> CYRILLIC CAPITAL LETTER TE u'\u0423' # 0xF5 -> CYRILLIC CAPITAL LETTER U u'\u0416' # 0xF6 -> CYRILLIC CAPITAL LETTER ZHE u'\u0412' # 0xF7 -> CYRILLIC CAPITAL LETTER VE u'\u042c' # 0xF8 -> CYRILLIC CAPITAL LETTER SOFT SIGN u'\u042b' # 0xF9 -> CYRILLIC CAPITAL LETTER YERU u'\u0417' # 0xFA -> CYRILLIC CAPITAL LETTER ZE u'\u0428' # 0xFB -> CYRILLIC CAPITAL LETTER SHA u'\u042d' # 0xFC -> CYRILLIC CAPITAL LETTER E u'\u0429' # 0xFD -> CYRILLIC CAPITAL LETTER SHCHA u'\u0427' # 0xFE -> CYRILLIC CAPITAL LETTER CHE u'\u042a' # 0xFF -> CYRILLIC CAPITAL LETTER HARD SIGN ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
apache-2.0
Zkin/pf-kernel-updates
scripts/gdb/linux/cpus.py
997
3560
# # gdb helper commands and functions for Linux kernel debugging # # per-cpu tools # # Copyright (c) Siemens AG, 2011-2013 # # Authors: # Jan Kiszka <jan.kiszka@siemens.com> # # This work is licensed under the terms of the GNU GPL version 2. # import gdb from linux import tasks, utils MAX_CPUS = 4096 def get_current_cpu(): if utils.get_gdbserver_type() == utils.GDBSERVER_QEMU: return gdb.selected_thread().num - 1 elif utils.get_gdbserver_type() == utils.GDBSERVER_KGDB: tid = gdb.selected_thread().ptid[2] if tid > (0x100000000 - MAX_CPUS - 2): return 0x100000000 - tid - 2 else: return tasks.get_thread_info(tasks.get_task_by_pid(tid))['cpu'] else: raise gdb.GdbError("Sorry, obtaining the current CPU is not yet " "supported with this gdb server.") def per_cpu(var_ptr, cpu): if cpu == -1: cpu = get_current_cpu() if utils.is_target_arch("sparc:v9"): offset = gdb.parse_and_eval( "trap_block[{0}].__per_cpu_base".format(str(cpu))) else: try: offset = gdb.parse_and_eval( "__per_cpu_offset[{0}]".format(str(cpu))) except gdb.error: # !CONFIG_SMP case offset = 0 pointer = var_ptr.cast(utils.get_long_type()) + offset return pointer.cast(var_ptr.type).dereference() cpu_mask = {} def cpu_mask_invalidate(event): global cpu_mask cpu_mask = {} gdb.events.stop.disconnect(cpu_mask_invalidate) if hasattr(gdb.events, 'new_objfile'): gdb.events.new_objfile.disconnect(cpu_mask_invalidate) def cpu_list(mask_name): global cpu_mask mask = None if mask_name in cpu_mask: mask = cpu_mask[mask_name] if mask is None: mask = gdb.parse_and_eval(mask_name + ".bits") if hasattr(gdb, 'events'): cpu_mask[mask_name] = mask gdb.events.stop.connect(cpu_mask_invalidate) if hasattr(gdb.events, 'new_objfile'): gdb.events.new_objfile.connect(cpu_mask_invalidate) bits_per_entry = mask[0].type.sizeof * 8 num_entries = mask.type.sizeof * 8 / bits_per_entry entry = -1 bits = 0 while True: while bits == 0: entry += 1 if entry == num_entries: return bits = mask[entry] if bits != 0: bit = 0 break while bits & 1 == 0: bits >>= 1 bit += 1 cpu = entry * bits_per_entry + bit bits >>= 1 bit += 1 yield cpu class PerCpu(gdb.Function): """Return per-cpu variable. $lx_per_cpu("VAR"[, CPU]): Return the per-cpu variable called VAR for the given CPU number. If CPU is omitted, the CPU of the current context is used. Note that VAR has to be quoted as string.""" def __init__(self): super(PerCpu, self).__init__("lx_per_cpu") def invoke(self, var_name, cpu=-1): var_ptr = gdb.parse_and_eval("&" + var_name.string()) return per_cpu(var_ptr, cpu) PerCpu() class LxCurrentFunc(gdb.Function): """Return current task. $lx_current([CPU]): Return the per-cpu task variable for the given CPU number. If CPU is omitted, the CPU of the current context is used.""" def __init__(self): super(LxCurrentFunc, self).__init__("lx_current") def invoke(self, cpu=-1): var_ptr = gdb.parse_and_eval("&current_task") return per_cpu(var_ptr, cpu).dereference() LxCurrentFunc()
gpl-2.0
eahneahn/free
lib/python2.7/site-packages/django/db/backends/dummy/base.py
114
2198
""" Dummy database backend for Django. Django uses this if the database ENGINE setting is empty (None or empty string). Each of these API functions, except connection.close(), raises ImproperlyConfigured. """ from django.core.exceptions import ImproperlyConfigured from django.db.backends import * from django.db.backends.creation import BaseDatabaseCreation def complain(*args, **kwargs): raise ImproperlyConfigured("settings.DATABASES is improperly configured. " "Please supply the ENGINE value. Check " "settings documentation for more details.") def ignore(*args, **kwargs): pass class DatabaseError(Exception): pass class IntegrityError(DatabaseError): pass class DatabaseOperations(BaseDatabaseOperations): quote_name = complain class DatabaseClient(BaseDatabaseClient): runshell = complain class DatabaseCreation(BaseDatabaseCreation): create_test_db = ignore destroy_test_db = ignore class DatabaseIntrospection(BaseDatabaseIntrospection): get_table_list = complain get_table_description = complain get_relations = complain get_indexes = complain get_key_columns = complain class DatabaseWrapper(BaseDatabaseWrapper): operators = {} # Override the base class implementations with null # implementations. Anything that tries to actually # do something raises complain; anything that tries # to rollback or undo something raises ignore. _cursor = complain _commit = complain _rollback = ignore _close = ignore _savepoint = ignore _savepoint_commit = complain _savepoint_rollback = ignore _set_autocommit = complain set_dirty = complain set_clean = complain def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = BaseDatabaseFeatures(self) self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) def is_usable(self): return True
agpl-3.0
lmazuel/azure-sdk-for-python
azure-mgmt-cognitiveservices/setup.py
2
2834
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- import re import os.path from io import open from setuptools import find_packages, setup try: from azure_bdist_wheel import cmdclass except ImportError: from distutils import log as logger logger.warn("Wheel is not available, disabling bdist_wheel hook") cmdclass = {} # Change the PACKAGE_NAME only to change folder and different name PACKAGE_NAME = "azure-mgmt-cognitiveservices" PACKAGE_PPRINT_NAME = "Cognitive Services Management" # a-b-c => a/b/c package_folder_path = PACKAGE_NAME.replace('-', '/') # a-b-c => a.b.c namespace_name = PACKAGE_NAME.replace('-', '.') # azure v0.x is not compatible with this package # azure v0.x used to have a __version__ attribute (newer versions don't) try: import azure try: ver = azure.__version__ raise Exception( 'This package is incompatible with azure=={}. '.format(ver) + 'Uninstall it with "pip uninstall azure".' ) except AttributeError: pass except ImportError: pass # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, 'version.py'), 'r') as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') with open('README.rst', encoding='utf-8') as f: readme = f.read() with open('HISTORY.rst', encoding='utf-8') as f: history = f.read() setup( name=PACKAGE_NAME, version=version, description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), long_description=readme + '\n\n' + history, license='MIT License', author='Microsoft Corporation', author_email='azpysdkhelp@microsoft.com', url='https://github.com/Azure/azure-sdk-for-python', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', ], zip_safe=False, packages=find_packages(exclude=["tests"]), install_requires=[ 'msrestazure~=0.4.11', 'azure-common~=1.1', ], cmdclass=cmdclass )
mit
destijl/grr
grr/lib/authorization/groups.py
2
1243
#!/usr/bin/env python """Group authorization checking.""" import logging from grr.lib import config_lib from grr.lib import registry class GroupAccessManager(object): __metaclass__ = registry.MetaclassRegistry __abstract = True # pylint: disable=g-bad-name def AuthorizeGroup(self, group, subject): raise NotImplementedError() def MemberOfAuthorizedGroup(self, unused_username, unused_subject): raise NotImplementedError() class NoGroupAccess(GroupAccessManager): """Placeholder class for enabling group ACLs. By default GRR doesn't have the concept of groups. To add it, override this class with a module in lib/local/groups.py that inherits from the same superclass. This class should be able to check group membership in whatever system you use: LDAP/AD/etc. """ def AuthorizeGroup(self, group, subject): raise NotImplementedError("Replace this class to use group authorizations.") def MemberOfAuthorizedGroup(self, unused_username, unused_subject): return False def CreateGroupAccessManager(): group_mgr_cls = config_lib.CONFIG["ACL.group_access_manager_class"] logging.debug("Using group access manager: %s", group_mgr_cls) return GroupAccessManager.classes[group_mgr_cls]()
apache-2.0
LTLMoP/LTLMoP
src/lib/simulator/ode/ckbot/CKBotLib.py
8
4522
# CKBotLib.py # Takes word specifications and choose a gait # Run from ~/Desktop/ltlmop-google OR ~/Downloads/ltlmop-asl # python robots/CKBot/CKBotLib.py import sys, os class CKBotLib: def __init__(self): # Make a list of words that describe gaits #self.words = ["tall","low","fast","action gait","1D motion","non-holonomic turning", # "holonomic","handles steps","handles rough surfaces"]; self.words = [] # Define Gaits # Can add this to text files and parse later #gait0 = Gait("Biped-walk",["tall","fast","non-holonomic turning"]) #gait0.name = "Biped-walk" #gait0.words = ["tall","fast","non-holonomic turning"] #gait1 = Gait("Biped-split",["action gait"]) #gait2 = Gait("Loop-roll",["tall","fast","non-holonomic turning"]) #gait3 = Gait("Loop-somersault",["1D motion","fast"]) #gait4 = Gait("Plus-crawl",["holonomic","low"]) #gait5 = Gait("Slinky-slink",["handles steps","tall"]) #gait6 = Gait("Twist-twist",["low","non-holonomic turning"]) #gait7 = Gait("Snake-crawl",["non-holonomic turning","low"]) #gait8 = Gait("Hexapod-run",["fast","handles rough surfaces"]) #self.poss_gaits = [gait0,gait1, gait2, gait3, gait4, gait5, gait6, gait7, gait8] self.poss_gaits = [] def readLibe(self): """ Parse library file """ curdir = os.getcwd() if ("simulator" in curdir) and ("ode" in curdir) and ("ckbot" in curdir): f = open('library/CKBotTraits.libe','r') else: f = open('lib/simulator/ode/ckbot/library/CKBotTraits.libe','r') reading_trait = 0 gait_number = 0 cgpair = [] # Make temporary gaitnames variable gaitnames = [] # Will have same indices of self.poss_gaits, but is a list of names, not gaits for line in f: # Find Config-Gait pairs in a trait # if we just read a trait, add config-pairs to self.poss_gaits if (reading_trait == 1): if line == "\n": reading_trait = 0 # Loop through cgpairs with this specific trait so we can build self.poss_gaits[] for pair in cgpair: # Make a new gait object if one with the same name doesn't exist if (pair not in gaitnames): # specify current cgpair with last trait in self.words gaitnames.append(pair) self.poss_gaits.append(Gait(pair,[self.words[-1]])) # Add trait to already made gait object self.poss_gaits[i].words else: idx = gaitnames.index(pair) self.poss_gaits[idx].words.append(self.words[-1]) # Restart cgpair cgpair = [] # Add config-gait to cgpair list elif (line[0] != "#") and not (line.strip() in cgpair): cgpair.append(line.strip()) # Find Gait Traits if (line.split().count("Trait:")>0): info = line.split(": ") self.words.append(info[1].strip()) gait_number = gait_number + 1 reading_trait = 1 def findGait(self,desired_words): # Find gaits that meet specification gait_match = 0 # does a specific gait match? gait_found = 0 # is there at least one gait that matches goodgaits = [] for gait in self.poss_gaits: for word in desired_words: if word in gait.words: #print "gait", gait.name,"has trait",word gait_match = gait_match + 1 if gait_match == len(desired_words): #print "gait is", gait.name goodgaits.append(gait.name) gait_found = 1 gait_match = 0 #print goodgaits # If no gaits were found, print "gait not found" if gait_found == 0: #print "gait not found" return # If a gait was found, run it in the simulator else: # Use first goodgait if we have more than one gait #print goodgaits [config,gait] = goodgaits[0].split("-") #print config #print gait return config class Gait: def __init__(self,name,words): self.name = "Config-gait" self.words = None self.name = name self.words = words if (__name__ == '__main__'): # Test list libs = CKBotLib() libs.readLibe() print "These are available definitions:" print libs.words print "\n" # Get user input desired_gait = raw_input('Enter gait specifications: ') #print "desired gait is", desired_gait # Parse input desired_words = desired_gait.split(" and ") # Run configuration in CKBot Simulator config = libs.findGait(desired_words) if config != None: print "Valid configuration: " + config + "\n" os.system("python CKBotSim.py " + config) #os.system("python lib/simulator/ode/ckbot/CKBotSim.py " + config) else: print "No configuration found for the specified trait set.\n"
gpl-3.0
t0mk/ansible
lib/ansible/utils/module_docs_fragments/avi.py
48
1616
# # Created on December 12, 2016 # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Avi Version: 16.3.4 # # # 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 <http://www.gnu.org/licenses/>. # class ModuleDocFragment(object): # Avi common documentation fragment DOCUMENTATION = """ options: controller: description: - IP address or hostname of the controller. The default value is the environment variable C(AVI_CONTROLLER). username: description: - Username used for accessing Avi controller. The default value is the environment variable C(AVI_USERNAME). password: description: - Password of Avi user in Avi controller. The default value is the environment variable C(AVI_PASSWORD). tenant: description: - Name of tenant used for all Avi API calls and context of object. default: admin tenant_uuid: description: - UUID of tenant used for all Avi API calls and context of object. default: '' """
gpl-3.0
ar7z1/ansible
lib/ansible/modules/network/panos/panos_dag_tags.py
10
7296
#!/usr/bin/python # -*- coding: utf-8 -*- # # Ansible module to manage PaloAltoNetworks Firewall # (c) 2016, techbizdev <techbizdev@paloaltonetworks.com> # # 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 <http://www.gnu.org/licenses/>. # limitations under the License. ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: panos_dag_tags short_description: Create tags for DAG's on PAN-OS devices. description: - Create the ip address to tag associations. Tags will in turn be used to create DAG's author: "Vinay Venkataraghavan (@vinayvenkat)" version_added: "2.5" requirements: - pan-python can be obtained from PyPI U(https://pypi.org/project/pan-python/) - pandevice can be obtained from PyPI U(https://pypi.org/project/pandevice/) notes: - Checkmode is not supported. - Panorama is not supported. options: api_key: description: - API key that can be used instead of I(username)/I(password) credentials. description: description: - The purpose / objective of the static Address Group commit: description: - commit if changed default: true devicegroup: description: > - Device groups are used for the Panorama interaction with Firewall(s). The group must exists on Panorama. If device group is not define we assume that we are contacting Firewall. operation: description: - The action to be taken. Supported values are I(add)/I(update)/I(find)/I(delete). tag_names: description: - The list of the tags that will be added or removed from the IP address. ip_to_register: description: - IP that will be registered with the given tag names. extends_documentation_fragment: panos ''' EXAMPLES = ''' - name: Create the tags to map IP addresses panos_dag_tags: ip_address: "{{ ip_address }}" password: "{{ password }}" ip_to_register: "{{ ip_to_register }}" tag_names: "{{ tag_names }}" description: "Tags to allow certain IP's to access various SaaS Applications" operation: 'add' tags: "adddagip" - name: List the IP address to tag mapping panos_dag_tags: ip_address: "{{ ip_address }}" password: "{{ password }}" tag_names: "{{ tag_names }}" description: "List the IP address to tag mapping" operation: 'list' tags: "listdagip" - name: Unregister an IP address from a tag mapping panos_dag_tags: ip_address: "{{ ip_address }}" password: "{{ password }}" ip_to_register: "{{ ip_to_register }}" tag_names: "{{ tag_names }}" description: "Unregister IP address from tag mappings" operation: 'delete' tags: "deletedagip" ''' RETURN = ''' # Default return values ''' try: from pandevice import base from pandevice import firewall from pandevice import panorama from pandevice import objects from pan.xapi import PanXapiError HAS_LIB = True except ImportError: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native def get_devicegroup(device, devicegroup): dg_list = device.refresh_devices() for group in dg_list: if isinstance(group, panorama.DeviceGroup): if group.name == devicegroup: return group return False def register_ip_to_tag_map(device, ip_addresses, tag): exc = None try: device.userid.register(ip_addresses, tag) except PanXapiError as exc: return False, exc return True, exc def get_all_address_group_mapping(device): exc = None ret = None try: ret = device.userid.get_registered_ip() except PanXapiError as exc: return False, exc return ret, exc def delete_address_from_mapping(device, ip_address, tags): exc = None try: ret = device.userid.unregister(ip_address, tags) except PanXapiError as exc: return False, exc return True, exc def main(): argument_spec = dict( ip_address=dict(required=True), password=dict(required=True, no_log=True), username=dict(default='admin'), api_key=dict(no_log=True), devicegroup=dict(default=None), description=dict(default=None), ip_to_register=dict(type='str', required=False), tag_names=dict(type='list', required=True), commit=dict(type='bool', default=True), operation=dict(type='str', required=True) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_LIB: module.fail_json(msg='pan-python is required for this module') ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] api_key = module.params['api_key'] commit = module.params['commit'] devicegroup = module.params['devicegroup'] operation = module.params['operation'] # Create the device with the appropriate pandevice type device = base.PanDevice.create_from_device(ip_address, username, password, api_key=api_key) # If Panorama, validate the devicegroup dev_group = None if devicegroup and isinstance(device, panorama.Panorama): dev_group = get_devicegroup(device, devicegroup) if dev_group: device.add(dev_group) else: module.fail_json(msg='\'%s\' device group not found in Panorama. Is the name correct?' % devicegroup) result = None if operation == 'add': result, exc = register_ip_to_tag_map(device, ip_addresses=module.params.get('ip_to_register', None), tag=module.params.get('tag_names', None) ) elif operation == 'list': result, exc = get_all_address_group_mapping(device) elif operation == 'delete': result, exc = delete_address_from_mapping(device, ip_address=module.params.get('ip_to_register', None), tags=module.params.get('tag_names', []) ) else: module.fail_json(msg="Unsupported option") if not result: module.fail_json(msg=exc.message) if commit: try: device.commit(sync=True) except PanXapiError as exc: module.fail_json(msg=to_native(exc)) module.exit_json(changed=True, msg=result) if __name__ == "__main__": main()
gpl-3.0
Timmenem/micropython
tests/misc/features.py
87
1952
# mad.py # Alf Clement 27-Mar-2014 # zero=0 three=3 print("1") print("2") print(three) print("{}".format(4)) five=25//5 print(int(five)) j=0 for i in range(4): j += i print(j) print(3+4) try: a=4//zero except: print(8) print("xxxxxxxxx".count("x")) def ten(): return 10 print(ten()) a=[] for i in range(13): a.append(i) print(a[11]) print(a[-1]) str="0123456789" print(str[1]+str[3]) def p(s): print(s) p("14") p(15) class A: def __init__(self): self.a=16 def print(self): print(self.a) def set(self,b): self.a=b a=A() a.print() a.set(17) a.print() b=A() b.set(a.a + 1) b.print() for i in range(20): pass print(i) if 20 > 30: a="1" else: a="2" if 0 < 4: print(a+"0") else: print(a+"1") a=[20,21,22,23,24] for i in a: if i < 21: continue if i > 21: break print(i) b=[a,a,a] print(b[1][2]) print(161//7) a=24 while True: try: def gcheck(): global a print(a) gcheck() class c25(): x=25 x=c25() print(x.x) raise except: print(26) print(27+zero) break print(28) k=29 def f(): global k k = yield k print(next(f())) while True: k+= 1 if k < 30: continue break print(k) for i in [1,2,3]: class A(): def __init__(self, c): self.a = i+10*c b = A(3) print(b.a) print(34) p=0 for i in range(35, -1, -1): print(i) p = p + 1 if p > 0: break p=36 while p == 36: print(p) p=37 print(p) for i in [38]: print(i) print(int(exec("def foo(): return 38") == None)+foo()) d = {} exec("def bar(): return 40", d) print(d["bar"]()) def fib2(n): result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return result print(fib2(100)[-2]-14) Answer={} Answer["ForAll"]=42 print(Answer["ForAll"]) i = 43 def f(i=i): print(i) i = 44 f() print(i) while True: try: if None != True: print(45) break else: print(0) except: print(0) print(46) print(46+1) def u(p): if p > 3: return 3*p else: return u(2*p)-3*u(p) print(u(16)) def u49(): return 49 print(u49())
mit
jonyroda97/redbot-amigosprovaveis
lib/matplotlib/backends/backend_nbagg.py
2
9384
"""Interactive figures in the IPython notebook""" # Note: There is a notebook in # lib/matplotlib/backends/web_backend/nbagg_uat.ipynb to help verify # that changes made maintain expected behaviour. import datetime from base64 import b64encode import json import io import os import six from uuid import uuid4 as uuid import tornado.ioloop from IPython.display import display, Javascript, HTML try: # Jupyter/IPython 4.x or later from ipykernel.comm import Comm except ImportError: # Jupyter/IPython 3.x or earlier from IPython.kernel.comm import Comm from matplotlib import rcParams, is_interactive from matplotlib._pylab_helpers import Gcf from matplotlib.backends.backend_webagg_core import ( FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg, TimerTornado) from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, NavigationToolbar2) from matplotlib.figure import Figure from matplotlib import is_interactive from matplotlib.backends.backend_webagg_core import (FigureManagerWebAgg, FigureCanvasWebAggCore, NavigationToolbar2WebAgg, TimerTornado) from matplotlib.backend_bases import (ShowBase, NavigationToolbar2, FigureCanvasBase) def connection_info(): """ Return a string showing the figure and connection status for the backend. This is intended as a diagnostic tool, and not for general use. """ result = [] for manager in Gcf.get_all_fig_managers(): fig = manager.canvas.figure result.append('{0} - {0}'.format((fig.get_label() or "Figure {0}".format(manager.num)), manager.web_sockets)) if not is_interactive(): result.append('Figures pending show: {0}'.format(len(Gcf._activeQue))) return '\n'.join(result) # Note: Version 3.2 and 4.x icons # http://fontawesome.io/3.2.1/icons/ # http://fontawesome.io/ # the `fa fa-xxx` part targets font-awesome 4, (IPython 3.x) # the icon-xxx targets font awesome 3.21 (IPython 2.x) _FONT_AWESOME_CLASSES = { 'home': 'fa fa-home icon-home', 'back': 'fa fa-arrow-left icon-arrow-left', 'forward': 'fa fa-arrow-right icon-arrow-right', 'zoom_to_rect': 'fa fa-square-o icon-check-empty', 'move': 'fa fa-arrows icon-move', 'download': 'fa fa-floppy-o icon-save', None: None } class NavigationIPy(NavigationToolbar2WebAgg): # Use the standard toolbar items + download button toolitems = [(text, tooltip_text, _FONT_AWESOME_CLASSES[image_file], name_of_method) for text, tooltip_text, image_file, name_of_method in (NavigationToolbar2.toolitems + (('Download', 'Download plot', 'download', 'download'),)) if image_file in _FONT_AWESOME_CLASSES] class FigureManagerNbAgg(FigureManagerWebAgg): ToolbarCls = NavigationIPy def __init__(self, canvas, num): self._shown = False FigureManagerWebAgg.__init__(self, canvas, num) def display_js(self): # XXX How to do this just once? It has to deal with multiple # browser instances using the same kernel (require.js - but the # file isn't static?). display(Javascript(FigureManagerNbAgg.get_javascript())) def show(self): if not self._shown: self.display_js() self._create_comm() else: self.canvas.draw_idle() self._shown = True def reshow(self): """ A special method to re-show the figure in the notebook. """ self._shown = False self.show() @property def connected(self): return bool(self.web_sockets) @classmethod def get_javascript(cls, stream=None): if stream is None: output = io.StringIO() else: output = stream super(FigureManagerNbAgg, cls).get_javascript(stream=output) with io.open(os.path.join( os.path.dirname(__file__), "web_backend", "nbagg_mpl.js"), encoding='utf8') as fd: output.write(fd.read()) if stream is None: return output.getvalue() def _create_comm(self): comm = CommSocket(self) self.add_web_socket(comm) return comm def destroy(self): self._send_event('close') # need to copy comms as callbacks will modify this list for comm in list(self.web_sockets): comm.on_close() self.clearup_closed() def clearup_closed(self): """Clear up any closed Comms.""" self.web_sockets = set([socket for socket in self.web_sockets if socket.is_open()]) if len(self.web_sockets) == 0: self.canvas.close_event() def remove_comm(self, comm_id): self.web_sockets = set([socket for socket in self.web_sockets if not socket.comm.comm_id == comm_id]) class FigureCanvasNbAgg(FigureCanvasWebAggCore): def new_timer(self, *args, **kwargs): return TimerTornado(*args, **kwargs) class CommSocket(object): """ Manages the Comm connection between IPython and the browser (client). Comms are 2 way, with the CommSocket being able to publish a message via the send_json method, and handle a message with on_message. On the JS side figure.send_message and figure.ws.onmessage do the sending and receiving respectively. """ def __init__(self, manager): self.supports_binary = None self.manager = manager self.uuid = str(uuid()) # Publish an output area with a unique ID. The javascript can then # hook into this area. display(HTML("<div id=%r></div>" % self.uuid)) try: self.comm = Comm('matplotlib', data={'id': self.uuid}) except AttributeError: raise RuntimeError('Unable to create an IPython notebook Comm ' 'instance. Are you in the IPython notebook?') self.comm.on_msg(self.on_message) manager = self.manager self._ext_close = False def _on_close(close_message): self._ext_close = True manager.remove_comm(close_message['content']['comm_id']) manager.clearup_closed() self.comm.on_close(_on_close) def is_open(self): return not (self._ext_close or self.comm._closed) def on_close(self): # When the socket is closed, deregister the websocket with # the FigureManager. if self.is_open(): try: self.comm.close() except KeyError: # apparently already cleaned it up? pass def send_json(self, content): self.comm.send({'data': json.dumps(content)}) def send_binary(self, blob): # The comm is ascii, so we always send the image in base64 # encoded data URL form. data = b64encode(blob) if six.PY3: data = data.decode('ascii') data_uri = "data:image/png;base64,{0}".format(data) self.comm.send({'data': data_uri}) def on_message(self, message): # The 'supports_binary' message is relevant to the # websocket itself. The other messages get passed along # to matplotlib as-is. # Every message has a "type" and a "figure_id". message = json.loads(message['content']['data']) if message['type'] == 'closing': self.on_close() self.manager.clearup_closed() elif message['type'] == 'supports_binary': self.supports_binary = message['value'] else: self.manager.handle_json(message) @_Backend.export class _BackendNbAgg(_Backend): FigureCanvas = FigureCanvasNbAgg FigureManager = FigureManagerNbAgg @staticmethod def new_figure_manager_given_figure(num, figure): canvas = FigureCanvasNbAgg(figure) if rcParams['nbagg.transparent']: figure.patch.set_alpha(0) manager = FigureManagerNbAgg(canvas, num) if is_interactive(): manager.show() figure.canvas.draw_idle() canvas.mpl_connect('close_event', lambda event: Gcf.destroy(num)) return manager @staticmethod def trigger_manager_draw(manager): manager.show() @staticmethod def show(): from matplotlib._pylab_helpers import Gcf managers = Gcf.get_all_fig_managers() if not managers: return interactive = is_interactive() for manager in managers: manager.show() # plt.figure adds an event which puts the figure in focus # in the activeQue. Disable this behaviour, as it results in # figures being put as the active figure after they have been # shown, even in non-interactive mode. if hasattr(manager, '_cidgcf'): manager.canvas.mpl_disconnect(manager._cidgcf) if not interactive and manager in Gcf._activeQue: Gcf._activeQue.remove(manager)
gpl-3.0
kustodian/ansible
test/sanity/code-smell/release-names.py
63
1695
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2019, Ansible Project # # 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 <http://www.gnu.org/licenses/>. """ Test that the release name is present in the list of used up release names """ from __future__ import (absolute_import, division, print_function) __metaclass__ = type from yaml import safe_load from ansible.release import __codename__ def main(): """Entrypoint to the script""" with open('.github/RELEASE_NAMES.yml') as f: releases = safe_load(f.read()) # Why this format? The file's sole purpose is to be read by a human when they need to know # which release names have already been used. So: # 1) It's easier for a human to find the release names when there's one on each line # 2) It helps keep other people from using the file and then asking for new features in it for name in (r.split(maxsplit=1)[1] for r in releases): if __codename__ == name: break else: print('.github/RELEASE_NAMES.yml: Current codename was not present in the file') if __name__ == '__main__': main()
gpl-3.0
cogmission/nupic
examples/opf/experiments/spatial_classification/auto_generated/searchDef.py
34
2300
#! /usr/bin/env python # ---------------------------------------------------------------------- # 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 Affero 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import os def getSearch(rootDir): """ This method returns search description. See the following file for the schema of the dictionary this method returns: py/nupic/swarming/exp_generator/experimentDescriptionSchema.json The streamDef element defines the stream for this model. The schema for this element can be found at: py/nupicengine/cluster/database/StreamDef.json """ # Form the stream definition dataPath = os.path.abspath(os.path.join(rootDir, 'datasets', 'scalar_1.csv')) streamDef = dict( version = 1, info = "testSpatialClassification", streams = [ dict(source="file://%s" % (dataPath), info="scalar_1.csv", columns=["*"], ), ], ) # Generate the experiment description expDesc = { "environment": 'nupic', "inferenceArgs":{ "predictedField":"classification", "predictionSteps": [0], }, "inferenceType": "MultiStep", "streamDef": streamDef, "includedFields": [ { "fieldName": "field1", "fieldType": "float", }, { "fieldName": "classification", "fieldType": "string", }, { "fieldName": "randomData", "fieldType": "float", }, ], "iterationCount": -1, } return expDesc
agpl-3.0
vdmann/cse-360-image-hosting-website
lib/python2.7/site-packages/django/shortcuts/__init__.py
116
5748
""" This module collects helper functions and classes that "span" multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ import warnings from django.template import loader, RequestContext from django.http import HttpResponse, Http404 from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.db.models.base import ModelBase from django.db.models.manager import Manager from django.db.models.query import QuerySet from django.core import urlresolvers def render_to_response(*args, **kwargs): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ httpresponse_kwargs = {'content_type': kwargs.pop('content_type', None)} mimetype = kwargs.pop('mimetype', None) if mimetype: warnings.warn("The mimetype keyword argument is deprecated, use " "content_type instead", DeprecationWarning, stacklevel=2) httpresponse_kwargs['content_type'] = mimetype return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) def render(request, *args, **kwargs): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. Uses a RequestContext by default. """ httpresponse_kwargs = { 'content_type': kwargs.pop('content_type', None), 'status': kwargs.pop('status', None), } if 'context_instance' in kwargs: context_instance = kwargs.pop('context_instance') if kwargs.get('current_app', None): raise ValueError('If you provide a context_instance you must ' 'set its current_app before calling render()') else: current_app = kwargs.pop('current_app', None) context_instance = RequestContext(request, current_app=current_app) kwargs['context_instance'] = context_instance return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) def redirect(to, *args, **kwargs): """ Returns an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urlresolvers.reverse()` will be used to reverse-resolve the name. * A URL, which will be used as-is for the redirect location. By default issues a temporary redirect; pass permanent=True to issue a permanent redirect """ if kwargs.pop('permanent', False): redirect_class = HttpResponsePermanentRedirect else: redirect_class = HttpResponseRedirect return redirect_class(resolve_url(to, *args, **kwargs)) def _get_queryset(klass): """ Returns a QuerySet from a Model, Manager, or QuerySet. Created to make get_object_or_404 and get_list_or_404 more DRY. Raises a ValueError if klass is not a Model, Manager, or QuerySet. """ if isinstance(klass, QuerySet): return klass elif isinstance(klass, Manager): manager = klass elif isinstance(klass, ModelBase): manager = klass._default_manager else: klass__name = klass.__name__ if isinstance(klass, type) \ else klass.__class__.__name__ raise ValueError("Object is of type '%s', but must be a Django Model, " "Manager, or QuerySet" % klass__name) return manager.all() def get_object_or_404(klass, *args, **kwargs): """ Uses get() to return an object, or raises a Http404 exception if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Note: Like with get(), an MultipleObjectsReturned will be raised if more than one object is found. """ queryset = _get_queryset(klass) try: return queryset.get(*args, **kwargs) except queryset.model.DoesNotExist: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) def get_list_or_404(klass, *args, **kwargs): """ Uses filter() to return a list of objects, or raise a Http404 exception if the list is empty. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the filter() query. """ queryset = _get_queryset(klass) obj_list = list(queryset.filter(*args, **kwargs)) if not obj_list: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) return obj_list def resolve_url(to, *args, **kwargs): """ Return a URL appropriate for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urlresolvers.reverse()` will be used to reverse-resolve the name. * A URL, which will be returned as-is. """ # If it's a model, use get_absolute_url() if hasattr(to, 'get_absolute_url'): return to.get_absolute_url() # Next try a reverse URL resolution. try: return urlresolvers.reverse(to, args=args, kwargs=kwargs) except urlresolvers.NoReverseMatch: # If this is a callable, re-raise. if callable(to): raise # If this doesn't "feel" like a URL, re-raise. if '/' not in to and '.' not in to: raise # Finally, fall back and assume it's a URL return to
mit
Universal-Model-Converter/UMC3.0a
data/Python/x86/Lib/site-packages/OpenGL/GL/NV/texture_shader.py
3
8361
'''OpenGL extension NV.texture_shader This module customises the behaviour of the OpenGL.raw.GL.NV.texture_shader to provide a more Python-friendly API Overview (from the spec) Standard OpenGL and the ARB_multitexture extension define a straightforward direct mechanism for mapping sets of texture coordinates to filtered colors. This extension provides a more functional mechanism. OpenGL's standard texturing mechanism defines a set of texture targets. Each texture target defines how the texture image is specified and accessed via a set of texture coordinates. OpenGL 1.0 defines the 1D and 2D texture targets. OpenGL 1.2 (and/or the EXT_texture3D extension) defines the 3D texture target. The ARB_texture_cube_map extension defines the cube map texture target. Each texture unit's texture coordinate set is mapped to a color using the unit's highest priority enabled texture target. This extension introduces texture shader stages. A sequence of texture shader stages provides a more flexible mechanism for mapping sets of texture coordinates to texture unit RGBA results than standard OpenGL. When the texture shader enable is on, the extension replaces the conventional OpenGL mechanism for mapping sets of texture coordinates to filtered colors with this extension's sequence of texture shader stages. Each texture shader stage runs one of 21 canned texture shader programs. These programs support conventional OpenGL texture mapping but also support dependent texture accesses, dot product texture programs, and special modes. (3D texture mapping texture shader operations are NOT provided by this extension; 3D texture mapping texture shader operations are added by the NV_texture_shader2 extension that is layered on this extension. See the NV_texture_shader2 specification.) To facilitate the new texture shader programs, this extension introduces several new texture formats and variations on existing formats. Existing color texture formats are extended by introducing new signed variants. Two new types of texture formats (beyond colors) are also introduced. Texture offset groups encode two signed offsets, and optionally a magnitude or a magnitude and an intensity. The new HILO (pronounced high-low) formats provide possibly signed, high precision (16-bit) two-component textures. Each program takes as input the stage's interpolated texture coordinate set (s,t,r,q). Each program generates two results: a shader stage result that may be used as an input to subsequent shader stage programs, and a texture unit RGBA result that becomes the texture color used by the texture unit's texture environment function or becomes the initial value for the corresponding texture register for register combiners. The texture unit RGBA result is always an RGBA color, but the shader stage result may be one of an RGBA color, a HILO value, a texture offset group, a floating-point value, or an invalid result. When both results are RGBA colors, the shader stage result and the texture unit RGBA result are usually identical (though not in all cases). Additionally, certain programs have a side-effect such as culling the fragment or replacing the fragment's depth value. The twenty-one programs are briefly described: <none> 1. NONE - Always generates a (0,0,0,0) texture unit RGBA result. Equivalent to disabling all texture targets in conventional OpenGL. <conventional textures> 2. TEXTURE_1D - Accesses a 1D texture via (s/q). 3. TEXTURE_2D - Accesses a 2D texture via (s/q,t/q). 4. TEXTURE_RECTANGLE_NV - Accesses a rectangular texture via (s/q,t/q). 5. TEXTURE_CUBE_MAP_ARB - Accesses a cube map texture via (s,t,r). <special modes> 6. PASS_THROUGH_NV - Converts a texture coordinate (s,t,r,q) directly to a [0,1] clamped (r,g,b,a) texture unit RGBA result. 7. CULL_FRAGMENT_NV - Culls the fragment based on the whether each (s,t,r,q) is "greater than or equal to zero" or "less than zero". <offset textures> 8. OFFSET_TEXTURE_2D_NV - Transforms the signed (ds,dt) components of a previous texture unit by a 2x2 floating-point matrix and then uses the result to offset the stage's texture coordinates for a 2D non-projective texture. 9. OFFSET_TEXTURE_2D_SCALE_NV - Same as above except the magnitude component of the previous texture unit result scales the red, green, and blue components of the unsigned RGBA texture 2D access. 10. OFFSET_TEXTURE_RECTANGLE_NV - Similar to OFFSET_TEXTURE_2D_NV except that the texture access is into a rectangular non-projective texture. 11. OFFSET_TEXTURE_RECTANGLE_SCALE_NV - Similar to OFFSET_TEXTURE_2D_SCALE_NV except that the texture access is into a rectangular non-projective texture. <dependent textures> 12. DEPENDENT_AR_TEXTURE_2D_NV - Converts the alpha and red components of a previous shader result into an (s,t) texture coordinate set to access a 2D non-projective texture. 13. DEPENDENT_GB_TEXTURE_2D_NV - Converts the green and blue components of a previous shader result into an (s,t) texture coordinate set to access a 2D non-projective texture. <dot product textures> 14. DOT_PRODUCT_NV - Computes the dot product of the texture shader's texture coordinate set (s,t,r) with some mapping of the components of a previous texture shader result. The component mapping depends on the type (RGBA or HILO) and signedness of the stage's previous texture input. Other dot product texture programs use the result of this program to compose a texture coordinate set for a dependent texture access. The color result is undefined. 15. DOT_PRODUCT_TEXTURE_2D_NV - When preceded by a DOT_PRODUCT_NV program in the previous texture shader stage, computes a second similar dot product and composes the two dot products into (s,t) texture coordinate set to access a 2D non-projective texture. 16. DOT_PRODUCT_TEXTURE_RECTANGLE_NV - Similar to DOT_PRODUCT_TEXTURE_2D_NV except that the texture acces is into a rectangular non-projective texture. 17. DOT_PRODUCT_TEXTURE_CUBE_MAP_NV - When preceded by two DOT_PRODUCT_NV programs in the previous two texture shader stages, computes a third similar dot product and composes the three dot products into (s,t,r) texture coordinate set to access a cube map texture. 18. DOT_PRODUCT_REFLECT_CUBE_MAP_NV - When preceded by two DOT_PRODUCT_NV programs in the previous two texture shader stages, computes a third similar dot product and composes the three dot products into a normal vector (Nx,Ny,Nz). An eye vector (Ex,Ey,Ez) is composed from the q texture coordinates of the three stages. A reflection vector (Rx,Ry,Rz) is computed based on the normal and eye vectors. The reflection vector forms an (s,t,r) texture coordinate set to access a cube map texture. 19. DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV - Operates like DOT_PRODUCT_REFLECT_CUBE_MAP_NV except that the eye vector (Ex,Ey,Ez) is a user-defined constant rather than composed from the q coordinates of the three stages. 20. DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV - When used instead of the second DOT_PRODUCT_NV program preceding a DOT_PRODUCT_REFLECT_CUBE_MAP_NV or DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV stage, the normal vector forms an (s,t,r) texture coordinate set to access a cube map texture. <dot product depth replace> 21. DOT_PRODUCT_DEPTH_REPLACE_NV - When preceded by a DOT_PRODUCT_NV program in the previous texture shader stage, computes a second similar dot product and replaces the fragment's window-space depth value with the first dot product results divided by the second. The texture unit RGBA result is (0,0,0,0). The official definition of this extension is available here: http://www.opengl.org/registry/specs/NV/texture_shader.txt ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from OpenGL.GL import glget import ctypes from OpenGL.raw.GL.NV.texture_shader import * ### END AUTOGENERATED SECTION
mit
frewsxcv/AutobahnPython
examples/asyncio/websocket/echo/client_coroutines_py2.py
5
2143
############################################################################### ## ## Copyright (C) 2013-2014 Tavendo GmbH ## ## 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 autobahn.asyncio.websocket import WebSocketClientProtocol, \ WebSocketClientFactory import asyncio class MyClientProtocol(WebSocketClientProtocol): def onConnect(self, response): print("Server connected: {0}".format(response.peer)) @asyncio.coroutine def onOpen(self): print("WebSocket connection open.") ## start sending messages every second .. while True: self.sendMessage(u"Hello, world!".encode('utf8')) self.sendMessage(b"\x00\x01\x03\x04", isBinary = True) yield asyncio.sleep(1) def onMessage(self, payload, isBinary): if isBinary: print("Binary message received: {0} bytes".format(len(payload))) else: print("Text message received: {0}".format(payload.decode('utf8'))) def onClose(self, wasClean, code, reason): print("WebSocket connection closed: {0}".format(reason)) if __name__ == '__main__': try: import asyncio except ImportError: ## Trollius >= 0.3 was renamed import trollius as asyncio factory = WebSocketClientFactory("ws://localhost:9000", debug = False) factory.protocol = MyClientProtocol loop = asyncio.get_event_loop() coro = loop.create_connection(factory, '127.0.0.1', 9000) loop.run_until_complete(coro) loop.run_forever() loop.close()
apache-2.0
andymckay/django
tests/regressiontests/localflavor/cn/tests.py
33
4892
# Tests for contrib/localflavor/ CN Form Fields from django.contrib.localflavor.cn.forms import (CNProvinceSelect, CNPostCodeField, CNIDCardField, CNPhoneNumberField, CNCellNumberField) from django.test import SimpleTestCase class CNLocalFlavorTests(SimpleTestCase): def test_CNProvinceSelect(self): f = CNProvinceSelect() correct_output = u'''<select name="provinces"> <option value="anhui">\u5b89\u5fbd</option> <option value="beijing">\u5317\u4eac</option> <option value="chongqing">\u91cd\u5e86</option> <option value="fujian">\u798f\u5efa</option> <option value="gansu">\u7518\u8083</option> <option value="guangdong">\u5e7f\u4e1c</option> <option value="guangxi">\u5e7f\u897f\u58ee\u65cf\u81ea\u6cbb\u533a</option> <option value="guizhou">\u8d35\u5dde</option> <option value="hainan">\u6d77\u5357</option> <option value="hebei">\u6cb3\u5317</option> <option value="heilongjiang">\u9ed1\u9f99\u6c5f</option> <option value="henan">\u6cb3\u5357</option> <option value="hongkong">\u9999\u6e2f</option> <option value="hubei" selected="selected">\u6e56\u5317</option> <option value="hunan">\u6e56\u5357</option> <option value="jiangsu">\u6c5f\u82cf</option> <option value="jiangxi">\u6c5f\u897f</option> <option value="jilin">\u5409\u6797</option> <option value="liaoning">\u8fbd\u5b81</option> <option value="macao">\u6fb3\u95e8</option> <option value="neimongol">\u5185\u8499\u53e4\u81ea\u6cbb\u533a</option> <option value="ningxia">\u5b81\u590f\u56de\u65cf\u81ea\u6cbb\u533a</option> <option value="qinghai">\u9752\u6d77</option> <option value="shaanxi">\u9655\u897f</option> <option value="shandong">\u5c71\u4e1c</option> <option value="shanghai">\u4e0a\u6d77</option> <option value="shanxi">\u5c71\u897f</option> <option value="sichuan">\u56db\u5ddd</option> <option value="taiwan">\u53f0\u6e7e</option> <option value="tianjin">\u5929\u6d25</option> <option value="xinjiang">\u65b0\u7586\u7ef4\u543e\u5c14\u81ea\u6cbb\u533a</option> <option value="xizang">\u897f\u85cf\u81ea\u6cbb\u533a</option> <option value="yunnan">\u4e91\u5357</option> <option value="zhejiang">\u6d59\u6c5f</option> </select>''' self.assertHTMLEqual(f.render('provinces', 'hubei'), correct_output) def test_CNPostCodeField(self): error_format = [u'Enter a post code in the format XXXXXX.'] valid = { '091209': u'091209' } invalid = { '09120': error_format, '09120916': error_format } self.assertFieldOutput(CNPostCodeField, valid, invalid) def test_CNIDCardField(self): valid = { # A valid 1st generation ID Card Number. '110101491001001': u'110101491001001', # A valid 2nd generation ID Card number. '11010119491001001X': u'11010119491001001X', # Another valid 2nd gen ID Number with a case change '11010119491001001x': u'11010119491001001X' } wrong_format = [u'ID Card Number consists of 15 or 18 digits.'] wrong_location = [u'Invalid ID Card Number: Wrong location code'] wrong_bday = [u'Invalid ID Card Number: Wrong birthdate'] wrong_checksum = [u'Invalid ID Card Number: Wrong checksum'] invalid = { 'abcdefghijklmnop': wrong_format, '1010101010101010': wrong_format, '010101491001001' : wrong_location, # 1st gen, 01 is invalid '110101491041001' : wrong_bday, # 1st gen. There wasn't day 41 '92010119491001001X': wrong_location, # 2nd gen, 92 is invalid '91010119491301001X': wrong_bday, # 2nd gen, 19491301 is invalid date '910101194910010014': wrong_checksum #2nd gen } self.assertFieldOutput(CNIDCardField, valid, invalid) def test_CNPhoneNumberField(self): error_format = [u'Enter a valid phone number.'] valid = { '010-12345678': u'010-12345678', '010-1234567': u'010-1234567', '0101-12345678': u'0101-12345678', '0101-1234567': u'0101-1234567', '010-12345678-020':u'010-12345678-020' } invalid = { '01x-12345678': error_format, '12345678': error_format, '01123-12345678': error_format, '010-123456789': error_format, '010-12345678-': error_format } self.assertFieldOutput(CNPhoneNumberField, valid, invalid) def test_CNCellNumberField(self): error_format = [u'Enter a valid cell number.'] valid = { '13012345678': u'13012345678', } invalid = { '130123456789': error_format, '14012345678': error_format } self.assertFieldOutput(CNCellNumberField, valid, invalid)
bsd-3-clause
kyoungrok0517/linguist
samples/Python/tornado-httpserver.py
92
18852
#!/usr/bin/env python # # Copyright 2009 Facebook # # 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. """A non-blocking, single-threaded HTTP server. Typical applications have little direct interaction with the `HTTPServer` class except to start a server at the beginning of the process (and even that is often done indirectly via `tornado.web.Application.listen`). This module also defines the `HTTPRequest` class which is exposed via `tornado.web.RequestHandler.request`. """ from __future__ import absolute_import, division, with_statement import Cookie import logging import socket import time from tornado.escape import utf8, native_str, parse_qs_bytes from tornado import httputil from tornado import iostream from tornado.netutil import TCPServer from tornado import stack_context from tornado.util import b, bytes_type try: import ssl # Python 2.6+ except ImportError: ssl = None class HTTPServer(TCPServer): r"""A non-blocking, single-threaded HTTP server. A server is defined by a request callback that takes an HTTPRequest instance as an argument and writes a valid HTTP response with `HTTPRequest.write`. `HTTPRequest.finish` finishes the request (but does not necessarily close the connection in the case of HTTP/1.1 keep-alive requests). A simple example server that echoes back the URI you requested:: import httpserver import ioloop def handle_request(request): message = "You requested %s\n" % request.uri request.write("HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s" % ( len(message), message)) request.finish() http_server = httpserver.HTTPServer(handle_request) http_server.listen(8888) ioloop.IOLoop.instance().start() `HTTPServer` is a very basic connection handler. Beyond parsing the HTTP request body and headers, the only HTTP semantics implemented in `HTTPServer` is HTTP/1.1 keep-alive connections. We do not, however, implement chunked encoding, so the request callback must provide a ``Content-Length`` header or implement chunked encoding for HTTP/1.1 requests for the server to run correctly for HTTP/1.1 clients. If the request handler is unable to do this, you can provide the ``no_keep_alive`` argument to the `HTTPServer` constructor, which will ensure the connection is closed on every request no matter what HTTP version the client is using. If ``xheaders`` is ``True``, we support the ``X-Real-Ip`` and ``X-Scheme`` headers, which override the remote IP and HTTP scheme for all requests. These headers are useful when running Tornado behind a reverse proxy or load balancer. `HTTPServer` can serve SSL traffic with Python 2.6+ and OpenSSL. To make this server serve SSL traffic, send the ssl_options dictionary argument with the arguments required for the `ssl.wrap_socket` method, including "certfile" and "keyfile":: HTTPServer(applicaton, ssl_options={ "certfile": os.path.join(data_dir, "mydomain.crt"), "keyfile": os.path.join(data_dir, "mydomain.key"), }) `HTTPServer` initialization follows one of three patterns (the initialization methods are defined on `tornado.netutil.TCPServer`): 1. `~tornado.netutil.TCPServer.listen`: simple single-process:: server = HTTPServer(app) server.listen(8888) IOLoop.instance().start() In many cases, `tornado.web.Application.listen` can be used to avoid the need to explicitly create the `HTTPServer`. 2. `~tornado.netutil.TCPServer.bind`/`~tornado.netutil.TCPServer.start`: simple multi-process:: server = HTTPServer(app) server.bind(8888) server.start(0) # Forks multiple sub-processes IOLoop.instance().start() When using this interface, an `IOLoop` must *not* be passed to the `HTTPServer` constructor. `start` will always start the server on the default singleton `IOLoop`. 3. `~tornado.netutil.TCPServer.add_sockets`: advanced multi-process:: sockets = tornado.netutil.bind_sockets(8888) tornado.process.fork_processes(0) server = HTTPServer(app) server.add_sockets(sockets) IOLoop.instance().start() The `add_sockets` interface is more complicated, but it can be used with `tornado.process.fork_processes` to give you more flexibility in when the fork happens. `add_sockets` can also be used in single-process servers if you want to create your listening sockets in some way other than `tornado.netutil.bind_sockets`. """ def __init__(self, request_callback, no_keep_alive=False, io_loop=None, xheaders=False, ssl_options=None, **kwargs): self.request_callback = request_callback self.no_keep_alive = no_keep_alive self.xheaders = xheaders TCPServer.__init__(self, io_loop=io_loop, ssl_options=ssl_options, **kwargs) def handle_stream(self, stream, address): HTTPConnection(stream, address, self.request_callback, self.no_keep_alive, self.xheaders) class _BadRequestException(Exception): """Exception class for malformed HTTP requests.""" pass class HTTPConnection(object): """Handles a connection to an HTTP client, executing HTTP requests. We parse HTTP headers and bodies, and execute the request callback until the HTTP conection is closed. """ def __init__(self, stream, address, request_callback, no_keep_alive=False, xheaders=False): self.stream = stream self.address = address self.request_callback = request_callback self.no_keep_alive = no_keep_alive self.xheaders = xheaders self._request = None self._request_finished = False # Save stack context here, outside of any request. This keeps # contexts from one request from leaking into the next. self._header_callback = stack_context.wrap(self._on_headers) self.stream.read_until(b("\r\n\r\n"), self._header_callback) self._write_callback = None def write(self, chunk, callback=None): """Writes a chunk of output to the stream.""" assert self._request, "Request closed" if not self.stream.closed(): self._write_callback = stack_context.wrap(callback) self.stream.write(chunk, self._on_write_complete) def finish(self): """Finishes the request.""" assert self._request, "Request closed" self._request_finished = True if not self.stream.writing(): self._finish_request() def _on_write_complete(self): if self._write_callback is not None: callback = self._write_callback self._write_callback = None callback() # _on_write_complete is enqueued on the IOLoop whenever the # IOStream's write buffer becomes empty, but it's possible for # another callback that runs on the IOLoop before it to # simultaneously write more data and finish the request. If # there is still data in the IOStream, a future # _on_write_complete will be responsible for calling # _finish_request. if self._request_finished and not self.stream.writing(): self._finish_request() def _finish_request(self): if self.no_keep_alive: disconnect = True else: connection_header = self._request.headers.get("Connection") if connection_header is not None: connection_header = connection_header.lower() if self._request.supports_http_1_1(): disconnect = connection_header == "close" elif ("Content-Length" in self._request.headers or self._request.method in ("HEAD", "GET")): disconnect = connection_header != "keep-alive" else: disconnect = True self._request = None self._request_finished = False if disconnect: self.stream.close() return self.stream.read_until(b("\r\n\r\n"), self._header_callback) def _on_headers(self, data): try: data = native_str(data.decode('latin1')) eol = data.find("\r\n") start_line = data[:eol] try: method, uri, version = start_line.split(" ") except ValueError: raise _BadRequestException("Malformed HTTP request line") if not version.startswith("HTTP/"): raise _BadRequestException("Malformed HTTP version in HTTP Request-Line") headers = httputil.HTTPHeaders.parse(data[eol:]) # HTTPRequest wants an IP, not a full socket address if getattr(self.stream.socket, 'family', socket.AF_INET) in ( socket.AF_INET, socket.AF_INET6): # Jython 2.5.2 doesn't have the socket.family attribute, # so just assume IP in that case. remote_ip = self.address[0] else: # Unix (or other) socket; fake the remote address remote_ip = '0.0.0.0' self._request = HTTPRequest( connection=self, method=method, uri=uri, version=version, headers=headers, remote_ip=remote_ip) content_length = headers.get("Content-Length") if content_length: content_length = int(content_length) if content_length > self.stream.max_buffer_size: raise _BadRequestException("Content-Length too long") if headers.get("Expect") == "100-continue": self.stream.write(b("HTTP/1.1 100 (Continue)\r\n\r\n")) self.stream.read_bytes(content_length, self._on_request_body) return self.request_callback(self._request) except _BadRequestException, e: logging.info("Malformed HTTP request from %s: %s", self.address[0], e) self.stream.close() return def _on_request_body(self, data): self._request.body = data content_type = self._request.headers.get("Content-Type", "") if self._request.method in ("POST", "PATCH", "PUT"): if content_type.startswith("application/x-www-form-urlencoded"): arguments = parse_qs_bytes(native_str(self._request.body)) for name, values in arguments.iteritems(): values = [v for v in values if v] if values: self._request.arguments.setdefault(name, []).extend( values) elif content_type.startswith("multipart/form-data"): fields = content_type.split(";") for field in fields: k, sep, v = field.strip().partition("=") if k == "boundary" and v: httputil.parse_multipart_form_data( utf8(v), data, self._request.arguments, self._request.files) break else: logging.warning("Invalid multipart/form-data") self.request_callback(self._request) class HTTPRequest(object): """A single HTTP request. All attributes are type `str` unless otherwise noted. .. attribute:: method HTTP request method, e.g. "GET" or "POST" .. attribute:: uri The requested uri. .. attribute:: path The path portion of `uri` .. attribute:: query The query portion of `uri` .. attribute:: version HTTP version specified in request, e.g. "HTTP/1.1" .. attribute:: headers `HTTPHeader` dictionary-like object for request headers. Acts like a case-insensitive dictionary with additional methods for repeated headers. .. attribute:: body Request body, if present, as a byte string. .. attribute:: remote_ip Client's IP address as a string. If `HTTPServer.xheaders` is set, will pass along the real IP address provided by a load balancer in the ``X-Real-Ip`` header .. attribute:: protocol The protocol used, either "http" or "https". If `HTTPServer.xheaders` is set, will pass along the protocol used by a load balancer if reported via an ``X-Scheme`` header. .. attribute:: host The requested hostname, usually taken from the ``Host`` header. .. attribute:: arguments GET/POST arguments are available in the arguments property, which maps arguments names to lists of values (to support multiple values for individual names). Names are of type `str`, while arguments are byte strings. Note that this is different from `RequestHandler.get_argument`, which returns argument values as unicode strings. .. attribute:: files File uploads are available in the files property, which maps file names to lists of :class:`HTTPFile`. .. attribute:: connection An HTTP request is attached to a single HTTP connection, which can be accessed through the "connection" attribute. Since connections are typically kept open in HTTP/1.1, multiple requests can be handled sequentially on a single connection. """ def __init__(self, method, uri, version="HTTP/1.0", headers=None, body=None, remote_ip=None, protocol=None, host=None, files=None, connection=None): self.method = method self.uri = uri self.version = version self.headers = headers or httputil.HTTPHeaders() self.body = body or "" if connection and connection.xheaders: # Squid uses X-Forwarded-For, others use X-Real-Ip self.remote_ip = self.headers.get( "X-Real-Ip", self.headers.get("X-Forwarded-For", remote_ip)) if not self._valid_ip(self.remote_ip): self.remote_ip = remote_ip # AWS uses X-Forwarded-Proto self.protocol = self.headers.get( "X-Scheme", self.headers.get("X-Forwarded-Proto", protocol)) if self.protocol not in ("http", "https"): self.protocol = "http" else: self.remote_ip = remote_ip if protocol: self.protocol = protocol elif connection and isinstance(connection.stream, iostream.SSLIOStream): self.protocol = "https" else: self.protocol = "http" self.host = host or self.headers.get("Host") or "127.0.0.1" self.files = files or {} self.connection = connection self._start_time = time.time() self._finish_time = None self.path, sep, self.query = uri.partition('?') arguments = parse_qs_bytes(self.query) self.arguments = {} for name, values in arguments.iteritems(): values = [v for v in values if v] if values: self.arguments[name] = values def supports_http_1_1(self): """Returns True if this request supports HTTP/1.1 semantics""" return self.version == "HTTP/1.1" @property def cookies(self): """A dictionary of Cookie.Morsel objects.""" if not hasattr(self, "_cookies"): self._cookies = Cookie.SimpleCookie() if "Cookie" in self.headers: try: self._cookies.load( native_str(self.headers["Cookie"])) except Exception: self._cookies = {} return self._cookies def write(self, chunk, callback=None): """Writes the given chunk to the response stream.""" assert isinstance(chunk, bytes_type) self.connection.write(chunk, callback=callback) def finish(self): """Finishes this HTTP request on the open connection.""" self.connection.finish() self._finish_time = time.time() def full_url(self): """Reconstructs the full URL for this request.""" return self.protocol + "://" + self.host + self.uri def request_time(self): """Returns the amount of time it took for this request to execute.""" if self._finish_time is None: return time.time() - self._start_time else: return self._finish_time - self._start_time def get_ssl_certificate(self): """Returns the client's SSL certificate, if any. To use client certificates, the HTTPServer must have been constructed with cert_reqs set in ssl_options, e.g.:: server = HTTPServer(app, ssl_options=dict( certfile="foo.crt", keyfile="foo.key", cert_reqs=ssl.CERT_REQUIRED, ca_certs="cacert.crt")) The return value is a dictionary, see SSLSocket.getpeercert() in the standard library for more details. http://docs.python.org/library/ssl.html#sslsocket-objects """ try: return self.connection.stream.socket.getpeercert() except ssl.SSLError: return None def __repr__(self): attrs = ("protocol", "host", "method", "uri", "version", "remote_ip", "body") args = ", ".join(["%s=%r" % (n, getattr(self, n)) for n in attrs]) return "%s(%s, headers=%s)" % ( self.__class__.__name__, args, dict(self.headers)) def _valid_ip(self, ip): try: res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST) return bool(res) except socket.gaierror, e: if e.args[0] == socket.EAI_NONAME: return False raise return True
mit
phbradley/tcr-dist
tcrdist/parse_cdr3.py
1
4891
import logging logger = logging.getLogger('parse_cdr3.py') from .all_genes import all_genes, gap_character def get_cdr3_and_j_match_counts( organism, ab, qseq, j_gene, min_min_j_matchlen = 3, extended_cdr3 = False ): #fasta = all_fasta[organism] jg = all_genes[organism][j_gene] errors = [] ## qseq starts at CA... assert qseq[0] == 'C' num_genome_j_positions_in_loop = len(jg.cdrs[0].replace(gap_character,''))-2 #num_genome_j_positions_in_loop = all_num_genome_j_positions_in_loop[organism][ab][j_gene] if extended_cdr3: num_genome_j_positions_in_loop += 2 ## up to but not including GXG ## history: was only for alpha aseq = qseq[:] ## starts at the C position ja_gene = j_gene #assert ja_gene in fasta ja_seq = jg.protseq #fasta[ ja_gene ] min_j_matchlen = min_min_j_matchlen+3 while min_j_matchlen >= min_min_j_matchlen: ntrim =0 while ntrim+min_j_matchlen<len(ja_seq) and ja_seq[ntrim:ntrim+min_j_matchlen] not in aseq: ntrim += 1 jatag = ja_seq[ntrim:ntrim+min_j_matchlen] if jatag in aseq: break else: min_j_matchlen -= 1 #print 'min_j_matchlen:',min_j_matchlen,'jatag:',jatag,'ntrim:',ntrim,'ja_seq:',ja_seq,'qseq',qseq if jatag not in aseq: logger.error('whoah %s %s %s',ab,aseq,ja_seq ) errors.append( 'j{}tag_not_in_aseq'.format(ab) ) return '-',[100,0],errors elif ja_seq.count( jatag ) != 1: logger.error( 'whoah2 %s %s %s',ab,aseq,ja_seq ) errors.append( 'multiple_j{}tag_in_jseq'.format(ab) ) return '-',[100,0],errors else: pos = aseq.find( jatag ) looplen = pos - ntrim + num_genome_j_positions_in_loop if not extended_cdr3: aseq = aseq[3:] looplen -= 3 ## dont count CAX if len(aseq)<looplen: logger.error('short %s %s %s',ab,aseq,ja_seq ) errors.append( ab+'seq_too_short' ) return '-',[100,0],errors cdrseq = aseq[:looplen ] ## now count mismatches in the J gene, beyond the cdrseq j_seq = jg.protseq #fasta[ j_gene ] ## not sure why we do this again (old legacy code) if qseq.count( cdrseq ) > 1: logger.error('multiple cdrseq occurrences %s %s'%(qseq,cdrseq)) errors.append('multiple_cdrseq_occ') return '-',[100,0],errors assert qseq.count(cdrseq) == 1 start_counting_qseq = qseq.find(cdrseq)+len(cdrseq) start_counting_jseq = num_genome_j_positions_in_loop j_match_counts = [0,0] #assert extended_cdr3 ## otherwise I think this count is not right? #print 'here',start_counting_qseq,start_counting_jseq,len(qseq) for qpos in range( start_counting_qseq, len(qseq)): jpos = start_counting_jseq + (qpos-start_counting_qseq) #print 'here',qpos,jpos if jpos>= len(j_seq): break if qseq[qpos] == j_seq[jpos]: j_match_counts[1] += 1 else: j_match_counts[0] += 1 return cdrseq, j_match_counts,errors def parse_cdr3( organism, ab, qseq, v_gene, j_gene, q2v_align, extended_cdr3 = False ): ## v_align is a mapping from 0-indexed qseq positions to 0-indexed v_gene protseq positions #fasta = all_fasta[ organism ] #align_fasta = all_align_fasta[ organism ] vg = all_genes[organism][v_gene] errors = [] ## what is the C position in this v gene? v_seq = vg.protseq #fasta[ v_gene ] v_alseq = vg.alseq #align_fasta[ v_gene ] assert v_seq == v_alseq.replace(gap_character,'') alseq_cpos = vg.cdr_columns[-1][0] - 1 ## now 0-indexed #alseq_cpos = alseq_C_pos[organism][ab] - 1 ## now 0-indexed numgaps = v_alseq[:alseq_cpos].count(gap_character) cpos = alseq_cpos - numgaps ## 0-indexed cpos_match = -1 v_match_counts = [0,0] qseq_len = len(qseq) for (qpos,vpos) in sorted( q2v_align.iteritems() ): #print 'q2v-align:',qpos, vpos, cpos if qpos == len(qseq): continue ## from a partial codon at the end if vpos == cpos: cpos_match = qpos elif vpos <= cpos: ## only count v mismatches here if qseq[qpos] == v_seq[vpos]: v_match_counts[1] += 1 else: v_match_counts[0] += 1 if cpos_match<0 or qseq[ cpos_match ] != 'C': ## problemo logger.error('failed to find blast match to C position') errors.append('no_V{}_Cpos_blastmatch'.format(ab)) return '-',[100,0],[100,0],errors cdrseq, j_match_counts, other_errors = get_cdr3_and_j_match_counts( organism, ab, qseq[ cpos_match: ], j_gene, extended_cdr3 = extended_cdr3 ) return cdrseq, v_match_counts, j_match_counts, errors+other_errors
mit
3quarterstack/simple_blog
django/db/models/fields/files.py
111
15938
import datetime import os from django import forms from django.db.models.fields import Field from django.core.files.base import File from django.core.files.storage import default_storage from django.core.files.images import ImageFile from django.db.models import signals from django.utils.encoding import force_str, force_text from django.utils import six from django.utils.translation import ugettext_lazy as _ class FieldFile(File): def __init__(self, instance, field, name): super(FieldFile, self).__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be simple strings. # By overriding the == operator, it can remain backwards compatibility. if hasattr(other, 'name'): return self.name == other.name return self.name == other def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.name) # The standard File contains most of the necessary properties, but # FieldFiles can be instantiated without a name, so that needs to # be checked for here. def _require_file(self): if not self: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) def _get_file(self): self._require_file() if not hasattr(self, '_file') or self._file is None: self._file = self.storage.open(self.name, 'rb') return self._file def _set_file(self, file): self._file = file def _del_file(self): del self._file file = property(_get_file, _set_file, _del_file) def _get_path(self): self._require_file() return self.storage.path(self.name) path = property(_get_path) def _get_url(self): self._require_file() return self.storage.url(self.name) url = property(_get_url) def _get_size(self): self._require_file() if not self._committed: return self.file.size return self.storage.size(self.name) size = property(_get_size) def open(self, mode='rb'): self._require_file() self.file.open(mode) # open() doesn't alter the file's contents, but it does reset the pointer open.alters_data = True # In addition to the standard File API, FieldFiles have extra methods # to further manipulate the underlying file, as well as update the # associated model instance. def save(self, name, content, save=True): name = self.field.generate_filename(self.instance, name) self.name = self.storage.save(name, content) setattr(self.instance, self.field.name, self.name) # Update the filesize cache self._size = content.size self._committed = True # Save the object because it has changed, unless save is False if save: self.instance.save() save.alters_data = True def delete(self, save=True): # Only close the file if it's already open, which we know by the # presence of self._file if hasattr(self, '_file'): self.close() del self.file self.storage.delete(self.name) self.name = None setattr(self.instance, self.field.name, self.name) # Delete the filesize cache if hasattr(self, '_size'): del self._size self._committed = False if save: self.instance.save() delete.alters_data = True def _get_closed(self): file = getattr(self, '_file', None) return file is None or file.closed closed = property(_get_closed) def close(self): file = getattr(self, '_file', None) if file is not None: file.close() def __getstate__(self): # FieldFile needs access to its associated model field and an instance # it's attached to in order to work properly, but the only necessary # data to be pickled is the file's name itself. Everything else will # be restored later, by FileDescriptor below. return {'name': self.name, 'closed': False, '_committed': True, '_file': None} class FileDescriptor(object): """ The descriptor for the file attribute on the model instance. Returns a FieldFile when accessed so you can do stuff like:: >>> instance.file.size Assigns a file object on assignment so you can do:: >>> instance.file = File(...) """ def __init__(self, field): self.field = field def __get__(self, instance=None, owner=None): if instance is None: raise AttributeError( "The '%s' attribute can only be accessed from %s instances." % (self.field.name, owner.__name__)) # This is slightly complicated, so worth an explanation. # instance.file`needs to ultimately return some instance of `File`, # probably a subclass. Additionally, this returned object needs to have # the FieldFile API so that users can easily do things like # instance.file.path and have that delegated to the file storage engine. # Easy enough if we're strict about assignment in __set__, but if you # peek below you can see that we're not. So depending on the current # value of the field we have to dynamically construct some sort of # "thing" to return. # The instance dict contains whatever was originally assigned # in __set__. file = instance.__dict__[self.field.name] # If this value is a string (instance.file = "path/to/file") or None # then we simply wrap it with the appropriate attribute class according # to the file field. [This is FieldFile for FileFields and # ImageFieldFile for ImageFields; it's also conceivable that user # subclasses might also want to subclass the attribute class]. This # object understands how to convert a path to a file, and also how to # handle None. if isinstance(file, six.string_types) or file is None: attr = self.field.attr_class(instance, self.field, file) instance.__dict__[self.field.name] = attr # Other types of files may be assigned as well, but they need to have # the FieldFile interface added to the. Thus, we wrap any other type of # File inside a FieldFile (well, the field's attr_class, which is # usually FieldFile). elif isinstance(file, File) and not isinstance(file, FieldFile): file_copy = self.field.attr_class(instance, self.field, file.name) file_copy.file = file file_copy._committed = False instance.__dict__[self.field.name] = file_copy # Finally, because of the (some would say boneheaded) way pickle works, # the underlying FieldFile might not actually itself have an associated # file. So we need to reset the details of the FieldFile in those cases. elif isinstance(file, FieldFile) and not hasattr(file, 'field'): file.instance = instance file.field = self.field file.storage = self.field.storage # That was fun, wasn't it? return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value class FileField(Field): # The class to wrap instance attributes in. Accessing the file object off # the instance will always return an instance of attr_class. attr_class = FieldFile # The descriptor to use for accessing the attribute off of the class. descriptor_class = FileDescriptor description = _("File") def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs): for arg in ('primary_key', 'unique'): if arg in kwargs: raise TypeError("'%s' is not a valid argument for %s." % (arg, self.__class__)) self.storage = storage or default_storage self.upload_to = upload_to if callable(upload_to): self.generate_filename = upload_to kwargs['max_length'] = kwargs.get('max_length', 100) super(FileField, self).__init__(verbose_name, name, **kwargs) def get_internal_type(self): return "FileField" def get_prep_lookup(self, lookup_type, value): if hasattr(value, 'name'): value = value.name return super(FileField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): "Returns field's value prepared for saving into a database." # Need to convert File objects provided via a form to unicode for database insertion if value is None: return None return six.text_type(value) def pre_save(self, model_instance, add): "Returns field's value just before saving." file = super(FileField, self).pre_save(model_instance, add) if file and not file._committed: # Commit the file to storage prior to saving the model file.save(file.name, file, save=False) return file def contribute_to_class(self, cls, name): super(FileField, self).contribute_to_class(cls, name) setattr(cls, self.name, self.descriptor_class(self)) def get_directory_name(self): return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to)))) def get_filename(self, filename): return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename))) def generate_filename(self, instance, filename): return os.path.join(self.get_directory_name(), self.get_filename(filename)) def save_form_data(self, instance, data): # Important: None means "no change", other false value means "clear" # This subtle distinction (rather than a more explicit marker) is # needed because we need to consume values that are also sane for a # regular (non Model-) Form to find in its cleaned_data dictionary. if data is not None: # This value will be converted to unicode and stored in the # database, so leaving False as-is is not acceptable. if not data: data = '' setattr(instance, self.name, data) def formfield(self, **kwargs): defaults = {'form_class': forms.FileField, 'max_length': self.max_length} # If a file has been provided previously, then the form doesn't require # that a new file is provided this time. # The code to mark the form field as not required is used by # form_for_instance, but can probably be removed once form_for_instance # is gone. ModelForm uses a different method to check for an existing file. if 'initial' in kwargs: defaults['required'] = False defaults.update(kwargs) return super(FileField, self).formfield(**defaults) class ImageFileDescriptor(FileDescriptor): """ Just like the FileDescriptor, but for ImageFields. The only difference is assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.name) super(ImageFileDescriptor, self).__set__(instance, value) # To prevent recalculating image dimensions when we are instantiating # an object from the database (bug #11084), only update dimensions if # the field had a value before this assignment. Since the default # value for FileField subclasses is an instance of field.attr_class, # previous_file will only be None when we are called from # Model.__init__(). The ImageField.update_dimension_fields method # hooked up to the post_init signal handles the Model.__init__() cases. # Assignment happening outside of Model.__init__() will trigger the # update right here. if previous_file is not None: self.field.update_dimension_fields(instance, force=True) class ImageFieldFile(ImageFile, FieldFile): def delete(self, save=True): # Clear the image dimensions cache if hasattr(self, '_dimensions_cache'): del self._dimensions_cache super(ImageFieldFile, self).delete(save) class ImageField(FileField): attr_class = ImageFieldFile descriptor_class = ImageFileDescriptor description = _("Image") def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): self.width_field, self.height_field = width_field, height_field super(ImageField, self).__init__(verbose_name, name, **kwargs) def contribute_to_class(self, cls, name): super(ImageField, self).contribute_to_class(cls, name) # Attach update_dimension_fields so that dimension fields declared # after their corresponding image field don't stay cleared by # Model.__init__, see bug #11196. signals.post_init.connect(self.update_dimension_fields, sender=cls) def update_dimension_fields(self, instance, force=False, *args, **kwargs): """ Updates field's width and height fields, if defined. This method is hooked up to model's post_init signal to update dimensions after instantiating a model instance. However, dimensions won't be updated if the dimensions fields are already populated. This avoids unnecessary recalculation when loading an object from the database. Dimensions can be forced to update with force=True, which is how ImageFileDescriptor.__set__ calls this method. """ # Nothing to update if the field doesn't have have dimension fields. has_dimension_fields = self.width_field or self.height_field if not has_dimension_fields: return # getattr will call the ImageFileDescriptor's __get__ method, which # coerces the assigned value into an instance of self.attr_class # (ImageFieldFile in this case). file = getattr(instance, self.attname) # Nothing to update if we have no file and not being forced to update. if not file and not force: return dimension_fields_filled = not( (self.width_field and not getattr(instance, self.width_field)) or (self.height_field and not getattr(instance, self.height_field)) ) # When both dimension fields have values, we are most likely loading # data from the database or updating an image field that already had # an image stored. In the first case, we don't want to update the # dimension fields because we are already getting their values from the # database. In the second case, we do want to update the dimensions # fields and will skip this return because force will be True since we # were called from ImageFileDescriptor.__set__. if dimension_fields_filled and not force: return # file should be an instance of ImageFieldFile or should be None. if file: width = file.width height = file.height else: # No file, so clear dimensions fields. width = None height = None # Update the width and height fields. if self.width_field: setattr(instance, self.width_field, width) if self.height_field: setattr(instance, self.height_field, height) def formfield(self, **kwargs): defaults = {'form_class': forms.ImageField} defaults.update(kwargs) return super(ImageField, self).formfield(**defaults)
mit
michael-dev2rights/ansible
lib/ansible/modules/cloud/amazon/s3_website.py
26
10810
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: s3_website short_description: Configure an s3 bucket as a website description: - Configure an s3 bucket as a website version_added: "2.2" author: Rob White (@wimnat) options: name: description: - "Name of the s3 bucket" required: true default: null error_key: description: - "The object key name to use when a 4XX class error occurs. To remove an error key, set to None." required: false default: null redirect_all_requests: description: - "Describes the redirect behavior for every request to this s3 bucket website endpoint" required: false default: null region: description: - > AWS region to create the bucket in. If not set then the value of the AWS_REGION and EC2_REGION environment variables are checked, followed by the aws_region and ec2_region settings in the Boto config file. If none of those are set the region defaults to the S3 Location: US Standard. required: false default: null state: description: - "Add or remove s3 website configuration" required: false default: present choices: [ 'present', 'absent' ] suffix: description: - > Suffix that is appended to a request that is for a directory on the website endpoint (e.g. if the suffix is index.html and you make a request to samplebucket/images/ the data that is returned will be for the object with the key name images/index.html). The suffix must not include a slash character. required: false default: index.html extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Configure an s3 bucket to redirect all requests to example.com - s3_website: name: mybucket.com redirect_all_requests: example.com state: present # Remove website configuration from an s3 bucket - s3_website: name: mybucket.com state: absent # Configure an s3 bucket as a website with index and error pages - s3_website: name: mybucket.com suffix: home.htm error_key: errors/404.htm state: present ''' RETURN = ''' index_document: description: index document type: complex returned: always contains: suffix: description: suffix that is appended to a request that is for a directory on the website endpoint returned: success type: string sample: index.html error_document: description: error document type: complex returned: always contains: key: description: object key name to use when a 4XX class error occurs returned: when error_document parameter set type: string sample: error.html redirect_all_requests_to: description: where to redirect requests type: complex returned: always contains: host_name: description: name of the host where requests will be redirected. returned: when redirect all requests parameter set type: string sample: ansible.com routing_rules: description: routing rules type: complex returned: always contains: routing_rule: host_name: description: name of the host where requests will be redirected. returned: when host name set as part of redirect rule type: string sample: ansible.com condition: key_prefix_equals: description: object key name prefix when the redirect is applied. For example, to redirect requests for ExamplePage.html, the key prefix will be ExamplePage.html returned: when routing rule present type: string sample: docs/ redirect: replace_key_prefix_with: description: object key prefix to use in the redirect request returned: when routing rule present type: string sample: documents/ ''' import time try: import boto3 from botocore.exceptions import ClientError, ParamValidationError HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import (HAS_BOTO3, boto3_conn, camel_dict_to_snake_dict, ec2_argument_spec, get_aws_connection_info) def _create_redirect_dict(url): redirect_dict = {} url_split = url.split(':') # Did we split anything? if len(url_split) == 2: redirect_dict[u'Protocol'] = url_split[0] redirect_dict[u'HostName'] = url_split[1].replace('//', '') elif len(url_split) == 1: redirect_dict[u'HostName'] = url_split[0] else: raise ValueError('Redirect URL appears invalid') return redirect_dict def _create_website_configuration(suffix, error_key, redirect_all_requests): website_configuration = {} if error_key is not None: website_configuration['ErrorDocument'] = { 'Key': error_key } if suffix is not None: website_configuration['IndexDocument'] = { 'Suffix': suffix } if redirect_all_requests is not None: website_configuration['RedirectAllRequestsTo'] = _create_redirect_dict(redirect_all_requests) return website_configuration def enable_or_update_bucket_as_website(client_connection, resource_connection, module): bucket_name = module.params.get("name") redirect_all_requests = module.params.get("redirect_all_requests") # If redirect_all_requests is set then don't use the default suffix that has been set if redirect_all_requests is not None: suffix = None else: suffix = module.params.get("suffix") error_key = module.params.get("error_key") changed = False try: bucket_website = resource_connection.BucketWebsite(bucket_name) except ClientError as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) try: website_config = client_connection.get_bucket_website(Bucket=bucket_name) except ClientError as e: if e.response['Error']['Code'] == 'NoSuchWebsiteConfiguration': website_config = None else: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) if website_config is None: try: bucket_website.put(WebsiteConfiguration=_create_website_configuration(suffix, error_key, redirect_all_requests)) changed = True except (ClientError, ParamValidationError) as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) except ValueError as e: module.fail_json(msg=str(e)) else: try: if (suffix is not None and website_config['IndexDocument']['Suffix'] != suffix) or \ (error_key is not None and website_config['ErrorDocument']['Key'] != error_key) or \ (redirect_all_requests is not None and website_config['RedirectAllRequestsTo'] != _create_redirect_dict(redirect_all_requests)): try: bucket_website.put(WebsiteConfiguration=_create_website_configuration(suffix, error_key, redirect_all_requests)) changed = True except (ClientError, ParamValidationError) as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) except KeyError as e: try: bucket_website.put(WebsiteConfiguration=_create_website_configuration(suffix, error_key, redirect_all_requests)) changed = True except (ClientError, ParamValidationError) as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) except ValueError as e: module.fail_json(msg=str(e)) # Wait 5 secs before getting the website_config again to give it time to update time.sleep(5) website_config = client_connection.get_bucket_website(Bucket=bucket_name) module.exit_json(changed=changed, **camel_dict_to_snake_dict(website_config)) def disable_bucket_as_website(client_connection, module): changed = False bucket_name = module.params.get("name") try: client_connection.get_bucket_website(Bucket=bucket_name) except ClientError as e: if e.response['Error']['Code'] == 'NoSuchWebsiteConfiguration': module.exit_json(changed=changed) else: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) try: client_connection.delete_bucket_website(Bucket=bucket_name) changed = True except ClientError as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) module.exit_json(changed=changed) def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( name=dict(type='str', required=True), state=dict(type='str', required=True, choices=['present', 'absent']), suffix=dict(type='str', required=False, default='index.html'), error_key=dict(type='str', required=False), redirect_all_requests=dict(type='str', required=False) ) ) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive = [ ['redirect_all_requests', 'suffix'], ['redirect_all_requests', 'error_key'] ]) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if region: client_connection = boto3_conn(module, conn_type='client', resource='s3', region=region, endpoint=ec2_url, **aws_connect_params) resource_connection = boto3_conn(module, conn_type='resource', resource='s3', region=region, endpoint=ec2_url, **aws_connect_params) else: module.fail_json(msg="region must be specified") state = module.params.get("state") if state == 'present': enable_or_update_bucket_as_website(client_connection, resource_connection, module) elif state == 'absent': disable_bucket_as_website(client_connection, module) if __name__ == '__main__': main()
gpl-3.0
QISKit/qiskit-sdk-py
test/python/test_qasm_parser.py
1
2809
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test for the QASM parser""" import unittest import ply from qiskit.qasm import Qasm, QasmError from qiskit.qasm.node.node import Node from qiskit.test import QiskitTestCase, Path def parse(file_path, prec=15): """ Simple helper - file_path: Path to the OpenQASM file - prec: Precision for the returned string """ qasm = Qasm(file_path) return qasm.parse().qasm(prec) class TestParser(QiskitTestCase): """QasmParser""" def setUp(self): self.qasm_file_path = self._get_resource_path('example.qasm', Path.QASMS) self.qasm_file_path_fail = self._get_resource_path( 'example_fail.qasm', Path.QASMS) self.qasm_file_path_if = self._get_resource_path( 'example_if.qasm', Path.QASMS) def test_parser(self): """should return a correct response for a valid circuit.""" res = parse(self.qasm_file_path) self.log.info(res) # TODO: For now only some basic checks. self.assertEqual(len(res), 1563) self.assertEqual(res[:12], "OPENQASM 2.0") self.assertEqual(res[14:41], "gate u3(theta,phi,lambda) q") self.assertEqual(res[1547:1562], "measure r -> d;") def test_parser_fail(self): """should fail a for a not valid circuit.""" self.assertRaisesRegex(QasmError, "Perhaps there is a missing", parse, file_path=self.qasm_file_path_fail) def test_all_valid_nodes(self): """Test that the tree contains only Node subclasses.""" def inspect(node): """Inspect node children.""" for child in node.children: self.assertTrue(isinstance(child, Node)) inspect(child) # Test the canonical example file. qasm = Qasm(self.qasm_file_path) res = qasm.parse() inspect(res) # Test a file containing if instructions. qasm_if = Qasm(self.qasm_file_path_if) res_if = qasm_if.parse() inspect(res_if) def test_get_tokens(self): """Test whether we get only valid tokens.""" qasm = Qasm(self.qasm_file_path) for token in qasm.get_tokens(): self.assertTrue(isinstance(token, ply.lex.LexToken)) if __name__ == '__main__': unittest.main()
apache-2.0
zxwing/ansible
lib/ansible/runner/lookup_plugins/redis_kv.py
176
2469
# (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com> # # 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 <http://www.gnu.org/licenses/>. from ansible import utils, errors import os HAVE_REDIS=False try: import redis # https://github.com/andymccurdy/redis-py/ HAVE_REDIS=True except ImportError: pass import re # ============================================================== # REDISGET: Obtain value from a GET on a Redis key. Terms # expected: 0 = URL, 1 = Key # URL may be empty, in which case redis://localhost:6379 assumed # -------------------------------------------------------------- class LookupModule(object): def __init__(self, basedir=None, **kwargs): self.basedir = basedir if HAVE_REDIS == False: raise errors.AnsibleError("Can't LOOKUP(redis_kv): module redis is not installed") def run(self, terms, inject=None, **kwargs): terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject) ret = [] for term in terms: (url,key) = term.split(',') if url == "": url = 'redis://localhost:6379' # urlsplit on Python 2.6.1 is broken. Hmm. Probably also the reason # Redis' from_url() doesn't work here. p = '(?P<scheme>[^:]+)://?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' try: m = re.search(p, url) host = m.group('host') port = int(m.group('port')) except AttributeError: raise errors.AnsibleError("Bad URI in redis lookup") try: conn = redis.Redis(host=host, port=port) res = conn.get(key) if res is None: res = "" ret.append(res) except: ret.append("") # connection failed or key not found return ret
gpl-3.0
subutai/pycept
tests/unit/client_test.py
3
3542
import pycept import unittest from mock import patch, MagicMock import httpretty class ClientTestCase(unittest.TestCase): @httpretty.activate @patch('os.path.exists', return_value=False) @patch('os.makedirs') @patch('json.dump') def testTokenizeEmptyString(self, mockExists, mockMakedirs, mockDump): client = pycept.Cept("apikey") httpretty.register_uri( httpretty.POST, "http://numenta.cortical.io:80/rest/text/tokenize?retinaName=eng_syn", body='[]', ) open_name = '%s.open' % __name__ with patch(open_name, create=True) as mock_open: mock_open.return_value = MagicMock(spec=file) result = client.tokenize("") self.assertListEqual(result, []) @httpretty.activate @patch('os.path.exists', return_value=False) @patch('os.makedirs') @patch('json.dump') def testTokenizeSingleSentence(self, mockExists, mockMakedirs, mockDump): client = pycept.Cept("apikey") httpretty.register_uri( httpretty.POST, "http://numenta.cortical.io:80/rest/text/tokenize?retinaName=eng_syn", body='["cow,jumped,moon"]', ) open_name = '%s.open' % __name__ with patch(open_name, create=True) as mock_open: mock_open.return_value = MagicMock(spec=file) result = client.tokenize("The cow jumped over the moon.") self.assertEqual(len(result), 1, "Wrong number of sentences in results") self.assertListEqual(result[0], ["cow", "jumped", "moon"]) @httpretty.activate @patch('os.path.exists', return_value=False) @patch('os.makedirs') @patch('json.dump') def testTokenizeMultipleSentences(self, mockExists, mockMakedirs, mockDump): client = pycept.Cept("apikey") httpretty.register_uri( httpretty.POST, "http://numenta.cortical.io:80/rest/text/tokenize?retinaName=eng_syn", body='["cow,jumped,moon","sun,came"]', ) open_name = '%s.open' % __name__ with patch(open_name, create=True) as mock_open: mock_open.return_value = MagicMock(spec=file) result = client.tokenize( "The cow jumped over the moon. And then the sun came up.") self.assertEqual(len(result), 2, "Wrong number of sentences in results") self.assertListEqual(result[0], ["cow", "jumped", "moon"]) self.assertListEqual(result[1], ["sun", "came"]) def testTinyEmptyBitMapToSdr(self): client = pycept.Cept("apikey") result = client._bitmapToSdr({ 'width': 1, 'height': 1, 'positions': [] }) self.assertEqual(result, "0") def testTinyFullBitMapToSdr(self): client = pycept.Cept("apikey") result = client._bitmapToSdr({ 'width': 1, 'height': 1, 'positions': [0] }) self.assertEqual(result, "1") def testSmallEmptyBitMapToSdr(self): client = pycept.Cept("apikey") result = client._bitmapToSdr({ 'width': 4, 'height': 4, 'positions': [] }) self.assertEqual(result, "0000000000000000") def testSmallFullBitMapToSdr(self): client = pycept.Cept("apikey") result = client._bitmapToSdr({ 'width': 4, 'height': 4, 'positions': [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] }) self.assertEqual(result, "1111111111111111") def testSmallPartialBitMapToSdr(self): client = pycept.Cept("apikey") result = client._bitmapToSdr({ 'width': 4, 'height': 4, 'positions': [2,3,6,7,10,11,14,15] }) self.assertEqual(result, "0011001100110011") if __name__ == "__main__": unittest.main()
mit
nitinitprof/odoo
addons/analytic/__init__.py
424
1072
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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 <http://www.gnu.org/licenses/>. # ############################################################################## import analytic # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
nzavagli/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/python-dateutil-2.4.2/dateutil/relativedelta.py
104
18172
# -*- coding: utf-8 -*- import datetime import calendar from six import integer_types __all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] class weekday(object): __slots__ = ["weekday", "n"] def __init__(self, weekday, n=None): self.weekday = weekday self.n = n def __call__(self, n): if n == self.n: return self else: return self.__class__(self.weekday, n) def __eq__(self, other): try: if self.weekday != other.weekday or self.n != other.n: return False except AttributeError: return False return True def __repr__(self): s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] if not self.n: return s else: return "%s(%+d)" % (s, self.n) MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)]) class relativedelta(object): """ The relativedelta type is based on the specification of the excellent work done by M.-A. Lemburg in his `mx.DateTime <http://www.egenix.com/files/python/mxDateTime.html>`_ extension. However, notice that this type does *NOT* implement the same algorithm as his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. There are two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes:: relativedelta(datetime1, datetime2) The second one is passing it any number of the following keyword arguments:: relativedelta(arg1=x,arg2=y,arg3=z...) year, month, day, hour, minute, second, microsecond: Absolute information (argument is singular); adding or subtracting a relativedelta with absolute information does not perform an aritmetic operation, but rather REPLACES the corresponding value in the original datetime with the value(s) in relativedelta. years, months, weeks, days, hours, minutes, seconds, microseconds: Relative information, may be negative (argument is plural); adding or subtracting a relativedelta with relative information performs the corresponding aritmetic operation on the original datetime value with the information in the relativedelta. weekday: One of the weekday instances (MO, TU, etc). These instances may receive a parameter N, specifying the Nth weekday, which could be positive or negative (like MO(+1) or MO(-2). Not specifying it is the same as specifying +1. You can also use an integer, where 0=MO. leapdays: Will add given days to the date found, if year is a leap year, and the date found is post 28 of february. yearday, nlyearday: Set the yearday or the non-leap year day (jump leap days). These are converted to day/month/leapdays information. Here is the behavior of operations with relativedelta: 1. Calculate the absolute year, using the 'year' argument, or the original datetime year, if the argument is not present. 2. Add the relative 'years' argument to the absolute year. 3. Do steps 1 and 2 for month/months. 4. Calculate the absolute day, using the 'day' argument, or the original datetime day, if the argument is not present. Then, subtract from the day until it fits in the year and month found after their operations. 5. Add the relative 'days' argument to the absolute day. Notice that the 'weeks' argument is multiplied by 7 and added to 'days'. 6. Do steps 1 and 2 for hour/hours, minute/minutes, second/seconds, microsecond/microseconds. 7. If the 'weekday' argument is present, calculate the weekday, with the given (wday, nth) tuple. wday is the index of the weekday (0-6, 0=Mon), and nth is the number of weeks to add forward or backward, depending on its signal. Notice that if the calculated date is already Monday, for example, using (0, 1) or (0, -1) won't change the day. """ def __init__(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None): if dt1 and dt2: # datetime is a subclass of date. So both must be date if not (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date)): raise TypeError("relativedelta only diffs datetime/date") # We allow two dates, or two datetimes, so we coerce them to be # of the same type if (isinstance(dt1, datetime.datetime) != isinstance(dt2, datetime.datetime)): if not isinstance(dt1, datetime.datetime): dt1 = datetime.datetime.fromordinal(dt1.toordinal()) elif not isinstance(dt2, datetime.datetime): dt2 = datetime.datetime.fromordinal(dt2.toordinal()) self.years = 0 self.months = 0 self.days = 0 self.leapdays = 0 self.hours = 0 self.minutes = 0 self.seconds = 0 self.microseconds = 0 self.year = None self.month = None self.day = None self.weekday = None self.hour = None self.minute = None self.second = None self.microsecond = None self._has_time = 0 months = (dt1.year*12+dt1.month)-(dt2.year*12+dt2.month) self._set_months(months) dtm = self.__radd__(dt2) if dt1 < dt2: while dt1 > dtm: months += 1 self._set_months(months) dtm = self.__radd__(dt2) else: while dt1 < dtm: months -= 1 self._set_months(months) dtm = self.__radd__(dt2) delta = dt1 - dtm self.seconds = delta.seconds+delta.days*86400 self.microseconds = delta.microseconds else: self.years = years self.months = months self.days = days+weeks*7 self.leapdays = leapdays self.hours = hours self.minutes = minutes self.seconds = seconds self.microseconds = microseconds self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.microsecond = microsecond if isinstance(weekday, integer_types): self.weekday = weekdays[weekday] else: self.weekday = weekday yday = 0 if nlyearday: yday = nlyearday elif yearday: yday = yearday if yearday > 59: self.leapdays = -1 if yday: ydayidx = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 366] for idx, ydays in enumerate(ydayidx): if yday <= ydays: self.month = idx+1 if idx == 0: self.day = yday else: self.day = yday-ydayidx[idx-1] break else: raise ValueError("invalid year day (%d)" % yday) self._fix() def _fix(self): if abs(self.microseconds) > 999999: s = self.microseconds//abs(self.microseconds) div, mod = divmod(self.microseconds*s, 1000000) self.microseconds = mod*s self.seconds += div*s if abs(self.seconds) > 59: s = self.seconds//abs(self.seconds) div, mod = divmod(self.seconds*s, 60) self.seconds = mod*s self.minutes += div*s if abs(self.minutes) > 59: s = self.minutes//abs(self.minutes) div, mod = divmod(self.minutes*s, 60) self.minutes = mod*s self.hours += div*s if abs(self.hours) > 23: s = self.hours//abs(self.hours) div, mod = divmod(self.hours*s, 24) self.hours = mod*s self.days += div*s if abs(self.months) > 11: s = self.months//abs(self.months) div, mod = divmod(self.months*s, 12) self.months = mod*s self.years += div*s if (self.hours or self.minutes or self.seconds or self.microseconds or self.hour is not None or self.minute is not None or self.second is not None or self.microsecond is not None): self._has_time = 1 else: self._has_time = 0 def _set_months(self, months): self.months = months if abs(self.months) > 11: s = self.months//abs(self.months) div, mod = divmod(self.months*s, 12) self.months = mod*s self.years = div*s else: self.years = 0 def __add__(self, other): if isinstance(other, relativedelta): return relativedelta(years=other.years+self.years, months=other.months+self.months, days=other.days+self.days, hours=other.hours+self.hours, minutes=other.minutes+self.minutes, seconds=other.seconds+self.seconds, microseconds=(other.microseconds + self.microseconds), leapdays=other.leapdays or self.leapdays, year=other.year or self.year, month=other.month or self.month, day=other.day or self.day, weekday=other.weekday or self.weekday, hour=other.hour or self.hour, minute=other.minute or self.minute, second=other.second or self.second, microsecond=(other.microsecond or self.microsecond)) if not isinstance(other, datetime.date): raise TypeError("unsupported type for add operation") elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth)-1)*7 if nth > 0: jumpdays += (7-ret.weekday()+weekday) % 7 else: jumpdays += (ret.weekday()-weekday) % 7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): return self.__neg__().__radd__(other) def __sub__(self, other): if not isinstance(other, relativedelta): raise TypeError("unsupported type for sub operation") return relativedelta(years=self.years-other.years, months=self.months-other.months, days=self.days-other.days, hours=self.hours-other.hours, minutes=self.minutes-other.minutes, seconds=self.seconds-other.seconds, microseconds=self.microseconds-other.microseconds, leapdays=self.leapdays or other.leapdays, year=self.year or other.year, month=self.month or other.month, day=self.day or other.day, weekday=self.weekday or other.weekday, hour=self.hour or other.hour, minute=self.minute or other.minute, second=self.second or other.second, microsecond=self.microsecond or other.microsecond) def __neg__(self): return relativedelta(years=-self.years, months=-self.months, days=-self.days, hours=-self.hours, minutes=-self.minutes, seconds=-self.seconds, microseconds=-self.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __bool__(self): return not (not self.years and not self.months and not self.days and not self.hours and not self.minutes and not self.seconds and not self.microseconds and not self.leapdays and self.year is None and self.month is None and self.day is None and self.weekday is None and self.hour is None and self.minute is None and self.second is None and self.microsecond is None) # Compatibility with Python 2.x __nonzero__ = __bool__ def __mul__(self, other): f = float(other) return relativedelta(years=int(self.years*f), months=int(self.months*f), days=int(self.days*f), hours=int(self.hours*f), minutes=int(self.minutes*f), seconds=int(self.seconds*f), microseconds=int(self.microseconds*f), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) __rmul__ = __mul__ def __eq__(self, other): if not isinstance(other, relativedelta): return False if self.weekday or other.weekday: if not self.weekday or not other.weekday: return False if self.weekday.weekday != other.weekday.weekday: return False n1, n2 = self.weekday.n, other.weekday.n if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): return False return (self.years == other.years and self.months == other.months and self.days == other.days and self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds and self.leapdays == other.leapdays and self.year == other.year and self.month == other.month and self.day == other.day and self.hour == other.hour and self.minute == other.minute and self.second == other.second and self.microsecond == other.microsecond) def __ne__(self, other): return not self.__eq__(other) def __div__(self, other): return self.__mul__(1/float(other)) __truediv__ = __div__ def __repr__(self): l = [] for attr in ["years", "months", "days", "leapdays", "hours", "minutes", "seconds", "microseconds"]: value = getattr(self, attr) if value: l.append("%s=%+d" % (attr, value)) for attr in ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) # vim:ts=4:sw=4:et
mit
Leoniela/nipype
nipype/interfaces/mipav/tests/test_auto_JistIntensityMp2rageMasking.py
9
1896
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.mipav.developer import JistIntensityMp2rageMasking def test_JistIntensityMp2rageMasking_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), inBackground=dict(argstr='--inBackground %s', ), inMasking=dict(argstr='--inMasking %s', ), inQuantitative=dict(argstr='--inQuantitative %s', ), inSecond=dict(argstr='--inSecond %s', ), inSkip=dict(argstr='--inSkip %s', ), inT1weighted=dict(argstr='--inT1weighted %s', ), null=dict(argstr='--null %s', ), outMasked=dict(argstr='--outMasked %s', hash_files=False, ), outMasked2=dict(argstr='--outMasked2 %s', hash_files=False, ), outSignal=dict(argstr='--outSignal %s', hash_files=False, ), outSignal2=dict(argstr='--outSignal2 %s', hash_files=False, ), terminal_output=dict(nohash=True, ), xDefaultMem=dict(argstr='-xDefaultMem %d', ), xMaxProcess=dict(argstr='-xMaxProcess %d', usedefault=True, ), xPrefExt=dict(argstr='--xPrefExt %s', ), ) inputs = JistIntensityMp2rageMasking.input_spec() for key, metadata in input_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_JistIntensityMp2rageMasking_outputs(): output_map = dict(outMasked=dict(), outMasked2=dict(), outSignal=dict(), outSignal2=dict(), ) outputs = JistIntensityMp2rageMasking.output_spec() for key, metadata in output_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(outputs.traits()[key], metakey), value
bsd-3-clause
pblasquez/librenms
lib/influxdb-php/vendor/guzzlehttp/guzzle/docs/conf.py
46
2006
import sys, os from sphinx.highlighting import lexers from pygments.lexers.web import PhpLexer lexers['php'] = PhpLexer(startinline=True, linenos=1) lexers['php-annotations'] = PhpLexer(startinline=True, linenos=1) primary_domain = 'php' extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'Guzzle' copyright = u'2015, Michael Dowling' version = '6' html_title = "Guzzle Documentation" html_short_title = "Guzzle" exclude_patterns = ['_build'] html_static_path = ['_static'] ##### Guzzle sphinx theme import guzzle_sphinx_theme html_translator_class = 'guzzle_sphinx_theme.HTMLTranslator' html_theme_path = guzzle_sphinx_theme.html_theme_path() html_theme = 'guzzle_sphinx_theme' # Custom sidebar templates, maps document names to template names. html_sidebars = { '**': ['logo-text.html', 'globaltoc.html', 'searchbox.html'] } # Register the theme as an extension to generate a sitemap.xml extensions.append("guzzle_sphinx_theme") # Guzzle theme options (see theme.conf for more information) html_theme_options = { # Set the path to a special layout to include for the homepage # "index_template": "homepage.html", # Allow a separate homepage from the master_doc # homepage = index # Set the name of the project to appear in the nav menu # "project_nav_name": "Guzzle", # Set your Disqus short name to enable comments # "disqus_comments_shortname": "my_disqus_comments_short_name", # Set you GA account ID to enable tracking # "google_analytics_account": "my_ga_account", # Path to a touch icon # "touch_icon": "", # Specify a base_url used to generate sitemap.xml links. If not # specified, then no sitemap will be built. "base_url": "http://guzzlephp.org" # Allow the "Table of Contents" page to be defined separately from "master_doc" # tocpage = Contents # Allow the project link to be overriden to a custom URL. # projectlink = http://myproject.url }
gpl-3.0
pyspeckit/pyspeckit
pyspeckit/spectrum/readers/alfalfa.py
8
2369
""" ALFAFA "source" .sav file """ from __future__ import print_function import idlsave try: import astropy.io.fits as pyfits except ImportError: import pyfits import pyspeckit import numpy as np def read_alfalfa_file(filename): """ Read the contents of a whole ALFALFA source file """ savfile = idlsave.read(filename) source_dict = dict([(name,read_alfalfa_source(savfile,ii)) for ii,name in enumerate(savfile.src.SRCNAME)]) return source_dict def read_alfalfa_source(savfile, sourcenumber=0): """ Create an Observation Block class for a single source in an ALFALFA 'source' IDL save file """ if type(savfile) is str and ".src" in savfile: savfile = idlsave.read(savfile) src = savfile.src[sourcenumber] header = pyfits.Header() splist = [] for spectra in src.spectra: for par in spectra.dtype.names: try: len(spectra[par]) except TypeError: header[par[:8]] = spectra[par] # assume ALFALFA spectra in Kelvin header['BUNIT'] = 'K' xarr = pyspeckit.spectrum.units.SpectroscopicAxis(spectra.velarr, refX=header['RESTFRQ'], refX_unit='MHz', unit='km/s') data = np.ma.masked_where(np.isnan(spectra.spec), spectra.spec) sp = pyspeckit.Spectrum(xarr=xarr, data=data, header=header) # the Source has a baseline presubtracted (I think) sp.baseline.baselinepars = spectra.baseline[::-1] sp.baseline.subtracted = True sp.baseline.order = len(spectra.baseline) sp.baseline.basespec = np.poly1d(sp.baseline.baselinepars)(np.arange(xarr.shape[0])) # There are multiple components in each Spectrum, but I think they are not indepedent sp.specfit.fittype = 'gaussian' sp.specfit.fitter = sp.specfit.Registry.multifitters['gaussian'] modelpars = zip(spectra['STON'],spectra['VCEN'],spectra['WIDTH']) modelerrs = zip(spectra['STON'],spectra['VCENERR_STAT'],spectra['WIDTHERR']) sp.specfit.modelpars = modelpars[0] # only use the first fit sp.specfit.fitter.mpp = modelpars[0] sp.specfit.modelerrs = modelerrs[0] sp.specfit.fitter.mpperr = modelerrs[0] sp.specfit._full_model() splist.append(sp) return pyspeckit.ObsBlock(splist)
mit
laszlocsomor/tensorflow
tensorflow/contrib/data/python/kernel_tests/concatenate_dataset_op_test.py
12
11402
# Copyright 2017 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 the experimental input pipeline ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np from tensorflow.contrib.data.python.ops import dataset_ops from tensorflow.contrib.data.python.ops import iterator_ops from tensorflow.python.data.util import nest from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.platform import test from tensorflow.python.training import saver as saver_lib class ConcatenateDatasetTest(test.TestCase): def testConcatenateDataset(self): input_components = ( np.tile(np.array([[1], [2], [3], [4]]), 20), np.tile(np.array([[12], [13], [14], [15]]), 15), np.array([37.0, 38.0, 39.0, 40.0])) to_concatenate_components = ( np.tile(np.array([[1], [2], [3], [4], [5]]), 20), np.tile(np.array([[12], [13], [14], [15], [16]]), 15), np.array([37.0, 38.0, 39.0, 40.0, 41.0])) input_dataset = dataset_ops.Dataset.from_tensor_slices(input_components) dataset_to_concatenate = dataset_ops.Dataset.from_tensor_slices( to_concatenate_components) concatenated = input_dataset.concatenate(dataset_to_concatenate) self.assertEqual(concatenated.output_shapes, (tensor_shape.TensorShape( [20]), tensor_shape.TensorShape([15]), tensor_shape.TensorShape([]))) iterator = concatenated.make_initializable_iterator() init_op = iterator.initializer get_next = iterator.get_next() with self.test_session() as sess: sess.run(init_op) for i in range(9): result = sess.run(get_next) if i < 4: for component, result_component in zip(input_components, result): self.assertAllEqual(component[i], result_component) else: for component, result_component in zip(to_concatenate_components, result): self.assertAllEqual(component[i - 4], result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testConcatenateDatasetDifferentShape(self): input_components = ( np.tile(np.array([[1], [2], [3], [4]]), 20), np.tile(np.array([[12], [13], [14], [15]]), 4)) to_concatenate_components = ( np.tile(np.array([[1], [2], [3], [4], [5]]), 20), np.tile(np.array([[12], [13], [14], [15], [16]]), 15)) input_dataset = dataset_ops.Dataset.from_tensor_slices(input_components) dataset_to_concatenate = dataset_ops.Dataset.from_tensor_slices( to_concatenate_components) concatenated = input_dataset.concatenate(dataset_to_concatenate) self.assertEqual( [ts.as_list() for ts in nest.flatten(concatenated.output_shapes)], [[20], [None]]) iterator = concatenated.make_initializable_iterator() init_op = iterator.initializer get_next = iterator.get_next() with self.test_session() as sess: sess.run(init_op) for i in range(9): result = sess.run(get_next) if i < 4: for component, result_component in zip(input_components, result): self.assertAllEqual(component[i], result_component) else: for component, result_component in zip(to_concatenate_components, result): self.assertAllEqual(component[i - 4], result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testConcatenateDatasetDifferentStructure(self): input_components = ( np.tile(np.array([[1], [2], [3], [4]]), 5), np.tile(np.array([[12], [13], [14], [15]]), 4)) to_concatenate_components = ( np.tile(np.array([[1], [2], [3], [4], [5]]), 20), np.tile(np.array([[12], [13], [14], [15], [16]]), 15), np.array([37.0, 38.0, 39.0, 40.0, 41.0])) input_dataset = dataset_ops.Dataset.from_tensor_slices(input_components) dataset_to_concatenate = dataset_ops.Dataset.from_tensor_slices( to_concatenate_components) with self.assertRaisesRegexp(ValueError, "don't have the same number of elements"): input_dataset.concatenate(dataset_to_concatenate) def testConcatenateDatasetDifferentType(self): input_components = ( np.tile(np.array([[1], [2], [3], [4]]), 5), np.tile(np.array([[12], [13], [14], [15]]), 4)) to_concatenate_components = ( np.tile(np.array([[1.0], [2.0], [3.0], [4.0]]), 5), np.tile(np.array([[12], [13], [14], [15]]), 15)) input_dataset = dataset_ops.Dataset.from_tensor_slices(input_components) dataset_to_concatenate = dataset_ops.Dataset.from_tensor_slices( to_concatenate_components) with self.assertRaisesRegexp(TypeError, "have different types"): input_dataset.concatenate(dataset_to_concatenate) def _iterator_checkpoint_prefix(self): return os.path.join(self.get_temp_dir(), "iterator") def _build_graph(self, input_components, to_concatenate_components): input_dataset = dataset_ops.Dataset.from_tensor_slices(input_components) dataset_to_concatenate = dataset_ops.Dataset.from_tensor_slices( to_concatenate_components) iterator = input_dataset.concatenate( dataset_to_concatenate).make_initializable_iterator() init_op = iterator.initializer get_next = iterator.get_next() saveable = iterator_ops.make_saveable_from_iterator(iterator) ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable) # TODO(shivaniagrawal) : non-intuitive way, add support in mata_graph for t in nest.flatten(get_next): ops.add_to_collection("get_next", t) return init_op, get_next def _testSaveRestoreUtility(self, start, break_range, stop): path = self._iterator_checkpoint_prefix() step = 0 meta_filename = path + "-%d.meta" % step input_components = (np.tile(np.array([[1], [2], [3], [4]]), 20), np.tile( np.array([[12], [13], [14], [15]]), 4)) to_concatenate_components = (np.tile( np.array([[5], [6], [7], [8], [9]]), 20), np.tile( np.array([[16], [17], [18], [19], [20]]), 15)) with ops.Graph().as_default() as g: init_op, get_next = self._build_graph(input_components, to_concatenate_components) saver = saver_lib.Saver() with self.test_session(graph=g) as sess: sess.run(init_op) for i in range(start, break_range): result = sess.run(get_next) if i < 4: for component, result_component in zip(input_components, result): self.assertAllEqual(component[i], result_component) else: for component, result_component in zip(to_concatenate_components, result): self.assertAllEqual(component[i - 4], result_component) saver.save(sess, path, step) with ops.Graph().as_default() as g: saver = saver_lib.import_meta_graph(meta_filename) with self.test_session(graph=g) as sess: get_next = nest.pack_sequence_as(("a", "b"), ops.get_collection("get_next")) saver.restore(sess, saver_lib.latest_checkpoint(self.get_temp_dir())) for i in range(break_range, stop): result = sess.run(get_next) if i < 4: for component, result_component in zip(input_components, result): self.assertAllEqual(component[i], result_component) else: for component, result_component in zip(to_concatenate_components, result): self.assertAllEqual(component[i - 4], result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) def testRestoreAtFirstDataset(self): start = 0 stop = 9 break_range = 3 self._testSaveRestoreUtility(start, break_range, stop) def testRestoreAtSecondDataset(self): start = 0 stop = 9 break_range = 6 self._testSaveRestoreUtility(start, break_range, stop) def testRestoreAtBetweenDatasets(self): start = 0 stop = 9 break_range = 4 self._testSaveRestoreUtility(start, break_range, stop) def testRestoreExhaustedIterator(self): start = 0 stop = 9 break_range = 9 self._testSaveRestoreUtility(start, break_range, stop) def testRestoreInModifiedGraph(self): start = 0 stop = 9 break_range = 6 path = self._iterator_checkpoint_prefix() step = 0 input_components = (np.tile(np.array([[1], [2], [3], [4]]), 20), np.tile( np.array([[12], [13], [14], [15]]), 4)) to_concatenate_components = (np.tile( np.array([[5], [6], [7], [8], [9]]), 20), np.tile( np.array([[16], [17], [18], [19], [20]]), 15)) with ops.Graph().as_default() as g: init_op, get_next = self._build_graph(input_components, to_concatenate_components) saver = saver_lib.Saver(allow_empty=True) with self.test_session(graph=g) as sess: sess.run(init_op) for i in range(start, break_range): result = sess.run(get_next) if i < 4: for component, result_component in zip(input_components, result): self.assertAllEqual(component[i], result_component) else: for component, result_component in zip(to_concatenate_components, result): self.assertAllEqual(component[i - 4], result_component) saver.save(sess, path, step) new_to_concatenate_components = (np.array([[5], [6], [7], [8], [9]]), np.array([[16], [17], [18], [19], [20]])) with ops.Graph().as_default() as g: init_op, get_next = self._build_graph(input_components, new_to_concatenate_components) saver = saver_lib.Saver() with self.test_session(graph=g) as sess: saver.restore(sess, saver_lib.latest_checkpoint(self.get_temp_dir())) for i in range(break_range, stop): result = sess.run(get_next) for component, result_component in zip(to_concatenate_components, result): self.assertAllEqual(component[i - 4], result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) if __name__ == "__main__": test.main()
apache-2.0
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_07_01/aio/operations/_public_ip_prefixes_operations.py
1
27147
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PublicIPPrefixesOperations: """PublicIPPrefixesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2020_07_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _delete_initial( self, resource_group_name: str, public_ip_prefix_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} # type: ignore async def begin_delete( self, resource_group_name: str, public_ip_prefix_name: str, **kwargs ) -> AsyncLROPoller[None]: """Deletes the specified public IP prefix. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_prefix_name: The name of the PublicIpPrefix. :type public_ip_prefix_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, public_ip_prefix_name=public_ip_prefix_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} # type: ignore async def get( self, resource_group_name: str, public_ip_prefix_name: str, expand: Optional[str] = None, **kwargs ) -> "_models.PublicIPPrefix": """Gets the specified public IP prefix in a specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_prefix_name: The name of the public IP prefix. :type public_ip_prefix_name: str :param expand: Expands referenced resources. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PublicIPPrefix, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_07_01.models.PublicIPPrefix :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPPrefix"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PublicIPPrefix', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, public_ip_prefix_name: str, parameters: "_models.PublicIPPrefix", **kwargs ) -> "_models.PublicIPPrefix": cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPPrefix"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'PublicIPPrefix') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('PublicIPPrefix', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('PublicIPPrefix', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, public_ip_prefix_name: str, parameters: "_models.PublicIPPrefix", **kwargs ) -> AsyncLROPoller["_models.PublicIPPrefix"]: """Creates or updates a static or dynamic public IP prefix. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_prefix_name: The name of the public IP prefix. :type public_ip_prefix_name: str :param parameters: Parameters supplied to the create or update public IP prefix operation. :type parameters: ~azure.mgmt.network.v2020_07_01.models.PublicIPPrefix :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PublicIPPrefix or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_07_01.models.PublicIPPrefix] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPPrefix"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, public_ip_prefix_name=public_ip_prefix_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('PublicIPPrefix', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} # type: ignore async def update_tags( self, resource_group_name: str, public_ip_prefix_name: str, parameters: "_models.TagsObject", **kwargs ) -> "_models.PublicIPPrefix": """Updates public IP prefix tags. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_prefix_name: The name of the public IP prefix. :type public_ip_prefix_name: str :param parameters: Parameters supplied to update public IP prefix tags. :type parameters: ~azure.mgmt.network.v2020_07_01.models.TagsObject :keyword callable cls: A custom type or function that will be passed the direct response :return: PublicIPPrefix, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_07_01.models.PublicIPPrefix :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPPrefix"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update_tags.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'TagsObject') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PublicIPPrefix', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} # type: ignore def list_all( self, **kwargs ) -> AsyncIterable["_models.PublicIPPrefixListResult"]: """Gets all the public IP prefixes in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PublicIPPrefixListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_07_01.models.PublicIPPrefixListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPPrefixListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_all.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('PublicIPPrefixListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPPrefixes'} # type: ignore def list( self, resource_group_name: str, **kwargs ) -> AsyncIterable["_models.PublicIPPrefixListResult"]: """Gets all public IP prefixes in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PublicIPPrefixListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_07_01.models.PublicIPPrefixListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPPrefixListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('PublicIPPrefixListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes'} # type: ignore
mit
DevangS/CoralNet
accounts/migrations/0004_create_user_called_alleviate.py
1
5492
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models from django.conf import settings class Migration(DataMigration): # Create a dummy user called "Alleviate". # This is the user under which Alleviate-accepted annotations # will be added. def forwards(self, orm): username = "Alleviate" print "-----" try: orm['auth.User'].objects.get(username=username) except orm['auth.User'].DoesNotExist: alleviateUser = orm['auth.User'](id=settings.ALLEVIATE_USER_ID, username=username, first_name="", last_name="", email="", password="", ) alleviateUser.save() print "Created user with username %s." % username else: print "User with username %s already exists; nothing needs to be done." % username print "-----" def backwards(self, orm): username = "Alleviate" print ( "-----\n" "NOTE: This migration rollback does nothing. " "Deleting the %s user would delete all Alleviate annotations, " "which would be very bad to do accidentally." "\n-----" % username ) models = { 'accounts.profile': { 'Meta': {'object_name': 'Profile'}, 'about_me': ('django.db.models.fields.CharField', [], {'max_length': '45', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'default': "'en'", 'max_length': '5'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '45', 'blank': 'True'}), 'mugshot': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'privacy': ('django.db.models.fields.CharField', [], {'default': "'registered'", 'max_length': '15'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'my_profile'", 'unique': 'True', 'to': "orm['auth.User']"}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['accounts'] symmetrical = True
bsd-2-clause
tuanvu216/udacity-course
intro_to_machine_learning/lesson/lesson_14_evaluation_metrics/evaluate_poi_identifier.py
1
2588
#!/usr/bin/python """ starter code for the evaluation mini-project start by copying your trained/tested POI identifier from that you built in the validation mini-project the second step toward building your POI identifier! start by loading/formatting the data """ import pickle import sys sys.path.append("C:/Vindico/Projects/Code/Python/Python/Course/Udacity/Intro to Machine Learning/ud120-projects-master/tools/") from feature_format import featureFormat, targetFeatureSplit from sklearn.tree import DecisionTreeClassifier from sklearn import cross_validation import numpy as np data_dict = pickle.load(open("C:/Vindico/Projects/Code/Python/Python/Course/Udacity/Intro to Machine Learning/ud120-projects-master/final_project/final_project_dataset.pkl", "r") ) ### add more features to features_list! features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### your code goes here features_train,features_test,labels_train,labels_test = cross_validation.train_test_split(features,labels,test_size=0.3, random_state=42) clf = DecisionTreeClassifier() clf.fit(features_train,labels_train) clf.score(features_test,labels_test) # How many POIs are in the test set for your POI identifier? pred = clf.predict(features_test) sum(pred) print len([e for e in labels_test if e == 1.0]) # How many people total are in your test set? len(pred) # If your identifier predicted 0. (not POI) for everyone in the test set, what would its accuracy be? 1.0 - 5.0/29 # Precision and recall can help illuminate your performance better. # Use the precision_score and recall_score available in sklearn.metrics to compute those quantities. # What’s the precision? from sklearn.metrics import * precision_score(labels_test, pred) # What’s the recall? recall_score(labels_test, pred) # Here are some made-up predictions and true labels for a hypothetical test set; # fill in the following boxes to practice identifying true positives, false positives, true negatives, and false negatives. # Let’s use the convention that “1” signifies a positive result, and “0” a negative. predictions = [0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1] true_labels = [0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0] # What's the precision of this classifier? precision_score(true_labels, predictions) # What's the recall of this classifier? recall_score(true_labels, predictions)
mit
jlachowski/clonedigger
clonedigger/clone_detection_algorithm.py
2
16192
from __future__ import print_function from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import range from builtins import * from past.utils import old_div # Copyright 2008 Peter Bulychev # # This file is part of Clone Digger. # # Clone Digger 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. # # Clone Digger 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 Clone Digger. If not, see <http://www.gnu.org/licenses/>. import sys from .anti_unification import * from .abstract_syntax_tree import * def findDuplicateCode(source_files, report): statement_sequences = [] statement_count = 0 sequences_lengths = [] for source_file in source_files: sequences = source_file.getTree().getAllStatementSequences() statement_sequences.extend(sequences) sequences_lengths.extend([len(s) for s in sequences]) statement_count += sum([len(s) for s in sequences]) if not sequences_lengths: print('Input is empty or the size of the input is below the size threshold') # sys.exit(0) return [] if verbose: n_sequences = len(sequences_lengths) avg_seq_length = old_div(sum(sequences_lengths),float(n_sequences)) max_seq_length = max(sequences_lengths) print('%d sequences' %(n_sequences,)) print('average sequence length: %f' % (avg_seq_length,)) print('maximum sequence length: %d' % (max_seq_length,)) sequences_without_restriction = statement_sequences sequences = [] if not arguments.force: for sequence in sequences_without_restriction: if len(sequence) > 1000: first_statement = sequence[0] print() print('-----------------------------------------') print('Warning: sequences of statements, consists of %d elements is too long.' %(len(sequence),)) print('It starts at %s:%d.'%(first_statement.getSourceFile().getFileName(), min(first_statement.getCoveredLineNumbers()))) print('It will be ignored. Use --force to override this restriction.') print('Please refer to http://clonedigger.sourceforge.net/documentation.html') print('-----------------------------------------') else: sequences.append(sequence) def calc_statement_sizes(): for sequence in statement_sequences: for statement in sequence: statement.storeSize() def build_hash_to_statement(dcup_hash = True): hash_to_statement = {} for statement_sequence in statement_sequences: for statement in statement_sequence: if dcup_hash: # 3 - CONSTANT HERE! h = statement.getDCupHash(arguments.hashing_depth) else: h = statement.getFullHash() if h not in hash_to_statement: hash_to_statement[h] = [statement] else: hash_to_statement[h].append(statement) return hash_to_statement def build_unifiers(hash_to_statement): processed_statements_count = 0 clusters = [] ret = {} for h in list(hash_to_statement.keys()): local_clusters = [] statements = hash_to_statement[h] for statement in statements: processed_statements_count += 1 if verbose and ((processed_statements_count % 1000) == 0): print('%d,' %(processed_statements_count,), end=' ') sys.stdout.flush() bestcluster = None mincost = sys.maxsize for cluster in local_clusters: cost = cluster.getAddCost(statement) if cost < mincost: mincost = cost bestcluster = cluster assert(local_clusters==[] or bestcluster) if mincost < 0: pdb.set_trace() assert(mincost >= 0) if bestcluster == None or mincost > arguments.clustering_threshold: newcluster = Cluster(statement) local_clusters.append(newcluster) else: bestcluster.unify(statement) ret[h] = local_clusters clusters.extend(local_clusters) return ret def clusterize(hash_to_statement, clusters_map): processed_statements_count = 0 # clusters_map contain hash values for statements, not unifiers # therefore it will work correct even if unifiers are smaller than hashing depth value for h in list(hash_to_statement.keys()): clusters = clusters_map[h] for statement in hash_to_statement[h]: processed_statements_count += 1 if verbose and ((processed_statements_count % 1000) == 0): print('%d,' %(processed_statements_count,), end=' ') sys.stdout.flush() mincost = sys.maxsize for cluster in clusters: new_u = Unifier(cluster.getUnifierTree(), statement) # assert(new_u.getSubstitutions()[0].getSize() == 0) cost = new_u.getSize() if cost < mincost: mincost = cost statement.setMark(cluster) cluster.addWithoutUnification(statement) def filterOutLongEquallyLabeledSequences(statement_sequences): #TODO - refactor, combine with the previous warning sequences_without_restriction = statement_sequences statement_sequences = [] for sequence in sequences_without_restriction: new_sequence = copy.copy(sequence._sequence) current_mark = None length = 0 first_statement_index = None flag = False for i in range(len(sequence)): statement = sequence[i] if statement.getMark() != current_mark: if flag == True: flag = False current_mark=statement.getMark() length=0 first_statement_index = i else: length += 1 if length>10: new_sequence[i] = None if not flag: for i in range(first_statement_index, i): new_sequence[i] = None first_statement = sequence[first_statement_index] print() print('-----------------------------------------') print('Warning: sequence of statements starting at %s:%d'%(first_statement.getSourceFile().getFileName(), min(first_statement.getCoveredLineNumbers()))) print('consists of many similar statements.') print('It will be ignored. Use --force to override this restriction.') print('Please refer to http://clonedigger.sourceforge.net/documentation.html') print('-----------------------------------------') flag = True new_sequence = new_sequence + [None] cur_sequence = StatementSequence() for statement in new_sequence: if statement == None: if cur_sequence: statement_sequences.append(cur_sequence) cur_sequence = StatementSequence() else: cur_sequence.addStatement(statement) return statement_sequences def mark_using_hash(hash_to_statement): for h in hash_to_statement: cluster = Cluster() for statement in hash_to_statement[h]: cluster.addWithoutUnification(statement) statement.setMark(cluster) def findHugeSequences(): def f_size(x): return x.getMaxCoveredLines() def f_elem(x): return StatementSequence(x).getCoveredLineNumbersCount() def fcode(x): return x.getMark() f = f_size suffix_tree_instance = suffix_tree.SuffixTree(fcode) for sequence in statement_sequences: suffix_tree_instance.add(sequence) return [PairSequences([StatementSequence(s1), StatementSequence(s2)]) for (s1,s2) in suffix_tree_instance.getBestMaxSubstrings(arguments.size_threshold, f, f_elem)] def refineDuplicates(pairs_sequences): r = [] flag = False while pairs_sequences: pair_sequences = pairs_sequences.pop() def all_pairsubsequences_size_n_threshold(n): lr = [] for first in range(0, pair_sequences.getLength()-n+1): new_pair_sequences = pair_sequences.subSequence(first, n) size = new_pair_sequences.getMaxCoveredLineNumbersCount() if size >= arguments.size_threshold: lr.append((new_pair_sequences, first)) return lr n = pair_sequences.getLength() + 1 while 1: n-=1 if n == 0: break new_pairs_sequences = all_pairsubsequences_size_n_threshold(n) for (candidate_sequence, first) in new_pairs_sequences: distance = candidate_sequence.calcDistance() if (distance < arguments.distance_threshold): r.append(candidate_sequence) if first > 0: pairs_sequences.append(pair_sequences.subSequence(0, first-1)) if first+n < pair_sequences.getLength(): pairs_sequences.append(pair_sequences.subSequence(first+n, pair_sequences.getLength() - first - n)) n+=1 flag = True break if flag: flag = False break return r def remove_dominated_clones(clones): ret_clones = [] # def f_cmp(a, b): # return a.getLevel().__cmp__(b.getLevel()) # clones.sort(f_cmp) statement_to_clone = {} for clone in clones: for sequence in clone: for statement in sequence: if statement not in statement_to_clone: statement_to_clone[statement] = [] statement_to_clone[statement].append(clone) for clone in clones: ancestors_2 = clone[1].getAncestors() flag = True for s1 in clone[0].getAncestors(): if s1 in statement_to_clone: for clone2 in statement_to_clone[s1]: if s1 in clone2[0]: seq = clone2[1] else: assert(s1 in clone2[1]) seq = clone2[0] for s2 in seq: if s2 in ancestors_2: flag = False break if not flag: break if not flag: break if flag: ret_clones.append(clone) return ret_clones if verbose: print('Number of statements: ', statement_count) print('Calculating size for each statement...', end=' ') sys.stdout.flush() calc_statement_sizes() if verbose: print('done') if verbose: print('Building statement hash...', end=' ') sys.stdout.flush() report.startTimer('Building statement hash') if arguments.clusterize_using_hash: hash_to_statement = build_hash_to_statement(dcup_hash = False) else: hash_to_statement = build_hash_to_statement(dcup_hash = True) report.stopTimer() if verbose: print('done') print('Number of different hash values: ', len(hash_to_statement)) if arguments.clusterize_using_dcup or arguments.clusterize_using_hash: print('Marking each statement with its hash value') mark_using_hash(hash_to_statement) else: if verbose: print('Building patterns...', end=' ') sys.stdout.flush() report.startTimer('Building patterns') clusters_map = build_unifiers(hash_to_statement) report.stopTimer() if verbose: print(Cluster.count, 'patterns were discovered') print('Choosing pattern for each statement...', end=' ') sys.stdout.flush() report.startTimer('Marking similar statements') clusterize(hash_to_statement, clusters_map) report.stopTimer() if verbose: print('done') if arguments.report_unifiers: if verbose: print('Building reverse hash for reporting ...', end=' ') sys.stdout.flush() reverse_hash = {} for sequence in statement_sequences: for statement in sequence: mark = statement.getMark() if mark not in reverse_hash: reverse_hash[mark] = [] reverse_hash[mark].append(statement) report.setMarkToStatementHash(reverse_hash) if verbose: print('done') if verbose: print('Finding similar sequences of statements...', end=' ') sys.stdout.flush() if not arguments.force: statement_sequences = filterOutLongEquallyLabeledSequences(statement_sequences) report.startTimer('Finding similar sequences of statements') duplicate_candidates = findHugeSequences() report.stopTimer() if verbose: print(len(duplicate_candidates), ' sequences were found') print('Refining candidates...', end=' ') sys.stdout.flush() if arguments.distance_threshold!=-1: report.startTimer('Refining candidates') clones = refineDuplicates(duplicate_candidates) report.stopTimer() else: clones = duplicate_candidates if verbose: print(len(clones), 'clones were found') if arguments.distance_threshold!=-1: if verbose: print('Removing dominated clones...', end=' ') sys.stdout.flush() old_clone_count = len(clones) clones = remove_dominated_clones(clones) if verbose: print(len(clones) - old_clone_count, 'clones were removed') ## get covered source lines for all detected clones (set of all) covered_source_lines = set() for clone in clones: for sequence in clone: covered_source_lines |= sequence.getLineNumberHashables() ## get source lines for all files/sequences (set of all) source_lines = set() for sequence in statement_sequences: source_lines |= sequence.getLineNumberHashables() report.all_source_lines_count = len(source_lines) report.covered_source_lines_count = len(covered_source_lines) return clones
gpl-3.0
ahaym/eden
modules/unit_tests/s3/benchmark.py
26
11407
# -*- coding: utf-8 -*- # # Core Benchmarks # # To run this script use: # python web2py.py -S eden -M -R applications/eden/modules/unit_tests/s3/benchmark.py # # Note: # # These tests represent the performance of specific server-side core # functions of Sahana Eden which are typically called millions of times # during normal operation of the site. # # The results of these tests depend on many variables (e.g. hardware # configuration, software stack etc.), thus, to compare the results # in order to optimize code or detect newly introduced bottlenecks the # tests must be run on always the same environment. # # When running these tests in order to optimize the environment, you can # use these benchmarks as a rough guideline for what you can expect: # # S3Model.configure = 2.90979003906 µs # S3Model.get_config = 2.2715420723 µs # S3Model.table(non-table) = 2.13528013229 µs # S3Model.get(non-table) = 2.0619969368 µs # S3Model.__getattr__(non-table) = 4.12402009964 µs # S3Model.__getitem__(non-table) = 4.24327015877 µs # S3Model.table = 2.91769790649 µs # S3Model.__getattr__ = 4.959856987 µs # S3Model.__getitem__ = 5.19830703735 µs # S3Resource.import_xml = 12.0009431839 ms (=83 rec/sec) # S3Resource.export (incl. DB extraction) = 3.75156188011 ms (=266 rec/sec) # S3Resource.export (w/o DB extraction) = 1.7192029953 ms (=581 rec/sec) # S3Resource.__init__ = 2.65161395073 ms # S3Resource.load = 5.55664610863 ms # # If you cannot achieve approximately these or even better results, then # it is recommendable to put effort into the optimization of the environment # in order to run Sahana Eden with acceptable performance. Typically you would # try to deploy Eden in an enviroment that allows 2-10 times better performance # than that. # # If you get FAIL messages, then the overall performance of Sahana Eden in # your enviroment is likely to be completely unacceptable. # import unittest import timeit # ============================================================================= #@unittest.skip("Comment or remove this line in modules/unit_tests/eden/benchmark.py to activate this test") class S3PerformanceTests(unittest.TestCase): def testDBSelect(self): """ DAL query peak performance """ db = current.db s3db = current.s3db print "" table = s3db.table("pr_person") x = lambda: [(row.first_name, row.last_name) for row in db(table.id > 0).select(table.id, table.first_name, table.last_name, limitby=(0, 50))] n = len(x()) mlt = timeit.Timer(x).timeit(number = int(100/n)) print "db.select = %s ms/record (=%s rec/sec)" % (mlt * 10.0, int(100/mlt)) x = lambda: [[(row.first_name, row.last_name) for row in db(table.id < i).select(table.id, table.first_name, table.last_name)] for i in xrange(n)] mlt = timeit.Timer(x).timeit(number = 10) * (100/n) print "db.select = %s ms/query (=%s q/sec)" % (mlt, int(1000/mlt)) def testS3ModelTable(self): s3db = current.s3db print "" table = s3db.table("pr_person") if table is not None: x = lambda: s3db.table("pr_person") mlt = timeit.Timer(x).timeit() print "S3Model.table = %s µs" % mlt self.assertTrue(mlt<10) x = lambda: s3db.pr_person mlt = timeit.Timer(x).timeit() print "S3Model.__getattr__ = %s µs" % mlt self.assertTrue(mlt<10) x = lambda: s3db["pr_person"] mlt = timeit.Timer(x).timeit() print "S3Model.__getitem__ = %s µs" % mlt self.assertTrue(mlt<10) def testS3ModelName(self): s3db = current.s3db print "" func = s3db.get("pr_person_represent") if func is not None: x = lambda: s3db.table("pr_person_represent") mlt = timeit.Timer(x).timeit() print "S3Model.table(non-table) = %s µs" % mlt self.assertTrue(mlt<10) x = lambda: s3db.get("pr_person_represent") mlt = timeit.Timer(x).timeit() print "S3Model.get(non-table) = %s µs" % mlt self.assertTrue(mlt<10) x = lambda: s3db.pr_person_represent mlt = timeit.Timer(x).timeit() print "S3Model.__getattr__(non-table) = %s µs" % mlt self.assertTrue(mlt<10) x = lambda: s3db["pr_person_represent"] mlt = timeit.Timer(x).timeit() print "S3Model.__getitem__(non-table) = %s µs" % mlt self.assertTrue(mlt<10) def testS3ModelConfigure(self): s3db = current.s3db print "" configure = s3db.configure x = lambda: configure("pr_person", testconfig = "Test") mlt = timeit.Timer(x).timeit() print "S3Model.configure = %s µs" % mlt self.assertTrue(mlt<10) get_config = s3db.get_config x = lambda: get_config("pr_person", "testconfig") mlt = timeit.Timer(x).timeit() print "S3Model.get_config = %s µs" % mlt self.assertTrue(mlt<10) def testS3ResourceInit(self): print "" current.auth.override = True current.s3db.resource("pr_person") x = lambda: current.s3db.resource("pr_person") mlt = timeit.Timer(x).timeit(number=1000) print "S3Resource.__init__ = %s ms" % mlt self.assertTrue(mlt<10) current.auth.override = False def testS3ResourceLoad(self): print "" current.auth.override = True resource = current.s3db.resource("pr_person") x = lambda: resource.load(limit=1) mlt = timeit.Timer(x).timeit(number=1000) print "S3Resource.load = %s ms" % mlt self.assertTrue(mlt<10) current.auth.override = False def testS3ResourceImportExport(self): xmlstr = """ <s3xml> <resource name="org_organisation" tuid="Philippine Red Cross"> <data field="name">Philippine Red Cross</data> </resource> <resource name="hrm_job_title" tuid="Team Leader"> <data field="name">Team Leader</data> <reference field="organisation_id" resource="org_organisation" tuid="Philippine Red Cross"/> </resource> <resource name="pr_person"> <data field="first_name">Chona</data> <data field="middle_name"/> <data field="last_name">Alinsub</data> <data field="initials"/> <data field="date_of_birth"/> <resource name="pr_person_details"> <data field="father_name"/> <data field="mother_name"/> <data field="occupation"/> <data field="company"/> <data field="affiliations"/> </resource> <resource name="pr_contact"> <data field="contact_method" value="SMS"/> <data field="value">9463778503</data> </resource> <resource name="pr_address"> <reference field="location_id" resource="gis_location" tuid="Location L4: Rizal"/> <data field="type">1</data> <data field="building_name"/> <data field="address"/> <data field="postcode">6600</data> <data field="L0">Philippines</data> <data field="L1">Visayas</data> <data field="L2">Southern Leyte</data> <data field="L3">Maasin City</data> <data field="L4">Rizal</data> </resource> <resource name="hrm_human_resource"> <data field="type">2</data> <reference field="job_title_id" resource="hrm_job_title" tuid="Team Leader"/> <reference field="organisation_id" resource="org_organisation" tuid="Philippine Red Cross"/> </resource> </resource> <resource name="gis_location" tuid="Location L1: Visayas"> <reference field="parent" resource="gis_location" uuid="urn:iso:std:iso:3166:-1:code:PH"/> <data field="name">Visayas</data> <data field="level">L1</data> </resource> <resource name="gis_location" tuid="Location L2: Southern Leyte"> <reference field="parent" resource="gis_location" tuid="Location L1: Visayas"/> <data field="name">Southern Leyte</data> <data field="level">L2</data> </resource> <resource name="gis_location" tuid="Location L3: Maasin City"> <reference field="parent" resource="gis_location" tuid="Location L2: Southern Leyte"/> <data field="name">Maasin City</data> <data field="level">L3</data> </resource> <resource name="gis_location" tuid="Location L4: Rizal"> <reference field="parent" resource="gis_location" tuid="Location L3: Maasin City"/> <data field="name">Rizal</data> <data field="level">L4</data> </resource> </s3xml>""" from lxml import etree tree = etree.ElementTree(etree.fromstring(xmlstr)) current.auth.override = True current.db.rollback() print "" resource = current.s3db.resource("org_organisation") x = lambda: resource.import_xml(tree) mlt = 0 for i in xrange(100): mlt += timeit.Timer(x).timeit(number=1) current.db.rollback() mlt *= 10 print "S3Resource.import_xml = %s ms (=%s rec/sec)" % (mlt, int(1000/mlt)) self.assertTrue(mlt<30) resource = current.s3db.resource("pr_person") from lxml import etree parent = etree.Element("test") rfields, dfields = resource.split_fields() x = lambda: resource._export_record(resource.table[1], rfields=rfields, dfields=dfields, parent=parent, export_map=Storage()) mlt = timeit.Timer(x).timeit(number=1000) print "S3Resource.export (incl. DB extraction) = %s ms (=%s rec/sec)" % (mlt, int(1000/mlt)) self.assertTrue(mlt<10) resource = current.s3db.resource("pr_person") from lxml import etree parent = etree.Element("test") rfields, dfields = resource.split_fields() record = resource.table[1] x = lambda: resource._export_record(record, rfields=rfields, dfields=dfields, parent=parent, export_map=Storage()) mlt = timeit.Timer(x).timeit(number=1000) print "S3Resource.export (w/o DB extraction) = %s ms (=%s rec/sec)" % (mlt, int(1000/mlt)) self.assertTrue(mlt<10) current.auth.override = False # ============================================================================= def run_suite(*test_classes): """ Run the test suite """ loader = unittest.TestLoader() suite = unittest.TestSuite() for test_class in test_classes: tests = loader.loadTestsFromTestCase(test_class) suite.addTests(tests) if suite is not None: unittest.TextTestRunner(verbosity=2).run(suite) return if __name__ == "__main__": run_suite( S3PerformanceTests, ) # END ========================================================================
mit
jeanlinux/calibre
src/calibre/gui2/viewer/config.py
8
20731
#!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import zipfile from functools import partial from PyQt5.Qt import ( QFont, QDialog, Qt, QColor, QColorDialog, QMenu, QInputDialog, QListWidgetItem, QFormLayout, QLabel, QLineEdit, QDialogButtonBox) from calibre.constants import iswindows, isxp from calibre.utils.config import Config, StringConfig, JSONConfig from calibre.utils.icu import sort_key from calibre.utils.localization import get_language, calibre_langcode_to_name from calibre.gui2 import min_available_height, error_dialog from calibre.gui2.languages import LanguagesEdit from calibre.gui2.shortcuts import ShortcutConfig from calibre.gui2.viewer.config_ui import Ui_Dialog def config(defaults=None): desc = _('Options to customize the ebook viewer') if defaults is None: c = Config('viewer', desc) else: c = StringConfig(defaults, desc) c.add_opt('remember_window_size', default=False, help=_('Remember last used window size')) c.add_opt('user_css', default='', help=_('Set the user CSS stylesheet. This can be used to customize the look of all books.')) c.add_opt('max_fs_width', default=800, help=_("Set the maximum width that the book's text and pictures will take" " when in fullscreen mode. This allows you to read the book text" " without it becoming too wide.")) c.add_opt('max_fs_height', default=-1, help=_("Set the maximum height that the book's text and pictures will take" " when in fullscreen mode. This allows you to read the book text" " without it becoming too tall. Note that this setting only takes effect in paged mode (which is the default mode).")) c.add_opt('fit_images', default=True, help=_('Resize images larger than the viewer window to fit inside it')) c.add_opt('hyphenate', default=False, help=_('Hyphenate text')) c.add_opt('hyphenate_default_lang', default='en', help=_('Default language for hyphenation rules')) c.add_opt('search_online_url', default='https://www.google.com/search?q={text}', help=_('The URL to use when searching for selected text online')) c.add_opt('remember_current_page', default=True, help=_('Save the current position in the document, when quitting')) c.add_opt('copy_bookmarks_to_file', default=True, help=_('Copy bookmarks to the ebook file for easy sharing, if possible')) c.add_opt('wheel_flips_pages', default=False, help=_('Have the mouse wheel turn pages')) c.add_opt('tap_flips_pages', default=True, help=_('Tapping on the screen turns pages')) c.add_opt('line_scrolling_stops_on_pagebreaks', default=False, help=_('Prevent the up and down arrow keys from scrolling past ' 'page breaks')) c.add_opt('page_flip_duration', default=0.5, help=_('The time, in seconds, for the page flip animation. Default' ' is half a second.')) c.add_opt('font_magnification_step', default=0.2, help=_('The amount by which to change the font size when clicking' ' the font larger/smaller buttons. Should be a number between ' '0 and 1.')) c.add_opt('fullscreen_clock', default=False, action='store_true', help=_('Show a clock in fullscreen mode.')) c.add_opt('fullscreen_pos', default=False, action='store_true', help=_('Show reading position in fullscreen mode.')) c.add_opt('fullscreen_scrollbar', default=True, action='store_false', help=_('Show the scrollbar in fullscreen mode.')) c.add_opt('start_in_fullscreen', default=False, action='store_true', help=_('Start viewer in full screen mode')) c.add_opt('show_fullscreen_help', default=True, action='store_false', help=_('Show full screen usage help')) c.add_opt('cols_per_screen', default=1) c.add_opt('cols_per_screen_portrait', default=1) c.add_opt('cols_per_screen_landscape', default=1) c.add_opt('cols_per_screen_migrated', default=False, action='store_true') c.add_opt('use_book_margins', default=False, action='store_true') c.add_opt('top_margin', default=20) c.add_opt('side_margin', default=40) c.add_opt('bottom_margin', default=20) c.add_opt('text_color', default=None) c.add_opt('background_color', default=None) c.add_opt('show_controls', default=True) fonts = c.add_group('FONTS', _('Font options')) fonts('serif_family', default='Times New Roman' if iswindows else 'Liberation Serif', help=_('The serif font family')) fonts('sans_family', default='Verdana' if iswindows else 'Liberation Sans', help=_('The sans-serif font family')) fonts('mono_family', default='Courier New' if iswindows else 'Liberation Mono', help=_('The monospaced font family')) fonts('default_font_size', default=20, help=_('The standard font size in px')) fonts('mono_font_size', default=16, help=_('The monospaced font size in px')) fonts('standard_font', default='serif', help=_('The standard font type')) fonts('minimum_font_size', default=8, help=_('The minimum font size in px')) oparse = c.parse def parse(): ans = oparse() if not ans.cols_per_screen_migrated: ans.cols_per_screen_portrait = ans.cols_per_screen_landscape = ans.cols_per_screen return ans c.parse = parse return c def load_themes(): return JSONConfig('viewer_themes') class ConfigDialog(QDialog, Ui_Dialog): def __init__(self, shortcuts, parent=None): QDialog.__init__(self, parent) self.setupUi(self) for x in ('text', 'background'): getattr(self, 'change_%s_color_button'%x).clicked.connect( partial(self.change_color, x, reset=False)) getattr(self, 'reset_%s_color_button'%x).clicked.connect( partial(self.change_color, x, reset=True)) self.css.setToolTip(_('Set the user CSS stylesheet. This can be used to customize the look of all books.')) self.shortcuts = shortcuts self.shortcut_config = ShortcutConfig(shortcuts, parent=self) bb = self.buttonBox bb.button(bb.RestoreDefaults).clicked.connect(self.restore_defaults) with zipfile.ZipFile(P('viewer/hyphenate/patterns.zip', allow_user_override=False), 'r') as zf: pats = [x.split('.')[0].replace('-', '_') for x in zf.namelist()] names = list(map(get_language, pats)) pmap = {} for i in range(len(pats)): pmap[names[i]] = pats[i] for x in sorted(names): self.hyphenate_default_lang.addItem(x, pmap[x]) self.hyphenate_pats = pats self.hyphenate_names = names p = self.tabs.widget(1) p.layout().addWidget(self.shortcut_config) if isxp: self.hyphenate.setVisible(False) self.hyphenate_default_lang.setVisible(False) self.hyphenate_label.setVisible(False) self.themes = load_themes() self.save_theme_button.clicked.connect(self.save_theme) self.load_theme_button.m = m = QMenu() self.load_theme_button.setMenu(m) m.triggered.connect(self.load_theme) self.delete_theme_button.m = m = QMenu() self.delete_theme_button.setMenu(m) m.triggered.connect(self.delete_theme) opts = config().parse() self.load_options(opts) self.init_load_themes() self.init_dictionaries() self.clear_search_history_button.clicked.connect(self.clear_search_history) self.resize(self.width(), min(self.height(), max(575, min_available_height()-25))) for x in 'add remove change'.split(): getattr(self, x + '_dictionary_website_button').clicked.connect(getattr(self, x + '_dictionary_website')) def clear_search_history(self): from calibre.gui2 import config config['viewer_search_history'] = [] config['viewer_toc_search_history'] = [] def save_theme(self): themename, ok = QInputDialog.getText(self, _('Theme name'), _('Choose a name for this theme')) if not ok: return themename = unicode(themename).strip() if not themename: return c = config('') c.add_opt('theme_name_xxx', default=themename) self.save_options(c) self.themes['theme_'+themename] = c.src self.init_load_themes() self.theming_message.setText(_('Saved settings as the theme named: %s')% themename) def init_load_themes(self): for x in ('load', 'delete'): m = getattr(self, '%s_theme_button'%x).menu() m.clear() for x in self.themes.iterkeys(): title = x[len('theme_'):] ac = m.addAction(title) ac.theme_id = x def load_theme(self, ac): theme = ac.theme_id raw = self.themes[theme] self.load_options(config(raw).parse()) self.theming_message.setText(_('Loaded settings from the theme %s')% theme[len('theme_'):]) def delete_theme(self, ac): theme = ac.theme_id del self.themes[theme] self.init_load_themes() self.theming_message.setText(_('Deleted the theme named: %s')% theme[len('theme_'):]) def init_dictionaries(self): from calibre.gui2.viewer.main import dprefs self.word_lookups = dprefs['word_lookups'] @dynamic_property def word_lookups(self): def fget(self): return dict(self.dictionary_list.item(i).data(Qt.UserRole) for i in range(self.dictionary_list.count())) def fset(self, wl): self.dictionary_list.clear() for langcode, url in sorted(wl.iteritems(), key=lambda (lc, url):sort_key(calibre_langcode_to_name(lc))): i = QListWidgetItem('%s: %s' % (calibre_langcode_to_name(langcode), url), self.dictionary_list) i.setData(Qt.UserRole, (langcode, url)) return property(fget=fget, fset=fset) def add_dictionary_website(self): class AD(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.setWindowTitle(_('Add a dictionary website')) self.l = l = QFormLayout(self) self.la = la = QLabel('<p>'+ _('Choose a language and enter the website address (URL) for it below.' ' The URL must have the placeholder <b>%s</b> in it, which will be replaced by the actual word being' ' looked up') % '{word}') la.setWordWrap(True) l.addRow(la) self.le = LanguagesEdit(self) l.addRow(_('&Language:'), self.le) self.url = u = QLineEdit(self) u.setMinimumWidth(350) u.setPlaceholderText(_('For example: %s') % 'http://dictionary.com/{word}') l.addRow(_('&URL:'), u) self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) l.addRow(bb) bb.accepted.connect(self.accept), bb.rejected.connect(self.reject) self.resize(self.sizeHint()) def accept(self): if '{word}' not in self.url.text(): return error_dialog(self, _('Invalid URL'), _( 'The URL {0} does not have the placeholder <b>{1}</b> in it.').format(self.url.text(), '{word}'), show=True) QDialog.accept(self) d = AD(self) if d.exec_() == d.Accepted: url = d.url.text() if url: wl = self.word_lookups for lc in d.le.lang_codes: wl[lc] = url self.word_lookups = wl def remove_dictionary_website(self): idx = self.dictionary_list.currentIndex() if idx.isValid(): lc, url = idx.data(Qt.UserRole) wl = self.word_lookups wl.pop(lc, None) self.word_lookups = wl def change_dictionary_website(self): idx = self.dictionary_list.currentIndex() if idx.isValid(): lc, url = idx.data(Qt.UserRole) url, ok = QInputDialog.getText(self, _('Enter new website'), 'URL:', text=url) if ok: wl = self.word_lookups wl[lc] = url self.word_lookups = wl def restore_defaults(self): opts = config('').parse() self.load_options(opts) from calibre.gui2.viewer.main import dprefs self.word_lookups = dprefs.defaults['word_lookups'] def load_options(self, opts): self.opt_remember_window_size.setChecked(opts.remember_window_size) self.opt_remember_current_page.setChecked(opts.remember_current_page) self.opt_copy_bookmarks_to_file.setChecked(opts.copy_bookmarks_to_file) self.opt_wheel_flips_pages.setChecked(opts.wheel_flips_pages) self.opt_tap_flips_pages.setChecked(opts.tap_flips_pages) self.opt_page_flip_duration.setValue(opts.page_flip_duration) fms = opts.font_magnification_step if fms < 0.01 or fms > 1: fms = 0.2 self.opt_font_mag_step.setValue(int(fms*100)) self.opt_line_scrolling_stops_on_pagebreaks.setChecked( opts.line_scrolling_stops_on_pagebreaks) self.serif_family.setCurrentFont(QFont(opts.serif_family)) self.sans_family.setCurrentFont(QFont(opts.sans_family)) self.mono_family.setCurrentFont(QFont(opts.mono_family)) self.default_font_size.setValue(opts.default_font_size) self.minimum_font_size.setValue(opts.minimum_font_size) self.mono_font_size.setValue(opts.mono_font_size) self.standard_font.setCurrentIndex( {'serif':0, 'sans':1, 'mono':2}[opts.standard_font]) self.css.setPlainText(opts.user_css) self.max_fs_width.setValue(opts.max_fs_width) self.max_fs_height.setValue(opts.max_fs_height) pats, names = self.hyphenate_pats, self.hyphenate_names try: idx = pats.index(opts.hyphenate_default_lang) except ValueError: idx = pats.index('en_us') idx = self.hyphenate_default_lang.findText(names[idx]) self.hyphenate_default_lang.setCurrentIndex(idx) self.hyphenate.setChecked(opts.hyphenate) self.hyphenate_default_lang.setEnabled(opts.hyphenate) self.search_online_url.setText(opts.search_online_url or '') self.opt_fit_images.setChecked(opts.fit_images) self.opt_fullscreen_clock.setChecked(opts.fullscreen_clock) self.opt_fullscreen_scrollbar.setChecked(opts.fullscreen_scrollbar) self.opt_start_in_fullscreen.setChecked(opts.start_in_fullscreen) self.opt_show_fullscreen_help.setChecked(opts.show_fullscreen_help) self.opt_fullscreen_pos.setChecked(opts.fullscreen_pos) self.opt_cols_per_screen_portrait.setValue(opts.cols_per_screen_portrait) self.opt_cols_per_screen_landscape.setValue(opts.cols_per_screen_landscape) self.opt_override_book_margins.setChecked(not opts.use_book_margins) for x in ('top', 'bottom', 'side'): getattr(self, 'opt_%s_margin'%x).setValue(getattr(opts, x+'_margin')) for x in ('text', 'background'): setattr(self, 'current_%s_color'%x, getattr(opts, '%s_color'%x)) self.update_sample_colors() self.opt_show_controls.setChecked(opts.show_controls) def change_color(self, which, reset=False): if reset: setattr(self, 'current_%s_color'%which, None) else: initial = getattr(self, 'current_%s_color'%which) if initial: initial = QColor(initial) else: initial = Qt.black if which == 'text' else Qt.white title = (_('Choose text color') if which == 'text' else _('Choose background color')) col = QColorDialog.getColor(initial, self, title, QColorDialog.ShowAlphaChannel) if col.isValid(): name = unicode(col.name()) setattr(self, 'current_%s_color'%which, name) self.update_sample_colors() def update_sample_colors(self): for x in ('text', 'background'): val = getattr(self, 'current_%s_color'%x) if not val: val = 'inherit' if x == 'text' else 'transparent' ss = 'QLabel { %s: %s }'%('background-color' if x == 'background' else 'color', val) getattr(self, '%s_color_sample'%x).setStyleSheet(ss) def accept(self, *args): if self.shortcut_config.is_editing: from calibre.gui2 import info_dialog info_dialog(self, _('Still editing'), _('You are in the middle of editing a keyboard shortcut' ' first complete that, by clicking outside the ' ' shortcut editing box.'), show=True) return self.save_options(config()) return QDialog.accept(self, *args) def save_options(self, c): c.set('serif_family', unicode(self.serif_family.currentFont().family())) c.set('sans_family', unicode(self.sans_family.currentFont().family())) c.set('mono_family', unicode(self.mono_family.currentFont().family())) c.set('default_font_size', self.default_font_size.value()) c.set('minimum_font_size', self.minimum_font_size.value()) c.set('mono_font_size', self.mono_font_size.value()) c.set('standard_font', {0:'serif', 1:'sans', 2:'mono'}[ self.standard_font.currentIndex()]) c.set('user_css', unicode(self.css.toPlainText())) c.set('remember_window_size', self.opt_remember_window_size.isChecked()) c.set('fit_images', self.opt_fit_images.isChecked()) c.set('max_fs_width', int(self.max_fs_width.value())) max_fs_height = self.max_fs_height.value() if max_fs_height <= self.max_fs_height.minimum(): max_fs_height = -1 c.set('max_fs_height', max_fs_height) c.set('hyphenate', self.hyphenate.isChecked()) c.set('remember_current_page', self.opt_remember_current_page.isChecked()) c.set('copy_bookmarks_to_file', self.opt_copy_bookmarks_to_file.isChecked()) c.set('wheel_flips_pages', self.opt_wheel_flips_pages.isChecked()) c.set('tap_flips_pages', self.opt_tap_flips_pages.isChecked()) c.set('page_flip_duration', self.opt_page_flip_duration.value()) c.set('font_magnification_step', float(self.opt_font_mag_step.value())/100.) idx = self.hyphenate_default_lang.currentIndex() c.set('hyphenate_default_lang', self.hyphenate_default_lang.itemData(idx)) c.set('line_scrolling_stops_on_pagebreaks', self.opt_line_scrolling_stops_on_pagebreaks.isChecked()) c.set('search_online_url', self.search_online_url.text().strip()) c.set('fullscreen_clock', self.opt_fullscreen_clock.isChecked()) c.set('fullscreen_pos', self.opt_fullscreen_pos.isChecked()) c.set('fullscreen_scrollbar', self.opt_fullscreen_scrollbar.isChecked()) c.set('show_fullscreen_help', self.opt_show_fullscreen_help.isChecked()) c.set('cols_per_screen_migrated', True) c.set('cols_per_screen_portrait', int(self.opt_cols_per_screen_portrait.value())) c.set('cols_per_screen_landscape', int(self.opt_cols_per_screen_landscape.value())) c.set('start_in_fullscreen', self.opt_start_in_fullscreen.isChecked()) c.set('use_book_margins', not self.opt_override_book_margins.isChecked()) c.set('text_color', self.current_text_color) c.set('background_color', self.current_background_color) c.set('show_controls', self.opt_show_controls.isChecked()) for x in ('top', 'bottom', 'side'): c.set(x+'_margin', int(getattr(self, 'opt_%s_margin'%x).value())) from calibre.gui2.viewer.main import dprefs dprefs['word_lookups'] = self.word_lookups
gpl-3.0
nzavagli/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Pygments-2.0.2/pygments/formatters/latex.py
72
17615
# -*- coding: utf-8 -*- """ pygments.formatters.latex ~~~~~~~~~~~~~~~~~~~~~~~~~ Formatter for LaTeX fancyvrb output. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import division from pygments.formatter import Formatter from pygments.lexer import Lexer from pygments.token import Token, STANDARD_TYPES from pygments.util import get_bool_opt, get_int_opt, StringIO, xrange, \ iteritems __all__ = ['LatexFormatter'] def escape_tex(text, commandprefix): return text.replace('\\', '\x00'). \ replace('{', '\x01'). \ replace('}', '\x02'). \ replace('\x00', r'\%sZbs{}' % commandprefix). \ replace('\x01', r'\%sZob{}' % commandprefix). \ replace('\x02', r'\%sZcb{}' % commandprefix). \ replace('^', r'\%sZca{}' % commandprefix). \ replace('_', r'\%sZus{}' % commandprefix). \ replace('&', r'\%sZam{}' % commandprefix). \ replace('<', r'\%sZlt{}' % commandprefix). \ replace('>', r'\%sZgt{}' % commandprefix). \ replace('#', r'\%sZsh{}' % commandprefix). \ replace('%', r'\%sZpc{}' % commandprefix). \ replace('$', r'\%sZdl{}' % commandprefix). \ replace('-', r'\%sZhy{}' % commandprefix). \ replace("'", r'\%sZsq{}' % commandprefix). \ replace('"', r'\%sZdq{}' % commandprefix). \ replace('~', r'\%sZti{}' % commandprefix) DOC_TEMPLATE = r''' \documentclass{%(docclass)s} \usepackage{fancyvrb} \usepackage{color} \usepackage[%(encoding)s]{inputenc} %(preamble)s %(styledefs)s \begin{document} \section*{%(title)s} %(code)s \end{document} ''' ## Small explanation of the mess below :) # # The previous version of the LaTeX formatter just assigned a command to # each token type defined in the current style. That obviously is # problematic if the highlighted code is produced for a different style # than the style commands themselves. # # This version works much like the HTML formatter which assigns multiple # CSS classes to each <span> tag, from the most specific to the least # specific token type, thus falling back to the parent token type if one # is not defined. Here, the classes are there too and use the same short # forms given in token.STANDARD_TYPES. # # Highlighted code now only uses one custom command, which by default is # \PY and selectable by the commandprefix option (and in addition the # escapes \PYZat, \PYZlb and \PYZrb which haven't been renamed for # backwards compatibility purposes). # # \PY has two arguments: the classes, separated by +, and the text to # render in that style. The classes are resolved into the respective # style commands by magic, which serves to ignore unknown classes. # # The magic macros are: # * \PY@it, \PY@bf, etc. are unconditionally wrapped around the text # to render in \PY@do. Their definition determines the style. # * \PY@reset resets \PY@it etc. to do nothing. # * \PY@toks parses the list of classes, using magic inspired by the # keyval package (but modified to use plusses instead of commas # because fancyvrb redefines commas inside its environments). # * \PY@tok processes one class, calling the \PY@tok@classname command # if it exists. # * \PY@tok@classname sets the \PY@it etc. to reflect the chosen style # for its class. # * \PY resets the style, parses the classnames and then calls \PY@do. # # Tip: to read this code, print it out in substituted form using e.g. # >>> print STYLE_TEMPLATE % {'cp': 'PY'} STYLE_TEMPLATE = r''' \makeatletter \def\%(cp)s@reset{\let\%(cp)s@it=\relax \let\%(cp)s@bf=\relax%% \let\%(cp)s@ul=\relax \let\%(cp)s@tc=\relax%% \let\%(cp)s@bc=\relax \let\%(cp)s@ff=\relax} \def\%(cp)s@tok#1{\csname %(cp)s@tok@#1\endcsname} \def\%(cp)s@toks#1+{\ifx\relax#1\empty\else%% \%(cp)s@tok{#1}\expandafter\%(cp)s@toks\fi} \def\%(cp)s@do#1{\%(cp)s@bc{\%(cp)s@tc{\%(cp)s@ul{%% \%(cp)s@it{\%(cp)s@bf{\%(cp)s@ff{#1}}}}}}} \def\%(cp)s#1#2{\%(cp)s@reset\%(cp)s@toks#1+\relax+\%(cp)s@do{#2}} %(styles)s \def\%(cp)sZbs{\char`\\} \def\%(cp)sZus{\char`\_} \def\%(cp)sZob{\char`\{} \def\%(cp)sZcb{\char`\}} \def\%(cp)sZca{\char`\^} \def\%(cp)sZam{\char`\&} \def\%(cp)sZlt{\char`\<} \def\%(cp)sZgt{\char`\>} \def\%(cp)sZsh{\char`\#} \def\%(cp)sZpc{\char`\%%} \def\%(cp)sZdl{\char`\$} \def\%(cp)sZhy{\char`\-} \def\%(cp)sZsq{\char`\'} \def\%(cp)sZdq{\char`\"} \def\%(cp)sZti{\char`\~} %% for compatibility with earlier versions \def\%(cp)sZat{@} \def\%(cp)sZlb{[} \def\%(cp)sZrb{]} \makeatother ''' def _get_ttype_name(ttype): fname = STANDARD_TYPES.get(ttype) if fname: return fname aname = '' while fname is None: aname = ttype[-1] + aname ttype = ttype.parent fname = STANDARD_TYPES.get(ttype) return fname + aname class LatexFormatter(Formatter): r""" Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages. Without the `full` option, code is formatted as one ``Verbatim`` environment, like this: .. sourcecode:: latex \begin{Verbatim}[commandchars=\\\{\}] \PY{k}{def }\PY{n+nf}{foo}(\PY{n}{bar}): \PY{k}{pass} \end{Verbatim} The special command used here (``\PY``) and all the other macros it needs are output by the `get_style_defs` method. With the `full` option, a complete LaTeX document is output, including the command definitions in the preamble. The `get_style_defs()` method of a `LatexFormatter` returns a string containing ``\def`` commands defining the macros needed inside the ``Verbatim`` environments. Additional options accepted: `style` The style to use, can be a string or a Style subclass (default: ``'default'``). `full` Tells the formatter to output a "full" document, i.e. a complete self-contained document (default: ``False``). `title` If `full` is true, the title that should be used to caption the document (default: ``''``). `docclass` If the `full` option is enabled, this is the document class to use (default: ``'article'``). `preamble` If the `full` option is enabled, this can be further preamble commands, e.g. ``\usepackage`` (default: ``''``). `linenos` If set to ``True``, output line numbers (default: ``False``). `linenostart` The line number for the first line (default: ``1``). `linenostep` If set to a number n > 1, only every nth line number is printed. `verboptions` Additional options given to the Verbatim environment (see the *fancyvrb* docs for possible values) (default: ``''``). `commandprefix` The LaTeX commands used to produce colored output are constructed using this prefix and some letters (default: ``'PY'``). .. versionadded:: 0.7 .. versionchanged:: 0.10 The default is now ``'PY'`` instead of ``'C'``. `texcomments` If set to ``True``, enables LaTeX comment lines. That is, LaTex markup in comment tokens is not escaped so that LaTeX can render it (default: ``False``). .. versionadded:: 1.2 `mathescape` If set to ``True``, enables LaTeX math mode escape in comments. That is, ``'$...$'`` inside a comment will trigger math mode (default: ``False``). .. versionadded:: 1.2 `escapeinside` If set to a string of length 2, enables escaping to LaTeX. Text delimited by these 2 characters is read as LaTeX code and typeset accordingly. It has no effect in string literals. It has no effect in comments if `texcomments` or `mathescape` is set. (default: ``''``). .. versionadded:: 2.0 `envname` Allows you to pick an alternative environment name replacing Verbatim. The alternate environment still has to support Verbatim's option syntax. (default: ``'Verbatim'``). .. versionadded:: 2.0 """ name = 'LaTeX' aliases = ['latex', 'tex'] filenames = ['*.tex'] def __init__(self, **options): Formatter.__init__(self, **options) self.docclass = options.get('docclass', 'article') self.preamble = options.get('preamble', '') self.linenos = get_bool_opt(options, 'linenos', False) self.linenostart = abs(get_int_opt(options, 'linenostart', 1)) self.linenostep = abs(get_int_opt(options, 'linenostep', 1)) self.verboptions = options.get('verboptions', '') self.nobackground = get_bool_opt(options, 'nobackground', False) self.commandprefix = options.get('commandprefix', 'PY') self.texcomments = get_bool_opt(options, 'texcomments', False) self.mathescape = get_bool_opt(options, 'mathescape', False) self.escapeinside = options.get('escapeinside', '') if len(self.escapeinside) == 2: self.left = self.escapeinside[0] self.right = self.escapeinside[1] else: self.escapeinside = '' self.envname = options.get('envname', u'Verbatim') self._create_stylesheet() def _create_stylesheet(self): t2n = self.ttype2name = {Token: ''} c2d = self.cmd2def = {} cp = self.commandprefix def rgbcolor(col): if col: return ','.join(['%.2f' % (int(col[i] + col[i + 1], 16) / 255.0) for i in (0, 2, 4)]) else: return '1,1,1' for ttype, ndef in self.style: name = _get_ttype_name(ttype) cmndef = '' if ndef['bold']: cmndef += r'\let\$$@bf=\textbf' if ndef['italic']: cmndef += r'\let\$$@it=\textit' if ndef['underline']: cmndef += r'\let\$$@ul=\underline' if ndef['roman']: cmndef += r'\let\$$@ff=\textrm' if ndef['sans']: cmndef += r'\let\$$@ff=\textsf' if ndef['mono']: cmndef += r'\let\$$@ff=\textsf' if ndef['color']: cmndef += (r'\def\$$@tc##1{\textcolor[rgb]{%s}{##1}}' % rgbcolor(ndef['color'])) if ndef['border']: cmndef += (r'\def\$$@bc##1{\setlength{\fboxsep}{0pt}' r'\fcolorbox[rgb]{%s}{%s}{\strut ##1}}' % (rgbcolor(ndef['border']), rgbcolor(ndef['bgcolor']))) elif ndef['bgcolor']: cmndef += (r'\def\$$@bc##1{\setlength{\fboxsep}{0pt}' r'\colorbox[rgb]{%s}{\strut ##1}}' % rgbcolor(ndef['bgcolor'])) if cmndef == '': continue cmndef = cmndef.replace('$$', cp) t2n[ttype] = name c2d[name] = cmndef def get_style_defs(self, arg=''): """ Return the command sequences needed to define the commands used to format text in the verbatim environment. ``arg`` is ignored. """ cp = self.commandprefix styles = [] for name, definition in iteritems(self.cmd2def): styles.append(r'\expandafter\def\csname %s@tok@%s\endcsname{%s}' % (cp, name, definition)) return STYLE_TEMPLATE % {'cp': self.commandprefix, 'styles': '\n'.join(styles)} def format_unencoded(self, tokensource, outfile): # TODO: add support for background colors t2n = self.ttype2name cp = self.commandprefix if self.full: realoutfile = outfile outfile = StringIO() outfile.write(u'\\begin{' + self.envname + u'}[commandchars=\\\\\\{\\}') if self.linenos: start, step = self.linenostart, self.linenostep outfile.write(u',numbers=left' + (start and u',firstnumber=%d' % start or u'') + (step and u',stepnumber=%d' % step or u'')) if self.mathescape or self.texcomments or self.escapeinside: outfile.write(u',codes={\\catcode`\\$=3\\catcode`\\^=7\\catcode`\\_=8}') if self.verboptions: outfile.write(u',' + self.verboptions) outfile.write(u']\n') for ttype, value in tokensource: if ttype in Token.Comment: if self.texcomments: # Try to guess comment starting lexeme and escape it ... start = value[0:1] for i in xrange(1, len(value)): if start[0] != value[i]: break start += value[i] value = value[len(start):] start = escape_tex(start, self.commandprefix) # ... but do not escape inside comment. value = start + value elif self.mathescape: # Only escape parts not inside a math environment. parts = value.split('$') in_math = False for i, part in enumerate(parts): if not in_math: parts[i] = escape_tex(part, self.commandprefix) in_math = not in_math value = '$'.join(parts) elif self.escapeinside: text = value value = '' while len(text) > 0: a, sep1, text = text.partition(self.left) if len(sep1) > 0: b, sep2, text = text.partition(self.right) if len(sep2) > 0: value += escape_tex(a, self.commandprefix) + b else: value += escape_tex(a + sep1 + b, self.commandprefix) else: value = value + escape_tex(a, self.commandprefix) else: value = escape_tex(value, self.commandprefix) elif ttype not in Token.Escape: value = escape_tex(value, self.commandprefix) styles = [] while ttype is not Token: try: styles.append(t2n[ttype]) except KeyError: # not in current style styles.append(_get_ttype_name(ttype)) ttype = ttype.parent styleval = '+'.join(reversed(styles)) if styleval: spl = value.split('\n') for line in spl[:-1]: if line: outfile.write("\\%s{%s}{%s}" % (cp, styleval, line)) outfile.write('\n') if spl[-1]: outfile.write("\\%s{%s}{%s}" % (cp, styleval, spl[-1])) else: outfile.write(value) outfile.write(u'\\end{' + self.envname + u'}\n') if self.full: realoutfile.write(DOC_TEMPLATE % dict(docclass = self.docclass, preamble = self.preamble, title = self.title, encoding = self.encoding or 'utf8', styledefs = self.get_style_defs(), code = outfile.getvalue())) class LatexEmbeddedLexer(Lexer): r""" This lexer takes one lexer as argument, the lexer for the language being formatted, and the left and right delimiters for escaped text. First everything is scanned using the language lexer to obtain strings and comments. All other consecutive tokens are merged and the resulting text is scanned for escaped segments, which are given the Token.Escape type. Finally text that is not escaped is scanned again with the language lexer. """ def __init__(self, left, right, lang, **options): self.left = left self.right = right self.lang = lang Lexer.__init__(self, **options) def get_tokens_unprocessed(self, text): buf = '' idx = 0 for i, t, v in self.lang.get_tokens_unprocessed(text): if t in Token.Comment or t in Token.String: if buf: for x in self.get_tokens_aux(idx, buf): yield x buf = '' yield i, t, v else: if not buf: idx = i buf += v if buf: for x in self.get_tokens_aux(idx, buf): yield x def get_tokens_aux(self, index, text): while text: a, sep1, text = text.partition(self.left) if a: for i, t, v in self.lang.get_tokens_unprocessed(a): yield index + i, t, v index += len(a) if sep1: b, sep2, text = text.partition(self.right) if sep2: yield index + len(sep1), Token.Escape, b index += len(sep1) + len(b) + len(sep2) else: yield index, Token.Error, sep1 index += len(sep1) text = b
mit
kemalakyol48/python-for-android
python3-alpha/python3-src/Lib/unittest/test/test_discovery.py
785
13838
import os import re import sys import unittest class TestableTestProgram(unittest.TestProgram): module = '__main__' exit = True defaultTest = failfast = catchbreak = buffer = None verbosity = 1 progName = '' testRunner = testLoader = None def __init__(self): pass class TestDiscovery(unittest.TestCase): # Heavily mocked tests so I can avoid hitting the filesystem def test_get_name_from_path(self): loader = unittest.TestLoader() loader._top_level_dir = '/foo' name = loader._get_name_from_path('/foo/bar/baz.py') self.assertEqual(name, 'bar.baz') if not __debug__: # asserts are off return with self.assertRaises(AssertionError): loader._get_name_from_path('/bar/baz.py') def test_find_tests(self): loader = unittest.TestLoader() original_listdir = os.listdir def restore_listdir(): os.listdir = original_listdir original_isfile = os.path.isfile def restore_isfile(): os.path.isfile = original_isfile original_isdir = os.path.isdir def restore_isdir(): os.path.isdir = original_isdir path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir', 'test.foo', 'test-not-a-module.py', 'another_dir'], ['test3.py', 'test4.py', ]] os.listdir = lambda path: path_lists.pop(0) self.addCleanup(restore_listdir) def isdir(path): return path.endswith('dir') os.path.isdir = isdir self.addCleanup(restore_isdir) def isfile(path): # another_dir is not a package and so shouldn't be recursed into return not path.endswith('dir') and not 'another_dir' in path os.path.isfile = isfile self.addCleanup(restore_isfile) loader._get_module_from_name = lambda path: path + ' module' loader.loadTestsFromModule = lambda module: module + ' tests' top_level = os.path.abspath('/foo') loader._top_level_dir = top_level suite = list(loader._find_tests(top_level, 'test*.py')) expected = [name + ' module tests' for name in ('test1', 'test2')] expected.extend([('test_dir.%s' % name) + ' module tests' for name in ('test3', 'test4')]) self.assertEqual(suite, expected) def test_find_tests_with_package(self): loader = unittest.TestLoader() original_listdir = os.listdir def restore_listdir(): os.listdir = original_listdir original_isfile = os.path.isfile def restore_isfile(): os.path.isfile = original_isfile original_isdir = os.path.isdir def restore_isdir(): os.path.isdir = original_isdir directories = ['a_directory', 'test_directory', 'test_directory2'] path_lists = [directories, [], [], []] os.listdir = lambda path: path_lists.pop(0) self.addCleanup(restore_listdir) os.path.isdir = lambda path: True self.addCleanup(restore_isdir) os.path.isfile = lambda path: os.path.basename(path) not in directories self.addCleanup(restore_isfile) class Module(object): paths = [] load_tests_args = [] def __init__(self, path): self.path = path self.paths.append(path) if os.path.basename(path) == 'test_directory': def load_tests(loader, tests, pattern): self.load_tests_args.append((loader, tests, pattern)) return 'load_tests' self.load_tests = load_tests def __eq__(self, other): return self.path == other.path loader._get_module_from_name = lambda name: Module(name) def loadTestsFromModule(module, use_load_tests): if use_load_tests: raise self.failureException('use_load_tests should be False for packages') return module.path + ' module tests' loader.loadTestsFromModule = loadTestsFromModule loader._top_level_dir = '/foo' # this time no '.py' on the pattern so that it can match # a test package suite = list(loader._find_tests('/foo', 'test*')) # We should have loaded tests from the test_directory package by calling load_tests # and directly from the test_directory2 package self.assertEqual(suite, ['load_tests', 'test_directory2' + ' module tests']) self.assertEqual(Module.paths, ['test_directory', 'test_directory2']) # load_tests should have been called once with loader, tests and pattern self.assertEqual(Module.load_tests_args, [(loader, 'test_directory' + ' module tests', 'test*')]) def test_discover(self): loader = unittest.TestLoader() original_isfile = os.path.isfile original_isdir = os.path.isdir def restore_isfile(): os.path.isfile = original_isfile os.path.isfile = lambda path: False self.addCleanup(restore_isfile) orig_sys_path = sys.path[:] def restore_path(): sys.path[:] = orig_sys_path self.addCleanup(restore_path) full_path = os.path.abspath(os.path.normpath('/foo')) with self.assertRaises(ImportError): loader.discover('/foo/bar', top_level_dir='/foo') self.assertEqual(loader._top_level_dir, full_path) self.assertIn(full_path, sys.path) os.path.isfile = lambda path: True os.path.isdir = lambda path: True def restore_isdir(): os.path.isdir = original_isdir self.addCleanup(restore_isdir) _find_tests_args = [] def _find_tests(start_dir, pattern): _find_tests_args.append((start_dir, pattern)) return ['tests'] loader._find_tests = _find_tests loader.suiteClass = str suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar') top_level_dir = os.path.abspath('/foo/bar') start_dir = os.path.abspath('/foo/bar/baz') self.assertEqual(suite, "['tests']") self.assertEqual(loader._top_level_dir, top_level_dir) self.assertEqual(_find_tests_args, [(start_dir, 'pattern')]) self.assertIn(top_level_dir, sys.path) def test_discover_with_modules_that_fail_to_import(self): loader = unittest.TestLoader() listdir = os.listdir os.listdir = lambda _: ['test_this_does_not_exist.py'] isfile = os.path.isfile os.path.isfile = lambda _: True orig_sys_path = sys.path[:] def restore(): os.path.isfile = isfile os.listdir = listdir sys.path[:] = orig_sys_path self.addCleanup(restore) suite = loader.discover('.') self.assertIn(os.getcwd(), sys.path) self.assertEqual(suite.countTestCases(), 1) test = list(list(suite)[0])[0] # extract test from suite with self.assertRaises(ImportError): test.test_this_does_not_exist() def test_command_line_handling_parseArgs(self): program = TestableTestProgram() args = [] def do_discovery(argv): args.extend(argv) program._do_discovery = do_discovery program.parseArgs(['something', 'discover']) self.assertEqual(args, []) program.parseArgs(['something', 'discover', 'foo', 'bar']) self.assertEqual(args, ['foo', 'bar']) def test_command_line_handling_discover_by_default(self): program = TestableTestProgram() program.module = None self.called = False def do_discovery(argv): self.called = True self.assertEqual(argv, []) program._do_discovery = do_discovery program.parseArgs(['something']) self.assertTrue(self.called) def test_command_line_handling_discover_by_default_with_options(self): program = TestableTestProgram() program.module = None args = ['something', '-v', '-b', '-v', '-c', '-f'] self.called = False def do_discovery(argv): self.called = True self.assertEqual(argv, args[1:]) program._do_discovery = do_discovery program.parseArgs(args) self.assertTrue(self.called) def test_command_line_handling_do_discovery_too_many_arguments(self): class Stop(Exception): pass def usageExit(): raise Stop program = TestableTestProgram() program.usageExit = usageExit with self.assertRaises(Stop): # too many args program._do_discovery(['one', 'two', 'three', 'four']) def test_command_line_handling_do_discovery_calls_loader(self): program = TestableTestProgram() class Loader(object): args = [] def discover(self, start_dir, pattern, top_level_dir): self.args.append((start_dir, pattern, top_level_dir)) return 'tests' program._do_discovery(['-v'], Loader=Loader) self.assertEqual(program.verbosity, 2) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['--verbose'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery([], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['fish', 'eggs'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'eggs', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['-s', 'fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'test*.py', None)]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['-t', 'fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')]) Loader.args = [] program = TestableTestProgram() program._do_discovery(['-p', 'fish'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('.', 'fish', None)]) self.assertFalse(program.failfast) self.assertFalse(program.catchbreak) Loader.args = [] program = TestableTestProgram() program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v', '-f', '-c'], Loader=Loader) self.assertEqual(program.test, 'tests') self.assertEqual(Loader.args, [('fish', 'eggs', None)]) self.assertEqual(program.verbosity, 2) self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) def test_detect_module_clash(self): class Module(object): __file__ = 'bar/foo.py' sys.modules['foo'] = Module full_path = os.path.abspath('foo') original_listdir = os.listdir original_isfile = os.path.isfile original_isdir = os.path.isdir def cleanup(): os.listdir = original_listdir os.path.isfile = original_isfile os.path.isdir = original_isdir del sys.modules['foo'] if full_path in sys.path: sys.path.remove(full_path) self.addCleanup(cleanup) def listdir(_): return ['foo.py'] def isfile(_): return True def isdir(_): return True os.listdir = listdir os.path.isfile = isfile os.path.isdir = isdir loader = unittest.TestLoader() mod_dir = os.path.abspath('bar') expected_dir = os.path.abspath('foo') msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. " "Is this module globally installed?" % (mod_dir, expected_dir)) self.assertRaisesRegex( ImportError, '^%s$' % msg, loader.discover, start_dir='foo', pattern='foo.py' ) self.assertEqual(sys.path[0], full_path) def test_discovery_from_dotted_path(self): loader = unittest.TestLoader() tests = [self] expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) self.wasRun = False def _find_tests(start_dir, pattern): self.wasRun = True self.assertEqual(start_dir, expectedPath) return tests loader._find_tests = _find_tests suite = loader.discover('unittest.test') self.assertTrue(self.wasRun) self.assertEqual(suite._tests, tests) if __name__ == '__main__': unittest.main()
apache-2.0
chengjf/database-interface-doc-management
flask-demo/flask/Lib/site-packages/pip/_vendor/requests/packages/urllib3/response.py
478
16459
try: import http.client as httplib except ImportError: import httplib import zlib import io from socket import timeout as SocketTimeout from ._collections import HTTPHeaderDict from .exceptions import ( ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked ) from .packages.six import string_types as basestring, binary_type, PY3 from .connection import HTTPException, BaseSSLError from .util.response import is_fp_closed class DeflateDecoder(object): def __init__(self): self._first_try = True self._data = binary_type() self._obj = zlib.decompressobj() def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data if not self._first_try: return self._obj.decompress(data) self._data += data try: return self._obj.decompress(data) except zlib.error: self._first_try = False self._obj = zlib.decompressobj(-zlib.MAX_WBITS) try: return self.decompress(self._data) finally: self._data = None class GzipDecoder(object): def __init__(self): self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data return self._obj.decompress(data) def _get_decoder(mode): if mode == 'gzip': return GzipDecoder() return DeflateDecoder() class HTTPResponse(io.IOBase): """ HTTP Response container. Backwards-compatible to httplib's HTTPResponse but the response ``body`` is loaded and decoded on-demand when the ``data`` property is accessed. This class is also compatible with the Python standard library's :mod:`io` module, and can hence be treated as a readable object in the context of that framework. Extra parameters for behaviour not present in httplib.HTTPResponse: :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, attempts to decode specific content-encoding's based on headers (like 'gzip' and 'deflate') will be skipped and raw data will be used instead. :param original_response: When this HTTPResponse wrapper is generated from an httplib.HTTPResponse object, it's convenient to include the original for debug purposes. It's otherwise unused. """ CONTENT_DECODERS = ['gzip', 'deflate'] REDIRECT_STATUSES = [301, 302, 303, 307, 308] def __init__(self, body='', headers=None, status=0, version=0, reason=None, strict=0, preload_content=True, decode_content=True, original_response=None, pool=None, connection=None): if isinstance(headers, HTTPHeaderDict): self.headers = headers else: self.headers = HTTPHeaderDict(headers) self.status = status self.version = version self.reason = reason self.strict = strict self.decode_content = decode_content self._decoder = None self._body = None self._fp = None self._original_response = original_response self._fp_bytes_read = 0 if body and isinstance(body, (basestring, binary_type)): self._body = body self._pool = pool self._connection = connection if hasattr(body, 'read'): self._fp = body # Are we using the chunked-style of transfer encoding? self.chunked = False self.chunk_left = None tr_enc = self.headers.get('transfer-encoding', '').lower() # Don't incur the penalty of creating a list and then discarding it encodings = (enc.strip() for enc in tr_enc.split(",")) if "chunked" in encodings: self.chunked = True # We certainly don't want to preload content when the response is chunked. if not self.chunked and preload_content and not self._body: self._body = self.read(decode_content=decode_content) def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get('location') return False def release_conn(self): if not self._pool or not self._connection: return self._pool._put_conn(self._connection) self._connection = None @property def data(self): # For backwords-compat with earlier urllib3 0.4 and earlier. if self._body: return self._body if self._fp: return self.read(cache_content=True) def tell(self): """ Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). """ return self._fp_bytes_read def _init_decoder(self): """ Set-up the _decoder attribute if necessar. """ # Note: content-encoding value should be case-insensitive, per RFC 7230 # Section 3.2 content_encoding = self.headers.get('content-encoding', '').lower() if self._decoder is None and content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) def _decode(self, data, decode_content, flush_decoder): """ Decode the data passed in and potentially flush the decoder. """ try: if decode_content and self._decoder: data = self._decoder.decompress(data) except (IOError, zlib.error) as e: content_encoding = self.headers.get('content-encoding', '').lower() raise DecodeError( "Received response with content-encoding: %s, but " "failed to decode it." % content_encoding, e) if flush_decoder and decode_content and self._decoder: buf = self._decoder.decompress(binary_type()) data += buf + self._decoder.flush() return data def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) """ self._init_decoder() if decode_content is None: decode_content = self.decode_content if self._fp is None: return flush_decoder = False try: try: if amt is None: # cStringIO doesn't like amt=None data = self._fp.read() flush_decoder = True else: cache_content = False data = self._fp.read(amt) if amt != 0 and not data: # Platform-specific: Buggy versions of Python. # Close the connection when no data is returned # # This is redundant to what httplib/http.client _should_ # already do. However, versions of python released before # December 15, 2012 (http://bugs.python.org/issue16298) do # not properly close the connection in all cases. There is # no harm in redundantly calling close. self._fp.close() flush_decoder = True except SocketTimeout: # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but # there is yet no clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if 'read operation timed out' not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise raise ReadTimeoutError(self._pool, None, 'Read timed out.') except HTTPException as e: # This includes IncompleteRead. raise ProtocolError('Connection broken: %r' % e, e) self._fp_bytes_read += len(data) data = self._decode(data, decode_content, flush_decoder) if cache_content: self._body = data return data finally: if self._original_response and self._original_response.isclosed(): self.release_conn() def stream(self, amt=2**16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ if self.chunked: for line in self.read_chunked(amt, decode_content=decode_content): yield line else: while not is_fp_closed(self._fp): data = self.read(amt=amt, decode_content=decode_content) if data: yield data @classmethod def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if PY3: # Python 3 headers = HTTPHeaderDict(headers.items()) else: # Python 2 headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) resp = ResponseCls(body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw) return resp # Backwards-compatibility methods for httplib.HTTPResponse def getheaders(self): return self.headers def getheader(self, name, default=None): return self.headers.get(name, default) # Overrides from io.IOBase def close(self): if not self.closed: self._fp.close() @property def closed(self): if self._fp is None: return True elif hasattr(self._fp, 'closed'): return self._fp.closed elif hasattr(self._fp, 'isclosed'): # Python 2 return self._fp.isclosed() else: return True def fileno(self): if self._fp is None: raise IOError("HTTPResponse has no file to get a fileno from") elif hasattr(self._fp, "fileno"): return self._fp.fileno() else: raise IOError("The file-like object this HTTPResponse is wrapped " "around has no file descriptor") def flush(self): if self._fp is not None and hasattr(self._fp, 'flush'): return self._fp.flush() def readable(self): # This method is required for `io` module compatibility. return True def readinto(self, b): # This method is required for `io` module compatibility. temp = self.read(len(b)) if len(temp) == 0: return 0 else: b[:len(temp)] = temp return len(temp) def _update_chunk_length(self): # First, we'll figure out length of a chunk and then # we'll try to read it from socket. if self.chunk_left is not None: return line = self._fp.fp.readline() line = line.split(b';', 1)[0] try: self.chunk_left = int(line, 16) except ValueError: # Invalid chunked protocol response, abort. self.close() raise httplib.IncompleteRead(line) def _handle_chunk(self, amt): returned_chunk = None if amt is None: chunk = self._fp._safe_read(self.chunk_left) returned_chunk = chunk self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None elif amt < self.chunk_left: value = self._fp._safe_read(amt) self.chunk_left = self.chunk_left - amt returned_chunk = value elif amt == self.chunk_left: value = self._fp._safe_read(amt) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None returned_chunk = value else: # amt > self.chunk_left returned_chunk = self._fp._safe_read(self.chunk_left) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None return returned_chunk def read_chunked(self, amt=None, decode_content=None): """ Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ self._init_decoder() # FIXME: Rewrite this method and make it a class with a better structured logic. if not self.chunked: raise ResponseNotChunked("Response is not chunked. " "Header 'transfer-encoding: chunked' is missing.") if self._original_response and self._original_response._method.upper() == 'HEAD': # Don't bother reading the body of a HEAD request. # FIXME: Can we do this somehow without accessing private httplib _method? self._original_response.close() return while True: self._update_chunk_length() if self.chunk_left == 0: break chunk = self._handle_chunk(amt) yield self._decode(chunk, decode_content=decode_content, flush_decoder=True) # Chunk content ends with \r\n: discard it. while True: line = self._fp.fp.readline() if not line: # Some sites may not end with '\r\n'. break if line == b'\r\n': break # We read everything; close the "file". if self._original_response: self._original_response.close() self.release_conn()
apache-2.0
adazey/Muzez
libs/youtube_dl/extractor/msn.py
17
4643
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import compat_str from ..utils import ( determine_ext, ExtractorError, int_or_none, unescapeHTML, ) class MSNIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?msn\.com/(?:[^/]+/)+(?P<display_id>[^/]+)/[a-z]{2}-(?P<id>[\da-zA-Z]+)' _TESTS = [{ 'url': 'http://www.msn.com/en-ae/foodanddrink/joinourtable/criminal-minds-shemar-moore-shares-a-touching-goodbye-message/vp-BBqQYNE', 'md5': '8442f66c116cbab1ff7098f986983458', 'info_dict': { 'id': 'BBqQYNE', 'display_id': 'criminal-minds-shemar-moore-shares-a-touching-goodbye-message', 'ext': 'mp4', 'title': 'Criminal Minds - Shemar Moore Shares A Touching Goodbye Message', 'description': 'md5:e8e89b897b222eb33a6b5067a8f1bc25', 'duration': 104, 'uploader': 'CBS Entertainment', 'uploader_id': 'IT0X5aoJ6bJgYerJXSDCgFmYPB1__54v', }, }, { 'url': 'http://www.msn.com/en-ae/news/offbeat/meet-the-nine-year-old-self-made-millionaire/ar-BBt6ZKf', 'only_matching': True, }, { 'url': 'http://www.msn.com/en-ae/video/watch/obama-a-lot-of-people-will-be-disappointed/vi-AAhxUMH', 'only_matching': True, }, { # geo restricted 'url': 'http://www.msn.com/en-ae/foodanddrink/joinourtable/the-first-fart-makes-you-laugh-the-last-fart-makes-you-cry/vp-AAhzIBU', 'only_matching': True, }, { 'url': 'http://www.msn.com/en-ae/entertainment/bollywood/watch-how-salman-khan-reacted-when-asked-if-he-would-apologize-for-his-‘raped-woman’-comment/vi-AAhvzW6', 'only_matching': True, }] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id, display_id = mobj.group('id', 'display_id') webpage = self._download_webpage(url, display_id) video = self._parse_json( self._search_regex( r'data-metadata\s*=\s*(["\'])(?P<data>.+?)\1', webpage, 'video data', default='{}', group='data'), display_id, transform_source=unescapeHTML) if not video: error = unescapeHTML(self._search_regex( r'data-error=(["\'])(?P<error>.+?)\1', webpage, 'error', group='error')) raise ExtractorError('%s said: %s' % (self.IE_NAME, error), expected=True) title = video['title'] formats = [] for file_ in video.get('videoFiles', []): format_url = file_.get('url') if not format_url: continue ext = determine_ext(format_url) if ext == 'ism': formats.extend(self._extract_ism_formats( format_url + '/Manifest', display_id, 'mss', fatal=False)) if 'm3u8' in format_url: # m3u8_native should not be used here until # https://github.com/rg3/youtube-dl/issues/9913 is fixed m3u8_formats = self._extract_m3u8_formats( format_url, display_id, 'mp4', m3u8_id='hls', fatal=False) formats.extend(m3u8_formats) else: formats.append({ 'url': format_url, 'ext': 'mp4', 'format_id': 'http', 'width': int_or_none(file_.get('width')), 'height': int_or_none(file_.get('height')), }) self._sort_formats(formats) subtitles = {} for file_ in video.get('files', []): format_url = file_.get('url') format_code = file_.get('formatCode') if not format_url or not format_code: continue if compat_str(format_code) == '3100': subtitles.setdefault(file_.get('culture', 'en'), []).append({ 'ext': determine_ext(format_url, 'ttml'), 'url': format_url, }) return { 'id': video_id, 'display_id': display_id, 'title': title, 'description': video.get('description'), 'thumbnail': video.get('headlineImage', {}).get('url'), 'duration': int_or_none(video.get('durationSecs')), 'uploader': video.get('sourceFriendly'), 'uploader_id': video.get('providerId'), 'creator': video.get('creator'), 'subtitles': subtitles, 'formats': formats, }
gpl-3.0
yhoshino11/GuestBook
.venv/lib/python2.7/site-packages/pip/baseparser.py
149
9643
"""Base option parser setup""" from __future__ import absolute_import import sys import optparse import os import re import textwrap from distutils.util import strtobool from pip._vendor.six import string_types from pip._vendor.six.moves import configparser from pip.locations import ( legacy_config_file, config_basename, running_under_virtualenv, site_config_files ) from pip.utils import appdirs, get_terminal_size _environ_prefix_re = re.compile(r"^PIP_", re.I) class PrettyHelpFormatter(optparse.IndentedHelpFormatter): """A prettier/less verbose help formatter for optparse.""" def __init__(self, *args, **kwargs): # help position must be aligned with __init__.parseopts.description kwargs['max_help_position'] = 30 kwargs['indent_increment'] = 1 kwargs['width'] = get_terminal_size()[0] - 2 optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs) def format_option_strings(self, option): return self._format_option_strings(option, ' <%s>', ', ') def _format_option_strings(self, option, mvarfmt=' <%s>', optsep=', '): """ Return a comma-separated list of option strings and metavars. :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') :param mvarfmt: metavar format string - evaluated as mvarfmt % metavar :param optsep: separator """ opts = [] if option._short_opts: opts.append(option._short_opts[0]) if option._long_opts: opts.append(option._long_opts[0]) if len(opts) > 1: opts.insert(1, optsep) if option.takes_value(): metavar = option.metavar or option.dest.lower() opts.append(mvarfmt % metavar.lower()) return ''.join(opts) def format_heading(self, heading): if heading == 'Options': return '' return heading + ':\n' def format_usage(self, usage): """ Ensure there is only one newline between usage and the first heading if there is no description. """ msg = '\nUsage: %s\n' % self.indent_lines(textwrap.dedent(usage), " ") return msg def format_description(self, description): # leave full control over description to us if description: if hasattr(self.parser, 'main'): label = 'Commands' else: label = 'Description' # some doc strings have initial newlines, some don't description = description.lstrip('\n') # some doc strings have final newlines and spaces, some don't description = description.rstrip() # dedent, then reindent description = self.indent_lines(textwrap.dedent(description), " ") description = '%s:\n%s\n' % (label, description) return description else: return '' def format_epilog(self, epilog): # leave full control over epilog to us if epilog: return epilog else: return '' def indent_lines(self, text, indent): new_lines = [indent + line for line in text.split('\n')] return "\n".join(new_lines) class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter): """Custom help formatter for use in ConfigOptionParser that updates the defaults before expanding them, allowing them to show up correctly in the help listing""" def expand_default(self, option): if self.parser is not None: self.parser.update_defaults(self.parser.defaults) return optparse.IndentedHelpFormatter.expand_default(self, option) class CustomOptionParser(optparse.OptionParser): def insert_option_group(self, idx, *args, **kwargs): """Insert an OptionGroup at a given position.""" group = self.add_option_group(*args, **kwargs) self.option_groups.pop() self.option_groups.insert(idx, group) return group @property def option_list_all(self): """Get a list of all options, including those in option groups.""" res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list) return res class ConfigOptionParser(CustomOptionParser): """Custom option parser which updates its defaults by checking the configuration files and environmental variables""" isolated = False def __init__(self, *args, **kwargs): self.config = configparser.RawConfigParser() self.name = kwargs.pop('name') self.isolated = kwargs.pop("isolated", False) self.files = self.get_config_files() if self.files: self.config.read(self.files) assert self.name optparse.OptionParser.__init__(self, *args, **kwargs) def get_config_files(self): # the files returned by this method will be parsed in order with the # first files listed being overridden by later files in standard # ConfigParser fashion config_file = os.environ.get('PIP_CONFIG_FILE', False) if config_file == os.devnull: return [] # at the base we have any site-wide configuration files = list(site_config_files) # per-user configuration next if not self.isolated: if config_file and os.path.exists(config_file): files.append(config_file) else: # This is the legacy config file, we consider it to be a lower # priority than the new file location. files.append(legacy_config_file) # This is the new config file, we consider it to be a higher # priority than the legacy file. files.append( os.path.join( appdirs.user_config_dir("pip"), config_basename, ) ) # finally virtualenv configuration first trumping others if running_under_virtualenv(): venv_config_file = os.path.join( sys.prefix, config_basename, ) if os.path.exists(venv_config_file): files.append(venv_config_file) return files def check_default(self, option, key, val): try: return option.check_value(key, val) except optparse.OptionValueError as exc: print("An error occurred during configuration: %s" % exc) sys.exit(3) def update_defaults(self, defaults): """Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).""" # Then go and look for the other sources of configuration: config = {} # 1. config files for section in ('global', self.name): config.update( self.normalize_keys(self.get_config_section(section)) ) # 2. environmental variables if not self.isolated: config.update(self.normalize_keys(self.get_environ_vars())) # Then set the options with those values for key, val in config.items(): option = self.get_option(key) if option is not None: # ignore empty values if not val: continue if option.action in ('store_true', 'store_false', 'count'): val = strtobool(val) if option.action == 'append': val = val.split() val = [self.check_default(option, key, v) for v in val] else: val = self.check_default(option, key, val) defaults[option.dest] = val return defaults def normalize_keys(self, items): """Return a config dictionary with normalized keys regardless of whether the keys were specified in environment variables or in config files""" normalized = {} for key, val in items: key = key.replace('_', '-') if not key.startswith('--'): key = '--%s' % key # only prefer long opts normalized[key] = val return normalized def get_config_section(self, name): """Get a section of a configuration""" if self.config.has_section(name): return self.config.items(name) return [] def get_environ_vars(self): """Returns a generator with all environmental vars with prefix PIP_""" for key, val in os.environ.items(): if _environ_prefix_re.search(key): yield (_environ_prefix_re.sub("", key).lower(), val) def get_default_values(self): """Overridding to make updating the defaults after instantiation of the option parser possible, update_defaults() does the dirty work.""" if not self.process_default_values: # Old, pre-Optik 1.5 behaviour. return optparse.Values(self.defaults) defaults = self.update_defaults(self.defaults.copy()) # ours for option in self._get_all_options(): default = defaults.get(option.dest) if isinstance(default, string_types): opt_str = option.get_opt_string() defaults[option.dest] = option.check_value(opt_str, default) return optparse.Values(defaults) def error(self, msg): self.print_usage(sys.stderr) self.exit(2, "%s\n" % msg)
mit
werbk/task-7.22
tests_group/group_lib.py
3
3954
from tests_group.group_helper import Group def clean(group): return Group(id=group.id, group_name=group.group_name.strip()) class GroupBase: def __init__(self, app): self.app = app def open_group_page(self): wd = self.app.wd if not (wd.current_url.endswith('/group.php') and len(wd.find_elements_by_name('new')) > 0): wd.find_element_by_link_text("groups").click() def count(self): wd = self.app.wd self.open_group_page() return len(wd.find_elements_by_name("selected[]")) def validation_of_group_exist(self): if self.count() == 0: self.create(Group(group_name='test')) self.click_group_page() def group_line(self, field, text): wd = self.app.wd if text: wd.find_element_by_name(field).click() wd.find_element_by_name(field).clear() wd.find_element_by_name(field).send_keys(text) def create(self, Group): wd = self.app.wd self.open_group_page() wd.find_element_by_name("new").click() self.group_line('group_name', Group.group_name) self.group_line('group_header', Group.group_header) self.group_line('group_footer', Group.group_footer) wd.find_element_by_name("submit").click() self.group_cache = None def delete_first_group(self): self.delete_group_by_index(0) def click_group_page(self): wd = self.app.wd wd.find_element_by_css_selector("div.msgbox").click() wd.find_element_by_link_text("group page").click() group_cache = None def get_group_list(self): if self.group_cache is None: wd = self.app.wd self.open_group_page() self.group_cache = [] for element in wd.find_elements_by_css_selector('span.group'): text = element.text id = element.find_element_by_name('selected[]').get_attribute('value') self.group_cache.append(Group(group_name=text, id=id)) return list(self.group_cache) def select_group_by_index(self, index): wd = self.app.wd wd.find_elements_by_name("selected[]")[index].click() def delete_group_by_index(self, index): wd = self.app.wd self.open_group_page() self.select_group_by_index(index) wd.find_element_by_name('delete').click() self.click_group_page() self.group_cache = None def edit_group_by_index(self, Group, index): wd = self.app.wd self.open_group_page() wd.find_elements_by_name("selected[]")[index].click() wd.find_element_by_name("edit").click() self.group_line('group_name', Group.group_name) self.group_line('group_header', Group.group_header) self.group_line('group_footer', Group.group_footer) wd.find_element_by_name("update").click() wd.find_element_by_link_text("groups").click() self.group_cache = None def delete_group_by_id(self, id): wd = self.app.wd self.open_group_page() self.select_group_by_id(id) wd.find_element_by_name('delete').click() self.click_group_page() self.group_cache = None def select_group_by_id(self, id): wd = self.app.wd wd.find_element_by_css_selector("input[value='%s']" % id).click() def edit_group_by_id(self, Group, group_id): wd = self.app.wd self.open_group_page() self.select_group_by_id(group_id) wd.find_element_by_xpath("//*[@id='content']//*[@name='edit'][1]").click() self.group_line('group_name', Group.group_name) self.group_line('group_header', Group.group_header) self.group_line('group_footer', Group.group_footer) wd.find_element_by_name("update").click() wd.find_element_by_link_text("groups").click() self.group_cash = None
apache-2.0
ukanga/SickRage
lib/github/InputGitAuthor.py
47
2633
# -*- coding: utf-8 -*- # ########################## Copyrights and license ############################ # # # Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2012 Zearin <zearin@gonk.net> # # Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> # # # # This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ # # # # PyGithub 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 3 of the License, or (at your option) # # any later version. # # # # PyGithub 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 PyGithub. If not, see <http://www.gnu.org/licenses/>. # # # # ############################################################################## import github.GithubObject class InputGitAuthor(object): """ """ def __init__(self, name, email, date=github.GithubObject.NotSet): """ :param name: string :param email: string :param date: string """ assert isinstance(name, (str, unicode)), name assert isinstance(email, (str, unicode)), email assert date is github.GithubObject.NotSet or isinstance(date, (str, unicode)), date # @todo Datetime? self.__name = name self.__email = email self.__date = date @property def _identity(self): identity = { "name": self.__name, "email": self.__email, } if self.__date is not github.GithubObject.NotSet: identity["date"] = self.__date return identity
gpl-3.0
evro/CouchPotatoServer
libs/xmpp/simplexml.py
198
22791
## simplexml.py based on Mattew Allum's xmlstream.py ## ## Copyright (C) 2003-2005 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: simplexml.py,v 1.34 2009/03/03 10:24:02 normanr Exp $ """Simplexml module provides xmpppy library with all needed tools to handle XML nodes and XML streams. I'm personally using it in many other separate projects. It is designed to be as standalone as possible.""" import xml.parsers.expat def XMLescape(txt): """Returns provided string with symbols & < > " replaced by their respective XML entities.""" # replace also FORM FEED and ESC, because they are not valid XML chars return txt.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;").replace(u'\x0C', "").replace(u'\x1B', "") ENCODING='utf-8' def ustr(what): """Converts object "what" to unicode string using it's own __str__ method if accessible or unicode method otherwise.""" if isinstance(what, unicode): return what try: r=what.__str__() except AttributeError: r=str(what) if not isinstance(r, unicode): return unicode(r,ENCODING) return r class Node(object): """ Node class describes syntax of separate XML Node. It have a constructor that permits node creation from set of "namespace name", attributes and payload of text strings and other nodes. It does not natively support building node from text string and uses NodeBuilder class for that purpose. After creation node can be mangled in many ways so it can be completely changed. Also node can be serialised into string in one of two modes: default (where the textual representation of node describes it exactly) and "fancy" - with whitespace added to make indentation and thus make result more readable by human. Node class have attribute FORCE_NODE_RECREATION that is defaults to False thus enabling fast node replication from the some other node. The drawback of the fast way is that new node shares some info with the "original" node that is changing the one node may influence the other. Though it is rarely needed (in xmpppy it is never needed at all since I'm usually never using original node after replication (and using replication only to move upwards on the classes tree). """ FORCE_NODE_RECREATION=0 def __init__(self, tag=None, attrs={}, payload=[], parent=None, nsp=None, node_built=False, node=None): """ Takes "tag" argument as the name of node (prepended by namespace, if needed and separated from it by a space), attrs dictionary as the set of arguments, payload list as the set of textual strings and child nodes that this node carries within itself and "parent" argument that is another node that this one will be the child of. Also the __init__ can be provided with "node" argument that is either a text string containing exactly one node or another Node instance to begin with. If both "node" and other arguments is provided then the node initially created as replica of "node" provided and then modified to be compliant with other arguments.""" if node: if self.FORCE_NODE_RECREATION and isinstance(node, Node): node=str(node) if not isinstance(node, Node): node=NodeBuilder(node,self) node_built = True else: self.name,self.namespace,self.attrs,self.data,self.kids,self.parent,self.nsd = node.name,node.namespace,{},[],[],node.parent,{} for key in node.attrs.keys(): self.attrs[key]=node.attrs[key] for data in node.data: self.data.append(data) for kid in node.kids: self.kids.append(kid) for k,v in node.nsd.items(): self.nsd[k] = v else: self.name,self.namespace,self.attrs,self.data,self.kids,self.parent,self.nsd = 'tag','',{},[],[],None,{} if parent: self.parent = parent self.nsp_cache = {} if nsp: for k,v in nsp.items(): self.nsp_cache[k] = v for attr,val in attrs.items(): if attr == 'xmlns': self.nsd[u''] = val elif attr.startswith('xmlns:'): self.nsd[attr[6:]] = val self.attrs[attr]=attrs[attr] if tag: if node_built: pfx,self.name = (['']+tag.split(':'))[-2:] self.namespace = self.lookup_nsp(pfx) else: if ' ' in tag: self.namespace,self.name = tag.split() else: self.name = tag if isinstance(payload, basestring): payload=[payload] for i in payload: if isinstance(i, Node): self.addChild(node=i) else: self.data.append(ustr(i)) def lookup_nsp(self,pfx=''): ns = self.nsd.get(pfx,None) if ns is None: ns = self.nsp_cache.get(pfx,None) if ns is None: if self.parent: ns = self.parent.lookup_nsp(pfx) self.nsp_cache[pfx] = ns else: return 'http://www.gajim.org/xmlns/undeclared' return ns def __str__(self,fancy=0): """ Method used to dump node into textual representation. if "fancy" argument is set to True produces indented output for readability.""" s = (fancy-1) * 2 * ' ' + "<" + self.name if self.namespace: if not self.parent or self.parent.namespace!=self.namespace: if 'xmlns' not in self.attrs: s = s + ' xmlns="%s"'%self.namespace for key in self.attrs.keys(): val = ustr(self.attrs[key]) s = s + ' %s="%s"' % ( key, XMLescape(val) ) s = s + ">" cnt = 0 if self.kids: if fancy: s = s + "\n" for a in self.kids: if not fancy and (len(self.data)-1)>=cnt: s=s+XMLescape(self.data[cnt]) elif (len(self.data)-1)>=cnt: s=s+XMLescape(self.data[cnt].strip()) if isinstance(a, Node): s = s + a.__str__(fancy and fancy+1) elif a: s = s + a.__str__() cnt=cnt+1 if not fancy and (len(self.data)-1) >= cnt: s = s + XMLescape(self.data[cnt]) elif (len(self.data)-1) >= cnt: s = s + XMLescape(self.data[cnt].strip()) if not self.kids and s.endswith('>'): s=s[:-1]+' />' if fancy: s = s + "\n" else: if fancy and not self.data: s = s + (fancy-1) * 2 * ' ' s = s + "</" + self.name + ">" if fancy: s = s + "\n" return s def getCDATA(self): """ Serialise node, dropping all tags and leaving CDATA intact. That is effectively kills all formatiing, leaving only text were contained in XML. """ s = "" cnt = 0 if self.kids: for a in self.kids: s=s+self.data[cnt] if a: s = s + a.getCDATA() cnt=cnt+1 if (len(self.data)-1) >= cnt: s = s + self.data[cnt] return s def addChild(self, name=None, attrs={}, payload=[], namespace=None, node=None): """ If "node" argument is provided, adds it as child node. Else creates new node from the other arguments' values and adds it as well.""" if 'xmlns' in attrs: raise AttributeError("Use namespace=x instead of attrs={'xmlns':x}") if node: newnode=node node.parent = self else: newnode=Node(tag=name, parent=self, attrs=attrs, payload=payload) if namespace: newnode.setNamespace(namespace) self.kids.append(newnode) self.data.append(u'') return newnode def addData(self, data): """ Adds some CDATA to node. """ self.data.append(ustr(data)) self.kids.append(None) def clearData(self): """ Removes all CDATA from the node. """ self.data=[] def delAttr(self, key): """ Deletes an attribute "key" """ del self.attrs[key] def delChild(self, node, attrs={}): """ Deletes the "node" from the node's childs list, if "node" is an instance. Else deletes the first node that have specified name and (optionally) attributes. """ if not isinstance(node, Node): node=self.getTag(node,attrs) self.kids[self.kids.index(node)]=None return node def getAttrs(self): """ Returns all node's attributes as dictionary. """ return self.attrs def getAttr(self, key): """ Returns value of specified attribute. """ try: return self.attrs[key] except: return None def getChildren(self): """ Returns all node's child nodes as list. """ return self.kids def getData(self): """ Returns all node CDATA as string (concatenated). """ return ''.join(self.data) def getName(self): """ Returns the name of node """ return self.name def getNamespace(self): """ Returns the namespace of node """ return self.namespace def getParent(self): """ Returns the parent of node (if present). """ return self.parent def getPayload(self): """ Return the payload of node i.e. list of child nodes and CDATA entries. F.e. for "<node>text1<nodea/><nodeb/> text2</node>" will be returned list: ['text1', <nodea instance>, <nodeb instance>, ' text2']. """ ret=[] for i in range(max(len(self.data),len(self.kids))): if i < len(self.data) and self.data[i]: ret.append(self.data[i]) if i < len(self.kids) and self.kids[i]: ret.append(self.kids[i]) return ret def getTag(self, name, attrs={}, namespace=None): """ Filters all child nodes using specified arguments as filter. Returns the first found or None if not found. """ return self.getTags(name, attrs, namespace, one=1) def getTagAttr(self,tag,attr): """ Returns attribute value of the child with specified name (or None if no such attribute).""" try: return self.getTag(tag).attrs[attr] except: return None def getTagData(self,tag): """ Returns cocatenated CDATA of the child with specified name.""" try: return self.getTag(tag).getData() except: return None def getTags(self, name, attrs={}, namespace=None, one=0): """ Filters all child nodes using specified arguments as filter. Returns the list of nodes found. """ nodes=[] for node in self.kids: if not node: continue if namespace and namespace!=node.getNamespace(): continue if node.getName() == name: for key in attrs.keys(): if key not in node.attrs or node.attrs[key]!=attrs[key]: break else: nodes.append(node) if one and nodes: return nodes[0] if not one: return nodes def iterTags(self, name, attrs={}, namespace=None): """ Iterate over all children using specified arguments as filter. """ for node in self.kids: if not node: continue if namespace is not None and namespace!=node.getNamespace(): continue if node.getName() == name: for key in attrs.keys(): if key not in node.attrs or \ node.attrs[key]!=attrs[key]: break else: yield node def setAttr(self, key, val): """ Sets attribute "key" with the value "val". """ self.attrs[key]=val def setData(self, data): """ Sets node's CDATA to provided string. Resets all previous CDATA!""" self.data=[ustr(data)] def setName(self,val): """ Changes the node name. """ self.name = val def setNamespace(self, namespace): """ Changes the node namespace. """ self.namespace=namespace def setParent(self, node): """ Sets node's parent to "node". WARNING: do not checks if the parent already present and not removes the node from the list of childs of previous parent. """ self.parent = node def setPayload(self,payload,add=0): """ Sets node payload according to the list specified. WARNING: completely replaces all node's previous content. If you wish just to add child or CDATA - use addData or addChild methods. """ if isinstance(payload, basestring): payload=[payload] if add: self.kids+=payload else: self.kids=payload def setTag(self, name, attrs={}, namespace=None): """ Same as getTag but if the node with specified namespace/attributes not found, creates such node and returns it. """ node=self.getTags(name, attrs, namespace=namespace, one=1) if node: return node else: return self.addChild(name, attrs, namespace=namespace) def setTagAttr(self,tag,attr,val): """ Creates new node (if not already present) with name "tag" and sets it's attribute "attr" to value "val". """ try: self.getTag(tag).attrs[attr]=val except: self.addChild(tag,attrs={attr:val}) def setTagData(self,tag,val,attrs={}): """ Creates new node (if not already present) with name "tag" and (optionally) attributes "attrs" and sets it's CDATA to string "val". """ try: self.getTag(tag,attrs).setData(ustr(val)) except: self.addChild(tag,attrs,payload=[ustr(val)]) def has_attr(self,key): """ Checks if node have attribute "key".""" return key in self.attrs def __getitem__(self,item): """ Returns node's attribute "item" value. """ return self.getAttr(item) def __setitem__(self,item,val): """ Sets node's attribute "item" value. """ return self.setAttr(item,val) def __delitem__(self,item): """ Deletes node's attribute "item". """ return self.delAttr(item) def __getattr__(self,attr): """ Reduce memory usage caused by T/NT classes - use memory only when needed. """ if attr=='T': self.T=T(self) return self.T if attr=='NT': self.NT=NT(self) return self.NT raise AttributeError class T: """ Auxiliary class used to quick access to node's child nodes. """ def __init__(self,node): self.__dict__['node']=node def __getattr__(self,attr): return self.node.getTag(attr) def __setattr__(self,attr,val): if isinstance(val,Node): Node.__init__(self.node.setTag(attr),node=val) else: return self.node.setTagData(attr,val) def __delattr__(self,attr): return self.node.delChild(attr) class NT(T): """ Auxiliary class used to quick create node's child nodes. """ def __getattr__(self,attr): return self.node.addChild(attr) def __setattr__(self,attr,val): if isinstance(val,Node): self.node.addChild(attr,node=val) else: return self.node.addChild(attr,payload=[val]) DBG_NODEBUILDER = 'nodebuilder' class NodeBuilder: """ Builds a Node class minidom from data parsed to it. This class used for two purposes: 1. Creation an XML Node from a textual representation. F.e. reading a config file. See an XML2Node method. 2. Handling an incoming XML stream. This is done by mangling the __dispatch_depth parameter and redefining the dispatch method. You do not need to use this class directly if you do not designing your own XML handler.""" def __init__(self,data=None,initial_node=None): """ Takes two optional parameters: "data" and "initial_node". By default class initialised with empty Node class instance. Though, if "initial_node" is provided it used as "starting point". You can think about it as of "node upgrade". "data" (if provided) feeded to parser immidiatedly after instance init. """ self.DEBUG(DBG_NODEBUILDER, "Preparing to handle incoming XML stream.", 'start') self._parser = xml.parsers.expat.ParserCreate() self._parser.StartElementHandler = self.starttag self._parser.EndElementHandler = self.endtag self._parser.CharacterDataHandler = self.handle_cdata self._parser.StartNamespaceDeclHandler = self.handle_namespace_start self._parser.buffer_text = True self.Parse = self._parser.Parse self.__depth = 0 self.__last_depth = 0 self.__max_depth = 0 self._dispatch_depth = 1 self._document_attrs = None self._document_nsp = None self._mini_dom=initial_node self.last_is_data = 1 self._ptr=None self.data_buffer = None self.streamError = '' if data: self._parser.Parse(data,1) def check_data_buffer(self): if self.data_buffer: self._ptr.data.append(''.join(self.data_buffer)) del self.data_buffer[:] self.data_buffer = None def destroy(self): """ Method used to allow class instance to be garbage-collected. """ self.check_data_buffer() self._parser.StartElementHandler = None self._parser.EndElementHandler = None self._parser.CharacterDataHandler = None self._parser.StartNamespaceDeclHandler = None def starttag(self, tag, attrs): """XML Parser callback. Used internally""" self.check_data_buffer() self._inc_depth() self.DEBUG(DBG_NODEBUILDER, "DEPTH -> %i , tag -> %s, attrs -> %s" % (self.__depth, tag, `attrs`), 'down') if self.__depth == self._dispatch_depth: if not self._mini_dom : self._mini_dom = Node(tag=tag, attrs=attrs, nsp = self._document_nsp, node_built=True) else: Node.__init__(self._mini_dom,tag=tag, attrs=attrs, nsp = self._document_nsp, node_built=True) self._ptr = self._mini_dom elif self.__depth > self._dispatch_depth: self._ptr.kids.append(Node(tag=tag,parent=self._ptr,attrs=attrs, node_built=True)) self._ptr = self._ptr.kids[-1] if self.__depth == 1: self._document_attrs = {} self._document_nsp = {} nsp, name = (['']+tag.split(':'))[-2:] for attr,val in attrs.items(): if attr == 'xmlns': self._document_nsp[u''] = val elif attr.startswith('xmlns:'): self._document_nsp[attr[6:]] = val else: self._document_attrs[attr] = val ns = self._document_nsp.get(nsp, 'http://www.gajim.org/xmlns/undeclared-root') try: self.stream_header_received(ns, name, attrs) except ValueError, e: self._document_attrs = None raise ValueError(str(e)) if not self.last_is_data and self._ptr.parent: self._ptr.parent.data.append('') self.last_is_data = 0 def endtag(self, tag ): """XML Parser callback. Used internally""" self.DEBUG(DBG_NODEBUILDER, "DEPTH -> %i , tag -> %s" % (self.__depth, tag), 'up') self.check_data_buffer() if self.__depth == self._dispatch_depth: if self._mini_dom.getName() == 'error': self.streamError = self._mini_dom.getChildren()[0].getName() self.dispatch(self._mini_dom) elif self.__depth > self._dispatch_depth: self._ptr = self._ptr.parent else: self.DEBUG(DBG_NODEBUILDER, "Got higher than dispatch level. Stream terminated?", 'stop') self._dec_depth() self.last_is_data = 0 if self.__depth == 0: self.stream_footer_received() def handle_cdata(self, data): """XML Parser callback. Used internally""" self.DEBUG(DBG_NODEBUILDER, data, 'data') if self.last_is_data: if self.data_buffer: self.data_buffer.append(data) elif self._ptr: self.data_buffer = [data] self.last_is_data = 1 def handle_namespace_start(self, prefix, uri): """XML Parser callback. Used internally""" self.check_data_buffer() def DEBUG(self, level, text, comment=None): """ Gets all NodeBuilder walking events. Can be used for debugging if redefined.""" def getDom(self): """ Returns just built Node. """ self.check_data_buffer() return self._mini_dom def dispatch(self,stanza): """ Gets called when the NodeBuilder reaches some level of depth on it's way up with the built node as argument. Can be redefined to convert incoming XML stanzas to program events. """ def stream_header_received(self,ns,tag,attrs): """ Method called when stream just opened. """ self.check_data_buffer() def stream_footer_received(self): """ Method called when stream just closed. """ self.check_data_buffer() def has_received_endtag(self, level=0): """ Return True if at least one end tag was seen (at level) """ return self.__depth <= level and self.__max_depth > level def _inc_depth(self): self.__last_depth = self.__depth self.__depth += 1 self.__max_depth = max(self.__depth, self.__max_depth) def _dec_depth(self): self.__last_depth = self.__depth self.__depth -= 1 def XML2Node(xml): """ Converts supplied textual string into XML node. Handy f.e. for reading configuration file. Raises xml.parser.expat.parsererror if provided string is not well-formed XML. """ return NodeBuilder(xml).getDom() def BadXML2Node(xml): """ Converts supplied textual string into XML node. Survives if xml data is cutted half way round. I.e. "<html>some text <br>some more text". Will raise xml.parser.expat.parsererror on misplaced tags though. F.e. "<b>some text <br>some more text</b>" will not work.""" return NodeBuilder(xml).getDom()
gpl-3.0
kaedroho/django
tests/string_lookup/models.py
106
1232
from django.db import models class Foo(models.Model): name = models.CharField(max_length=50) friend = models.CharField(max_length=50, blank=True) def __str__(self): return "Foo %s" % self.name class Bar(models.Model): name = models.CharField(max_length=50) normal = models.ForeignKey(Foo, models.CASCADE, related_name='normal_foo') fwd = models.ForeignKey("Whiz", models.CASCADE) back = models.ForeignKey("Foo", models.CASCADE) def __str__(self): return "Bar %s" % self.place.name class Whiz(models.Model): name = models.CharField(max_length=50) def __str__(self): return "Whiz %s" % self.name class Child(models.Model): parent = models.OneToOneField('Base', models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return "Child %s" % self.name class Base(models.Model): name = models.CharField(max_length=50) def __str__(self): return "Base %s" % self.name class Article(models.Model): name = models.CharField(max_length=50) text = models.TextField() submitted_from = models.GenericIPAddressField(blank=True, null=True) def __str__(self): return "Article %s" % self.name
bsd-3-clause
auready/django
django/db/models/aggregates.py
26
5000
""" Classes to represent the definitions of aggregate functions. """ from django.core.exceptions import FieldError from django.db.models.expressions import Func, Star from django.db.models.fields import DecimalField, FloatField, IntegerField __all__ = [ 'Aggregate', 'Avg', 'Count', 'Max', 'Min', 'StdDev', 'Sum', 'Variance', ] class Aggregate(Func): contains_aggregate = True name = None def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): # Aggregates are not allowed in UPDATE queries, so ignore for_save c = super().resolve_expression(query, allow_joins, reuse, summarize) if not summarize: expressions = c.get_source_expressions() for index, expr in enumerate(expressions): if expr.contains_aggregate: before_resolved = self.get_source_expressions()[index] name = before_resolved.name if hasattr(before_resolved, 'name') else repr(before_resolved) raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name)) return c @property def default_alias(self): expressions = self.get_source_expressions() if len(expressions) == 1 and hasattr(expressions[0], 'name'): return '%s__%s' % (expressions[0].name, self.name.lower()) raise TypeError("Complex expressions require an alias") def get_group_by_cols(self): return [] class Avg(Aggregate): function = 'AVG' name = 'Avg' def _resolve_output_field(self): source_field = self.get_source_fields()[0] if isinstance(source_field, (IntegerField, DecimalField)): self._output_field = FloatField() super()._resolve_output_field() def as_oracle(self, compiler, connection): if self.output_field.get_internal_type() == 'DurationField': expression = self.get_source_expressions()[0] from django.db.backends.oracle.functions import IntervalToSeconds, SecondsToInterval return compiler.compile( SecondsToInterval(Avg(IntervalToSeconds(expression))) ) return super().as_sql(compiler, connection) class Count(Aggregate): function = 'COUNT' name = 'Count' template = '%(function)s(%(distinct)s%(expressions)s)' def __init__(self, expression, distinct=False, **extra): if expression == '*': expression = Star() super().__init__( expression, distinct='DISTINCT ' if distinct else '', output_field=IntegerField(), **extra ) def __repr__(self): return "{}({}, distinct={})".format( self.__class__.__name__, self.arg_joiner.join(str(arg) for arg in self.source_expressions), 'False' if self.extra['distinct'] == '' else 'True', ) def convert_value(self, value, expression, connection, context): if value is None: return 0 return int(value) class Max(Aggregate): function = 'MAX' name = 'Max' class Min(Aggregate): function = 'MIN' name = 'Min' class StdDev(Aggregate): name = 'StdDev' def __init__(self, expression, sample=False, **extra): self.function = 'STDDEV_SAMP' if sample else 'STDDEV_POP' super().__init__(expression, output_field=FloatField(), **extra) def __repr__(self): return "{}({}, sample={})".format( self.__class__.__name__, self.arg_joiner.join(str(arg) for arg in self.source_expressions), 'False' if self.function == 'STDDEV_POP' else 'True', ) def convert_value(self, value, expression, connection, context): if value is None: return value return float(value) class Sum(Aggregate): function = 'SUM' name = 'Sum' def as_oracle(self, compiler, connection): if self.output_field.get_internal_type() == 'DurationField': expression = self.get_source_expressions()[0] from django.db.backends.oracle.functions import IntervalToSeconds, SecondsToInterval return compiler.compile( SecondsToInterval(Sum(IntervalToSeconds(expression))) ) return super().as_sql(compiler, connection) class Variance(Aggregate): name = 'Variance' def __init__(self, expression, sample=False, **extra): self.function = 'VAR_SAMP' if sample else 'VAR_POP' super().__init__(expression, output_field=FloatField(), **extra) def __repr__(self): return "{}({}, sample={})".format( self.__class__.__name__, self.arg_joiner.join(str(arg) for arg in self.source_expressions), 'False' if self.function == 'VAR_POP' else 'True', ) def convert_value(self, value, expression, connection, context): if value is None: return value return float(value)
bsd-3-clause
rsunder10/PopularityBased-SearchEngine
lib/python3.4/site-packages/django/db/models/fields/subclassing.py
44
2031
""" Convenience routines for creating non-trivial Field subclasses, as well as backwards compatibility utilities. Add SubfieldBase as the metaclass for your Field subclass, implement to_python() and the other necessary methods and everything will work seamlessly. """ import warnings from django.utils.deprecation import RemovedInDjango110Warning class SubfieldBase(type): """ A metaclass for custom Field subclasses. This ensures the model's attribute has the descriptor protocol attached to it. """ def __new__(cls, name, bases, attrs): warnings.warn("SubfieldBase has been deprecated. Use Field.from_db_value instead.", RemovedInDjango110Warning, stacklevel=2) new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs) new_class.contribute_to_class = make_contrib( new_class, attrs.get('contribute_to_class') ) return new_class class Creator(object): """ A placeholder class that provides a way to set the attribute on the model. """ def __init__(self, field): self.field = field def __get__(self, obj, type=None): if obj is None: return self return obj.__dict__[self.field.name] def __set__(self, obj, value): obj.__dict__[self.field.name] = self.field.to_python(value) def make_contrib(superclass, func=None): """ Returns a suitable contribute_to_class() method for the Field subclass. If 'func' is passed in, it is the existing contribute_to_class() method on the subclass and it is called before anything else. It is assumed in this case that the existing contribute_to_class() calls all the necessary superclass methods. """ def contribute_to_class(self, cls, name, **kwargs): if func: func(self, cls, name, **kwargs) else: super(superclass, self).contribute_to_class(cls, name, **kwargs) setattr(cls, self.name, Creator(self)) return contribute_to_class
mit
sammerry/ansible
v1/ansible/module_utils/splitter.py
372
8425
# (c) 2014 James Cammarata, <jcammarata@ansible.com> # # 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 <http://www.gnu.org/licenses/>. def _get_quote_state(token, quote_char): ''' the goal of this block is to determine if the quoted string is unterminated in which case it needs to be put back together ''' # the char before the current one, used to see if # the current character is escaped prev_char = None for idx, cur_char in enumerate(token): if idx > 0: prev_char = token[idx-1] if cur_char in '"\'' and prev_char != '\\': if quote_char: if cur_char == quote_char: quote_char = None else: quote_char = cur_char return quote_char def _count_jinja2_blocks(token, cur_depth, open_token, close_token): ''' this function counts the number of opening/closing blocks for a given opening/closing type and adjusts the current depth for that block based on the difference ''' num_open = token.count(open_token) num_close = token.count(close_token) if num_open != num_close: cur_depth += (num_open - num_close) if cur_depth < 0: cur_depth = 0 return cur_depth def split_args(args): ''' Splits args on whitespace, but intelligently reassembles those that may have been split over a jinja2 block or quotes. When used in a remote module, we won't ever have to be concerned about jinja2 blocks, however this function is/will be used in the core portions as well before the args are templated. example input: a=b c="foo bar" example output: ['a=b', 'c="foo bar"'] Basically this is a variation shlex that has some more intelligence for how Ansible needs to use it. ''' # the list of params parsed out of the arg string # this is going to be the result value when we are donei params = [] # here we encode the args, so we have a uniform charset to # work with, and split on white space args = args.strip() try: args = args.encode('utf-8') do_decode = True except UnicodeDecodeError: do_decode = False items = args.split('\n') # iterate over the tokens, and reassemble any that may have been # split on a space inside a jinja2 block. # ex if tokens are "{{", "foo", "}}" these go together # These variables are used # to keep track of the state of the parsing, since blocks and quotes # may be nested within each other. quote_char = None inside_quotes = False print_depth = 0 # used to count nested jinja2 {{ }} blocks block_depth = 0 # used to count nested jinja2 {% %} blocks comment_depth = 0 # used to count nested jinja2 {# #} blocks # now we loop over each split chunk, coalescing tokens if the white space # split occurred within quotes or a jinja2 block of some kind for itemidx,item in enumerate(items): # we split on spaces and newlines separately, so that we # can tell which character we split on for reassembly # inside quotation characters tokens = item.strip().split(' ') line_continuation = False for idx,token in enumerate(tokens): # if we hit a line continuation character, but # we're not inside quotes, ignore it and continue # on to the next token while setting a flag if token == '\\' and not inside_quotes: line_continuation = True continue # store the previous quoting state for checking later was_inside_quotes = inside_quotes quote_char = _get_quote_state(token, quote_char) inside_quotes = quote_char is not None # multiple conditions may append a token to the list of params, # so we keep track with this flag to make sure it only happens once # append means add to the end of the list, don't append means concatenate # it to the end of the last token appended = False # if we're inside quotes now, but weren't before, append the token # to the end of the list, since we'll tack on more to it later # otherwise, if we're inside any jinja2 block, inside quotes, or we were # inside quotes (but aren't now) concat this token to the last param if inside_quotes and not was_inside_quotes: params.append(token) appended = True elif print_depth or block_depth or comment_depth or inside_quotes or was_inside_quotes: if idx == 0 and not inside_quotes and was_inside_quotes: params[-1] = "%s%s" % (params[-1], token) elif len(tokens) > 1: spacer = '' if idx > 0: spacer = ' ' params[-1] = "%s%s%s" % (params[-1], spacer, token) else: spacer = '' if not params[-1].endswith('\n') and idx == 0: spacer = '\n' params[-1] = "%s%s%s" % (params[-1], spacer, token) appended = True # if the number of paired block tags is not the same, the depth has changed, so we calculate that here # and may append the current token to the params (if we haven't previously done so) prev_print_depth = print_depth print_depth = _count_jinja2_blocks(token, print_depth, "{{", "}}") if print_depth != prev_print_depth and not appended: params.append(token) appended = True prev_block_depth = block_depth block_depth = _count_jinja2_blocks(token, block_depth, "{%", "%}") if block_depth != prev_block_depth and not appended: params.append(token) appended = True prev_comment_depth = comment_depth comment_depth = _count_jinja2_blocks(token, comment_depth, "{#", "#}") if comment_depth != prev_comment_depth and not appended: params.append(token) appended = True # finally, if we're at zero depth for all blocks and not inside quotes, and have not # yet appended anything to the list of params, we do so now if not (print_depth or block_depth or comment_depth) and not inside_quotes and not appended and token != '': params.append(token) # if this was the last token in the list, and we have more than # one item (meaning we split on newlines), add a newline back here # to preserve the original structure if len(items) > 1 and itemidx != len(items) - 1 and not line_continuation: if not params[-1].endswith('\n') or item == '': params[-1] += '\n' # always clear the line continuation flag line_continuation = False # If we're done and things are not at zero depth or we're still inside quotes, # raise an error to indicate that the args were unbalanced if print_depth or block_depth or comment_depth or inside_quotes: raise Exception("error while splitting arguments, either an unbalanced jinja2 block or quotes") # finally, we decode each param back to the unicode it was in the arg string if do_decode: params = [x.decode('utf-8') for x in params] return params def is_quoted(data): return len(data) > 0 and (data[0] == '"' and data[-1] == '"' or data[0] == "'" and data[-1] == "'") def unquote(data): ''' removes first and last quotes from a string, if the string starts and ends with the same quotes ''' if is_quoted(data): return data[1:-1] return data
gpl-3.0
stshine/servo
tests/wpt/css-tests/tools/webdriver/webdriver/error.py
82
3570
# 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 collections class WebDriverException(Exception): http_status = None status_code = None class ElementNotSelectableException(WebDriverException): http_status = 400 status_code = "element not selectable" class ElementNotVisibleException(WebDriverException): http_status = 400 status_code = "element not visible" class InsecureCertificateException(WebDriverException): http_status = 400 status_code = "insecure certificate" class InvalidArgumentException(WebDriverException): http_status = 400 status_code = "invalid argument" class InvalidCookieDomainException(WebDriverException): http_status = 400 status_code = "invalid cookie domain" class InvalidElementCoordinatesException(WebDriverException): http_status = 400 status_code = "invalid element coordinates" class InvalidElementStateException(WebDriverException): http_status = 400 status_code = "invalid cookie domain" class InvalidSelectorException(WebDriverException): http_status = 400 status_code = "invalid selector" class InvalidSessionIdException(WebDriverException): http_status = 404 status_code = "invalid session id" class JavascriptErrorException(WebDriverException): http_status = 500 status_code = "javascript error" class MoveTargetOutOfBoundsException(WebDriverException): http_status = 500 status_code = "move target out of bounds" class NoSuchAlertException(WebDriverException): http_status = 400 status_code = "no such alert" class NoSuchElementException(WebDriverException): http_status = 404 status_code = "no such element" class NoSuchFrameException(WebDriverException): http_status = 400 status_code = "no such frame" class NoSuchWindowException(WebDriverException): http_status = 400 status_code = "no such window" class ScriptTimeoutException(WebDriverException): http_status = 408 status_code = "script timeout" class SessionNotCreatedException(WebDriverException): http_status = 500 status_code = "session not created" class StaleElementReferenceException(WebDriverException): http_status = 400 status_code = "stale element reference" class TimeoutException(WebDriverException): http_status = 408 status_code = "timeout" class UnableToSetCookieException(WebDriverException): http_status = 500 status_code = "unable to set cookie" class UnexpectedAlertOpenException(WebDriverException): http_status = 500 status_code = "unexpected alert open" class UnknownErrorException(WebDriverException): http_status = 500 status_code = "unknown error" class UnknownCommandException(WebDriverException): http_status = 404 status_code = "unknown command" class UnknownMethodException(WebDriverException): http_status = 405 status_code = "unknown method" class UnsupportedOperationException(WebDriverException): http_status = 500 status_code = "unsupported operation" def get(status_code): """Gets exception from `status_code`, falling back to ``WebDriverException`` if it is not found. """ return _errors.get(status_code, WebDriverException) _errors = collections.defaultdict() for item in locals().values(): if type(item) == type and issubclass(item, WebDriverException): _errors[item.status_code] = item
mpl-2.0
ArphonePei/PDFConverter
thirdparty/curl/tests/http_pipe.py
22
14355
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Modified by Linus Nielsen Feltzing for inclusion in the libcurl test # framework # import SocketServer import argparse import re import select import socket import time import pprint import os INFO_MESSAGE = ''' This is a test server to test the libcurl pipelining functionality. It is a modified version if Google's HTTP pipelining test server. More information can be found here: http://dev.chromium.org/developers/design-documents/network-stack/http-pipelining Source code can be found here: http://code.google.com/p/http-pipelining-test/ ''' MAX_REQUEST_SIZE = 1024 # bytes MIN_POLL_TIME = 0.01 # seconds. Minimum time to poll, in order to prevent # excessive looping because Python refuses to poll for # small timeouts. SEND_BUFFER_TIME = 0.5 # seconds TIMEOUT = 30 # seconds class Error(Exception): pass class RequestTooLargeError(Error): pass class ServeIndexError(Error): pass class UnexpectedMethodError(Error): pass class RequestParser(object): """Parses an input buffer looking for HTTP GET requests.""" global logfile LOOKING_FOR_GET = 1 READING_HEADERS = 2 HEADER_RE = re.compile('([^:]+):(.*)\n') REQUEST_RE = re.compile('([^ ]+) ([^ ]+) HTTP/(\d+)\.(\d+)\n') def __init__(self): """Initializer.""" self._buffer = "" self._pending_headers = {} self._pending_request = "" self._state = self.LOOKING_FOR_GET self._were_all_requests_http_1_1 = True self._valid_requests = [] def ParseAdditionalData(self, data): """Finds HTTP requests in |data|. Args: data: (String) Newly received input data from the socket. Returns: (List of Tuples) (String) The request path. (Map of String to String) The header name and value. Raises: RequestTooLargeError: If the request exceeds MAX_REQUEST_SIZE. UnexpectedMethodError: On a non-GET method. Error: On a programming error. """ logfile = open('log/server.input', 'a') logfile.write(data) logfile.close() self._buffer += data.replace('\r', '') should_continue_parsing = True while should_continue_parsing: if self._state == self.LOOKING_FOR_GET: should_continue_parsing = self._DoLookForGet() elif self._state == self.READING_HEADERS: should_continue_parsing = self._DoReadHeader() else: raise Error('Unexpected state: ' + self._state) if len(self._buffer) > MAX_REQUEST_SIZE: raise RequestTooLargeError( 'Request is at least %d bytes' % len(self._buffer)) valid_requests = self._valid_requests self._valid_requests = [] return valid_requests @property def were_all_requests_http_1_1(self): return self._were_all_requests_http_1_1 def _DoLookForGet(self): """Tries to parse an HTTTP request line. Returns: (Boolean) True if a request was found. Raises: UnexpectedMethodError: On a non-GET method. """ m = self.REQUEST_RE.match(self._buffer) if not m: return False method, path, http_major, http_minor = m.groups() if method != 'GET': raise UnexpectedMethodError('Unexpected method: ' + method) if path in ['/', '/index.htm', '/index.html']: raise ServeIndexError() if http_major != '1' or http_minor != '1': self._were_all_requests_http_1_1 = False # print method, path self._pending_request = path self._buffer = self._buffer[m.end():] self._state = self.READING_HEADERS return True def _DoReadHeader(self): """Tries to parse a HTTP header. Returns: (Boolean) True if it found the end of the request or a HTTP header. """ if self._buffer.startswith('\n'): self._buffer = self._buffer[1:] self._state = self.LOOKING_FOR_GET self._valid_requests.append((self._pending_request, self._pending_headers)) self._pending_headers = {} self._pending_request = "" return True m = self.HEADER_RE.match(self._buffer) if not m: return False header = m.group(1).lower() value = m.group(2).strip().lower() if header not in self._pending_headers: self._pending_headers[header] = value self._buffer = self._buffer[m.end():] return True class ResponseBuilder(object): """Builds HTTP responses for a list of accumulated requests.""" def __init__(self): """Initializer.""" self._max_pipeline_depth = 0 self._requested_paths = [] self._processed_end = False self._were_all_requests_http_1_1 = True def QueueRequests(self, requested_paths, were_all_requests_http_1_1): """Adds requests to the queue of requests. Args: requested_paths: (List of Strings) Requested paths. """ self._requested_paths.extend(requested_paths) self._were_all_requests_http_1_1 = were_all_requests_http_1_1 def Chunkify(self, data, chunksize): """ Divides a string into chunks """ return [hex(chunksize)[2:] + "\r\n" + data[i:i+chunksize] + "\r\n" for i in range(0, len(data), chunksize)] def BuildResponses(self): """Converts the queue of requests into responses. Returns: (String) Buffer containing all of the responses. """ result = "" self._max_pipeline_depth = max(self._max_pipeline_depth, len(self._requested_paths)) for path, headers in self._requested_paths: if path == '/verifiedserver': body = "WE ROOLZ: {}\r\n".format(os.getpid()); result += self._BuildResponse( '200 OK', ['Server: Apache', 'Content-Length: {}'.format(len(body)), 'Cache-Control: no-store'], body) elif path == '/alphabet.txt': body = 'abcdefghijklmnopqrstuvwxyz' result += self._BuildResponse( '200 OK', ['Server: Apache', 'Content-Length: 26', 'Cache-Control: no-store'], body) elif path == '/reverse.txt': body = 'zyxwvutsrqponmlkjihgfedcba' result += self._BuildResponse( '200 OK', ['Content-Length: 26', 'Cache-Control: no-store'], body) elif path == '/chunked.txt': body = ('7\r\nchunked\r\n' '8\r\nencoding\r\n' '2\r\nis\r\n' '3\r\nfun\r\n' '0\r\n\r\n') result += self._BuildResponse( '200 OK', ['Transfer-Encoding: chunked', 'Cache-Control: no-store'], body) elif path == '/cached.txt': body = 'azbycxdwevfugthsirjqkplomn' result += self._BuildResponse( '200 OK', ['Content-Length: 26', 'Cache-Control: max-age=60'], body) elif path == '/connection_close.txt': body = 'azbycxdwevfugthsirjqkplomn' result += self._BuildResponse( '200 OK', ['Content-Length: 26', 'Cache-Control: max-age=60', 'Connection: close'], body) self._processed_end = True elif path == '/1k.txt': str = '0123456789abcdef' body = ''.join([str for num in xrange(64)]) result += self._BuildResponse( '200 OK', ['Server: Apache', 'Content-Length: 1024', 'Cache-Control: max-age=60'], body) elif path == '/10k.txt': str = '0123456789abcdef' body = ''.join([str for num in xrange(640)]) result += self._BuildResponse( '200 OK', ['Server: Apache', 'Content-Length: 10240', 'Cache-Control: max-age=60'], body) elif path == '/100k.txt': str = '0123456789abcdef' body = ''.join([str for num in xrange(6400)]) result += self._BuildResponse( '200 OK', ['Server: Apache', 'Content-Length: 102400', 'Cache-Control: max-age=60'], body) elif path == '/100k_chunked.txt': str = '0123456789abcdef' moo = ''.join([str for num in xrange(6400)]) body = self.Chunkify(moo, 20480) body.append('0\r\n\r\n') body = ''.join(body) result += self._BuildResponse( '200 OK', ['Transfer-Encoding: chunked', 'Cache-Control: no-store'], body) elif path == '/stats.txt': results = { 'max_pipeline_depth': self._max_pipeline_depth, 'were_all_requests_http_1_1': int(self._were_all_requests_http_1_1), } body = ','.join(['%s:%s' % (k, v) for k, v in results.items()]) result += self._BuildResponse( '200 OK', ['Content-Length: %s' % len(body), 'Cache-Control: no-store'], body) self._processed_end = True else: result += self._BuildResponse('404 Not Found', ['Content-Length: 7'], 'Go away') if self._processed_end: break self._requested_paths = [] return result def WriteError(self, status, error): """Returns an HTTP response for the specified error. Args: status: (String) Response code and descrtion (e.g. "404 Not Found") Returns: (String) Text of HTTP response. """ return self._BuildResponse( status, ['Connection: close', 'Content-Type: text/plain'], error) @property def processed_end(self): return self._processed_end def _BuildResponse(self, status, headers, body): """Builds an HTTP response. Args: status: (String) Response code and descrtion (e.g. "200 OK") headers: (List of Strings) Headers (e.g. "Connection: close") body: (String) Response body. Returns: (String) Text of HTTP response. """ return ('HTTP/1.1 %s\r\n' '%s\r\n' '\r\n' '%s' % (status, '\r\n'.join(headers), body)) class PipelineRequestHandler(SocketServer.BaseRequestHandler): """Called on an incoming TCP connection.""" def _GetTimeUntilTimeout(self): return self._start_time + TIMEOUT - time.time() def _GetTimeUntilNextSend(self): if not self._last_queued_time: return TIMEOUT return self._last_queued_time + SEND_BUFFER_TIME - time.time() def handle(self): self._request_parser = RequestParser() self._response_builder = ResponseBuilder() self._last_queued_time = 0 self._num_queued = 0 self._num_written = 0 self._send_buffer = "" self._start_time = time.time() try: poller = select.epoll(sizehint=1) poller.register(self.request.fileno(), select.EPOLLIN) while not self._response_builder.processed_end or self._send_buffer: time_left = self._GetTimeUntilTimeout() time_until_next_send = self._GetTimeUntilNextSend() max_poll_time = min(time_left, time_until_next_send) + MIN_POLL_TIME events = None if max_poll_time > 0: if self._send_buffer: poller.modify(self.request.fileno(), select.EPOLLIN | select.EPOLLOUT) else: poller.modify(self.request.fileno(), select.EPOLLIN) events = poller.poll(timeout=max_poll_time) if self._GetTimeUntilTimeout() <= 0: return if self._GetTimeUntilNextSend() <= 0: self._send_buffer += self._response_builder.BuildResponses() self._num_written = self._num_queued self._last_queued_time = 0 for fd, mode in events: if mode & select.EPOLLIN: new_data = self.request.recv(MAX_REQUEST_SIZE, socket.MSG_DONTWAIT) if not new_data: return new_requests = self._request_parser.ParseAdditionalData(new_data) self._response_builder.QueueRequests( new_requests, self._request_parser.were_all_requests_http_1_1) self._num_queued += len(new_requests) self._last_queued_time = time.time() elif mode & select.EPOLLOUT: num_bytes_sent = self.request.send(self._send_buffer[0:4096]) self._send_buffer = self._send_buffer[num_bytes_sent:] time.sleep(0.05) else: return except RequestTooLargeError as e: self.request.send(self._response_builder.WriteError( '413 Request Entity Too Large', e)) raise except UnexpectedMethodError as e: self.request.send(self._response_builder.WriteError( '405 Method Not Allowed', e)) raise except ServeIndexError: self.request.send(self._response_builder.WriteError( '200 OK', INFO_MESSAGE)) except Exception as e: print e self.request.close() class PipelineServer(SocketServer.ForkingMixIn, SocketServer.TCPServer): pass parser = argparse.ArgumentParser() parser.add_argument("--port", action="store", default=0, type=int, help="port to listen on") parser.add_argument("--verbose", action="store", default=0, type=int, help="verbose output") parser.add_argument("--pidfile", action="store", default=0, help="file name for the PID") parser.add_argument("--logfile", action="store", default=0, help="file name for the log") parser.add_argument("--srcdir", action="store", default=0, help="test directory") parser.add_argument("--id", action="store", default=0, help="server ID") parser.add_argument("--ipv4", action="store_true", default=0, help="IPv4 flag") args = parser.parse_args() if args.pidfile: pid = os.getpid() f = open(args.pidfile, 'w') f.write('{}'.format(pid)) f.close() server = PipelineServer(('0.0.0.0', args.port), PipelineRequestHandler) server.allow_reuse_address = True server.serve_forever()
agpl-3.0
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/test/test_threading.py
8
34689
# Very rudimentary test of threading module import test.test_support from test.test_support import verbose, cpython_only from test.script_helper import assert_python_ok import random import re import sys thread = test.test_support.import_module('thread') threading = test.test_support.import_module('threading') import time import unittest import weakref import os import subprocess try: import _testcapi except ImportError: _testcapi = None from test import lock_tests # A trivial mutable counter. class Counter(object): def __init__(self): self.value = 0 def inc(self): self.value += 1 def dec(self): self.value -= 1 def get(self): return self.value class TestThread(threading.Thread): def __init__(self, name, testcase, sema, mutex, nrunning): threading.Thread.__init__(self, name=name) self.testcase = testcase self.sema = sema self.mutex = mutex self.nrunning = nrunning def run(self): delay = random.random() / 10000.0 if verbose: print 'task %s will run for %.1f usec' % ( self.name, delay * 1e6) with self.sema: with self.mutex: self.nrunning.inc() if verbose: print self.nrunning.get(), 'tasks are running' self.testcase.assertLessEqual(self.nrunning.get(), 3) time.sleep(delay) if verbose: print 'task', self.name, 'done' with self.mutex: self.nrunning.dec() self.testcase.assertGreaterEqual(self.nrunning.get(), 0) if verbose: print '%s is finished. %d tasks are running' % ( self.name, self.nrunning.get()) class BaseTestCase(unittest.TestCase): def setUp(self): self._threads = test.test_support.threading_setup() def tearDown(self): test.test_support.threading_cleanup(*self._threads) test.test_support.reap_children() class ThreadTests(BaseTestCase): # Create a bunch of threads, let each do some work, wait until all are # done. def test_various_ops(self): # This takes about n/3 seconds to run (about n/3 clumps of tasks, # times about 1 second per clump). NUMTASKS = 10 # no more than 3 of the 10 can run at once sema = threading.BoundedSemaphore(value=3) mutex = threading.RLock() numrunning = Counter() threads = [] for i in range(NUMTASKS): t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning) threads.append(t) self.assertIsNone(t.ident) self.assertRegexpMatches(repr(t), r'^<TestThread\(.*, initial\)>$') t.start() if verbose: print 'waiting for all tasks to complete' for t in threads: t.join(NUMTASKS) self.assertFalse(t.is_alive()) self.assertNotEqual(t.ident, 0) self.assertIsNotNone(t.ident) self.assertRegexpMatches(repr(t), r'^<TestThread\(.*, \w+ -?\d+\)>$') if verbose: print 'all tasks done' self.assertEqual(numrunning.get(), 0) def test_ident_of_no_threading_threads(self): # The ident still must work for the main thread and dummy threads. self.assertIsNotNone(threading.currentThread().ident) def f(): ident.append(threading.currentThread().ident) done.set() done = threading.Event() ident = [] thread.start_new_thread(f, ()) done.wait() self.assertIsNotNone(ident[0]) # Kill the "immortal" _DummyThread del threading._active[ident[0]] # run with a small(ish) thread stack size (256kB) def test_various_ops_small_stack(self): if verbose: print 'with 256kB thread stack size...' try: threading.stack_size(262144) except thread.error: self.skipTest('platform does not support changing thread stack size') self.test_various_ops() threading.stack_size(0) # run with a large thread stack size (1MB) def test_various_ops_large_stack(self): if verbose: print 'with 1MB thread stack size...' try: threading.stack_size(0x100000) except thread.error: self.skipTest('platform does not support changing thread stack size') self.test_various_ops() threading.stack_size(0) def test_foreign_thread(self): # Check that a "foreign" thread can use the threading module. def f(mutex): # Calling current_thread() forces an entry for the foreign # thread to get made in the threading._active map. threading.current_thread() mutex.release() mutex = threading.Lock() mutex.acquire() tid = thread.start_new_thread(f, (mutex,)) # Wait for the thread to finish. mutex.acquire() self.assertIn(tid, threading._active) self.assertIsInstance(threading._active[tid], threading._DummyThread) del threading._active[tid] # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) # exposed at the Python level. This test relies on ctypes to get at it. def test_PyThreadState_SetAsyncExc(self): try: import ctypes except ImportError: self.skipTest('requires ctypes') set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc class AsyncExc(Exception): pass exception = ctypes.py_object(AsyncExc) # First check it works when setting the exception from the same thread. tid = thread.get_ident() try: result = set_async_exc(ctypes.c_long(tid), exception) # The exception is async, so we might have to keep the VM busy until # it notices. while True: pass except AsyncExc: pass else: # This code is unreachable but it reflects the intent. If we wanted # to be smarter the above loop wouldn't be infinite. self.fail("AsyncExc not raised") try: self.assertEqual(result, 1) # one thread state modified except UnboundLocalError: # The exception was raised too quickly for us to get the result. pass # `worker_started` is set by the thread when it's inside a try/except # block waiting to catch the asynchronously set AsyncExc exception. # `worker_saw_exception` is set by the thread upon catching that # exception. worker_started = threading.Event() worker_saw_exception = threading.Event() class Worker(threading.Thread): def run(self): self.id = thread.get_ident() self.finished = False try: while True: worker_started.set() time.sleep(0.1) except AsyncExc: self.finished = True worker_saw_exception.set() t = Worker() t.daemon = True # so if this fails, we don't hang Python at shutdown t.start() if verbose: print " started worker thread" # Try a thread id that doesn't make sense. if verbose: print " trying nonsensical thread id" result = set_async_exc(ctypes.c_long(-1), exception) self.assertEqual(result, 0) # no thread states modified # Now raise an exception in the worker thread. if verbose: print " waiting for worker thread to get started" ret = worker_started.wait() self.assertTrue(ret) if verbose: print " verifying worker hasn't exited" self.assertFalse(t.finished) if verbose: print " attempting to raise asynch exception in worker" result = set_async_exc(ctypes.c_long(t.id), exception) self.assertEqual(result, 1) # one thread state modified if verbose: print " waiting for worker to say it caught the exception" worker_saw_exception.wait(timeout=10) self.assertTrue(t.finished) if verbose: print " all OK -- joining worker" if t.finished: t.join() # else the thread is still running, and we have no way to kill it def test_limbo_cleanup(self): # Issue 7481: Failure to start thread should cleanup the limbo map. def fail_new_thread(*args): raise thread.error() _start_new_thread = threading._start_new_thread threading._start_new_thread = fail_new_thread try: t = threading.Thread(target=lambda: None) self.assertRaises(thread.error, t.start) self.assertFalse( t in threading._limbo, "Failed to cleanup _limbo map on failure of Thread.start().") finally: threading._start_new_thread = _start_new_thread def test_finalize_runnning_thread(self): # Issue 1402: the PyGILState_Ensure / _Release functions may be called # very late on python exit: on deallocation of a running thread for # example. try: import ctypes except ImportError: self.skipTest('requires ctypes') rc = subprocess.call([sys.executable, "-c", """if 1: import ctypes, sys, time, thread # This lock is used as a simple event variable. ready = thread.allocate_lock() ready.acquire() # Module globals are cleared before __del__ is run # So we save the functions in class dict class C: ensure = ctypes.pythonapi.PyGILState_Ensure release = ctypes.pythonapi.PyGILState_Release def __del__(self): state = self.ensure() self.release(state) def waitingThread(): x = C() ready.release() time.sleep(100) thread.start_new_thread(waitingThread, ()) ready.acquire() # Be sure the other thread is waiting. sys.exit(42) """]) self.assertEqual(rc, 42) def test_finalize_with_trace(self): # Issue1733757 # Avoid a deadlock when sys.settrace steps into threading._shutdown p = subprocess.Popen([sys.executable, "-c", """if 1: import sys, threading # A deadlock-killer, to prevent the # testsuite to hang forever def killer(): import os, time time.sleep(2) print 'program blocked; aborting' os._exit(2) t = threading.Thread(target=killer) t.daemon = True t.start() # This is the trace function def func(frame, event, arg): threading.current_thread() return func sys.settrace(func) """], stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.addCleanup(p.stdout.close) self.addCleanup(p.stderr.close) stdout, stderr = p.communicate() rc = p.returncode self.assertFalse(rc == 2, "interpreted was blocked") self.assertTrue(rc == 0, "Unexpected error: " + repr(stderr)) def test_join_nondaemon_on_shutdown(self): # Issue 1722344 # Raising SystemExit skipped threading._shutdown p = subprocess.Popen([sys.executable, "-c", """if 1: import threading from time import sleep def child(): sleep(1) # As a non-daemon thread we SHOULD wake up and nothing # should be torn down yet print "Woke up, sleep function is:", sleep threading.Thread(target=child).start() raise SystemExit """], stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.addCleanup(p.stdout.close) self.addCleanup(p.stderr.close) stdout, stderr = p.communicate() self.assertEqual(stdout.strip(), "Woke up, sleep function is: <built-in function sleep>") stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip() self.assertEqual(stderr, "") def test_enumerate_after_join(self): # Try hard to trigger #1703448: a thread is still returned in # threading.enumerate() after it has been join()ed. enum = threading.enumerate old_interval = sys.getcheckinterval() try: for i in xrange(1, 100): # Try a couple times at each thread-switching interval # to get more interleavings. sys.setcheckinterval(i // 5) t = threading.Thread(target=lambda: None) t.start() t.join() l = enum() self.assertNotIn(t, l, "#1703448 triggered after %d trials: %s" % (i, l)) finally: sys.setcheckinterval(old_interval) def test_no_refcycle_through_target(self): class RunSelfFunction(object): def __init__(self, should_raise): # The links in this refcycle from Thread back to self # should be cleaned up when the thread completes. self.should_raise = should_raise self.thread = threading.Thread(target=self._run, args=(self,), kwargs={'yet_another':self}) self.thread.start() def _run(self, other_ref, yet_another): if self.should_raise: raise SystemExit cyclic_object = RunSelfFunction(should_raise=False) weak_cyclic_object = weakref.ref(cyclic_object) cyclic_object.thread.join() del cyclic_object self.assertEqual(None, weak_cyclic_object(), msg=('%d references still around' % sys.getrefcount(weak_cyclic_object()))) raising_cyclic_object = RunSelfFunction(should_raise=True) weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) raising_cyclic_object.thread.join() del raising_cyclic_object self.assertEqual(None, weak_raising_cyclic_object(), msg=('%d references still around' % sys.getrefcount(weak_raising_cyclic_object()))) @unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()') def test_dummy_thread_after_fork(self): # Issue #14308: a dummy thread in the active list doesn't mess up # the after-fork mechanism. code = """if 1: import thread, threading, os, time def background_thread(evt): # Creates and registers the _DummyThread instance threading.current_thread() evt.set() time.sleep(10) evt = threading.Event() thread.start_new_thread(background_thread, (evt,)) evt.wait() assert threading.active_count() == 2, threading.active_count() if os.fork() == 0: assert threading.active_count() == 1, threading.active_count() os._exit(0) else: os.wait() """ _, out, err = assert_python_ok("-c", code) self.assertEqual(out, '') self.assertEqual(err, '') @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") def test_is_alive_after_fork(self): # Try hard to trigger #18418: is_alive() could sometimes be True on # threads that vanished after a fork. old_interval = sys.getcheckinterval() # Make the bug more likely to manifest. sys.setcheckinterval(10) try: for i in range(20): t = threading.Thread(target=lambda: None) t.start() pid = os.fork() if pid == 0: os._exit(1 if t.is_alive() else 0) else: t.join() pid, status = os.waitpid(pid, 0) self.assertEqual(0, status) finally: sys.setcheckinterval(old_interval) def test_BoundedSemaphore_limit(self): # BoundedSemaphore should raise ValueError if released too often. for limit in range(1, 10): bs = threading.BoundedSemaphore(limit) threads = [threading.Thread(target=bs.acquire) for _ in range(limit)] for t in threads: t.start() for t in threads: t.join() threads = [threading.Thread(target=bs.release) for _ in range(limit)] for t in threads: t.start() for t in threads: t.join() self.assertRaises(ValueError, bs.release) class ThreadJoinOnShutdown(BaseTestCase): # Between fork() and exec(), only async-safe functions are allowed (issues # #12316 and #11870), and fork() from a worker thread is known to trigger # problems with some operating systems (issue #3863): skip problematic tests # on platforms known to behave badly. platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', 'os2emx') def _run_and_join(self, script): script = """if 1: import sys, os, time, threading # a thread, which waits for the main program to terminate def joiningfunc(mainthread): mainthread.join() print 'end of thread' \n""" + script p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) rc = p.wait() data = p.stdout.read().replace('\r', '') p.stdout.close() self.assertEqual(data, "end of main\nend of thread\n") self.assertFalse(rc == 2, "interpreter was blocked") self.assertTrue(rc == 0, "Unexpected error") def test_1_join_on_shutdown(self): # The usual case: on exit, wait for a non-daemon thread script = """if 1: import os t = threading.Thread(target=joiningfunc, args=(threading.current_thread(),)) t.start() time.sleep(0.1) print 'end of main' """ self._run_and_join(script) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_2_join_in_forked_process(self): # Like the test above, but from a forked interpreter script = """if 1: childpid = os.fork() if childpid != 0: os.waitpid(childpid, 0) sys.exit(0) t = threading.Thread(target=joiningfunc, args=(threading.current_thread(),)) t.start() print 'end of main' """ self._run_and_join(script) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_3_join_in_forked_from_thread(self): # Like the test above, but fork() was called from a worker thread # In the forked process, the main Thread object must be marked as stopped. script = """if 1: main_thread = threading.current_thread() def worker(): childpid = os.fork() if childpid != 0: os.waitpid(childpid, 0) sys.exit(0) t = threading.Thread(target=joiningfunc, args=(main_thread,)) print 'end of main' t.start() t.join() # Should not block: main_thread is already stopped w = threading.Thread(target=worker) w.start() """ self._run_and_join(script) def assertScriptHasOutput(self, script, expected_output): p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) rc = p.wait() data = p.stdout.read().decode().replace('\r', '') self.assertEqual(rc, 0, "Unexpected error") self.assertEqual(data, expected_output) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_4_joining_across_fork_in_worker_thread(self): # There used to be a possible deadlock when forking from a child # thread. See http://bugs.python.org/issue6643. # The script takes the following steps: # - The main thread in the parent process starts a new thread and then # tries to join it. # - The join operation acquires the Lock inside the thread's _block # Condition. (See threading.py:Thread.join().) # - We stub out the acquire method on the condition to force it to wait # until the child thread forks. (See LOCK ACQUIRED HERE) # - The child thread forks. (See LOCK HELD and WORKER THREAD FORKS # HERE) # - The main thread of the parent process enters Condition.wait(), # which releases the lock on the child thread. # - The child process returns. Without the necessary fix, when the # main thread of the child process (which used to be the child thread # in the parent process) attempts to exit, it will try to acquire the # lock in the Thread._block Condition object and hang, because the # lock was held across the fork. script = """if 1: import os, time, threading finish_join = False start_fork = False def worker(): # Wait until this thread's lock is acquired before forking to # create the deadlock. global finish_join while not start_fork: time.sleep(0.01) # LOCK HELD: Main thread holds lock across this call. childpid = os.fork() finish_join = True if childpid != 0: # Parent process just waits for child. os.waitpid(childpid, 0) # Child process should just return. w = threading.Thread(target=worker) # Stub out the private condition variable's lock acquire method. # This acquires the lock and then waits until the child has forked # before returning, which will release the lock soon after. If # someone else tries to fix this test case by acquiring this lock # before forking instead of resetting it, the test case will # deadlock when it shouldn't. condition = w._block orig_acquire = condition.acquire call_count_lock = threading.Lock() call_count = 0 def my_acquire(): global call_count global start_fork orig_acquire() # LOCK ACQUIRED HERE start_fork = True if call_count == 0: while not finish_join: time.sleep(0.01) # WORKER THREAD FORKS HERE with call_count_lock: call_count += 1 condition.acquire = my_acquire w.start() w.join() print('end of main') """ self.assertScriptHasOutput(script, "end of main\n") @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_5_clear_waiter_locks_to_avoid_crash(self): # Check that a spawned thread that forks doesn't segfault on certain # platforms, namely OS X. This used to happen if there was a waiter # lock in the thread's condition variable's waiters list. Even though # we know the lock will be held across the fork, it is not safe to # release locks held across forks on all platforms, so releasing the # waiter lock caused a segfault on OS X. Furthermore, since locks on # OS X are (as of this writing) implemented with a mutex + condition # variable instead of a semaphore, while we know that the Python-level # lock will be acquired, we can't know if the internal mutex will be # acquired at the time of the fork. script = """if True: import os, time, threading start_fork = False def worker(): # Wait until the main thread has attempted to join this thread # before continuing. while not start_fork: time.sleep(0.01) childpid = os.fork() if childpid != 0: # Parent process just waits for child. (cpid, rc) = os.waitpid(childpid, 0) assert cpid == childpid assert rc == 0 print('end of worker thread') else: # Child process should just return. pass w = threading.Thread(target=worker) # Stub out the private condition variable's _release_save method. # This releases the condition's lock and flips the global that # causes the worker to fork. At this point, the problematic waiter # lock has been acquired once by the waiter and has been put onto # the waiters list. condition = w._block orig_release_save = condition._release_save def my_release_save(): global start_fork orig_release_save() # Waiter lock held here, condition lock released. start_fork = True condition._release_save = my_release_save w.start() w.join() print('end of main thread') """ output = "end of worker thread\nend of main thread\n" self.assertScriptHasOutput(script, output) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_reinit_tls_after_fork(self): # Issue #13817: fork() would deadlock in a multithreaded program with # the ad-hoc TLS implementation. def do_fork_and_wait(): # just fork a child process and wait it pid = os.fork() if pid > 0: os.waitpid(pid, 0) else: os._exit(0) # start a bunch of threads that will fork() child processes threads = [] for i in range(16): t = threading.Thread(target=do_fork_and_wait) threads.append(t) t.start() for t in threads: t.join() @cpython_only @unittest.skipIf(_testcapi is None, "need _testcapi module") def test_frame_tstate_tracing(self): # Issue #14432: Crash when a generator is created in a C thread that is # destroyed while the generator is still used. The issue was that a # generator contains a frame, and the frame kept a reference to the # Python state of the destroyed C thread. The crash occurs when a trace # function is setup. def noop_trace(frame, event, arg): # no operation return noop_trace def generator(): while 1: yield "generator" def callback(): if callback.gen is None: callback.gen = generator() return next(callback.gen) callback.gen = None old_trace = sys.gettrace() sys.settrace(noop_trace) try: # Install a trace function threading.settrace(noop_trace) # Create a generator in a C thread which exits after the call _testcapi.call_in_temporary_c_thread(callback) # Call the generator in a different Python thread, check that the # generator didn't keep a reference to the destroyed thread state for test in range(3): # The trace function is still called here callback() finally: sys.settrace(old_trace) class ThreadingExceptionTests(BaseTestCase): # A RuntimeError should be raised if Thread.start() is called # multiple times. def test_start_thread_again(self): thread = threading.Thread() thread.start() self.assertRaises(RuntimeError, thread.start) def test_joining_current_thread(self): current_thread = threading.current_thread() self.assertRaises(RuntimeError, current_thread.join); def test_joining_inactive_thread(self): thread = threading.Thread() self.assertRaises(RuntimeError, thread.join) def test_daemonize_active_thread(self): thread = threading.Thread() thread.start() self.assertRaises(RuntimeError, setattr, thread, "daemon", True) def test_print_exception(self): script = r"""if 1: import threading import time running = False def run(): global running running = True while running: time.sleep(0.01) 1.0/0.0 t = threading.Thread(target=run) t.start() while not running: time.sleep(0.01) running = False t.join() """ rc, out, err = assert_python_ok("-c", script) self.assertEqual(out, '') self.assertIn("Exception in thread", err) self.assertIn("Traceback (most recent call last):", err) self.assertIn("ZeroDivisionError", err) self.assertNotIn("Unhandled exception", err) def test_print_exception_stderr_is_none_1(self): script = r"""if 1: import sys import threading import time running = False def run(): global running running = True while running: time.sleep(0.01) 1.0/0.0 t = threading.Thread(target=run) t.start() while not running: time.sleep(0.01) sys.stderr = None running = False t.join() """ rc, out, err = assert_python_ok("-c", script) self.assertEqual(out, '') self.assertIn("Exception in thread", err) self.assertIn("Traceback (most recent call last):", err) self.assertIn("ZeroDivisionError", err) self.assertNotIn("Unhandled exception", err) def test_print_exception_stderr_is_none_2(self): script = r"""if 1: import sys import threading import time running = False def run(): global running running = True while running: time.sleep(0.01) 1.0/0.0 sys.stderr = None t = threading.Thread(target=run) t.start() while not running: time.sleep(0.01) running = False t.join() """ rc, out, err = assert_python_ok("-c", script) self.assertEqual(out, '') self.assertNotIn("Unhandled exception", err) class LockTests(lock_tests.LockTests): locktype = staticmethod(threading.Lock) class RLockTests(lock_tests.RLockTests): locktype = staticmethod(threading.RLock) class EventTests(lock_tests.EventTests): eventtype = staticmethod(threading.Event) class ConditionAsRLockTests(lock_tests.RLockTests): # Condition uses an RLock by default and exports its API. locktype = staticmethod(threading.Condition) class ConditionTests(lock_tests.ConditionTests): condtype = staticmethod(threading.Condition) class SemaphoreTests(lock_tests.SemaphoreTests): semtype = staticmethod(threading.Semaphore) class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): semtype = staticmethod(threading.BoundedSemaphore) @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem') def test_recursion_limit(self): # Issue 9670 # test that excessive recursion within a non-main thread causes # an exception rather than crashing the interpreter on platforms # like Mac OS X or FreeBSD which have small default stack sizes # for threads script = """if True: import threading def recurse(): return recurse() def outer(): try: recurse() except RuntimeError: pass w = threading.Thread(target=outer) w.start() w.join() print('end of main thread') """ expected_output = "end of main thread\n" p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) stdout, stderr = p.communicate() data = stdout.decode().replace('\r', '') self.assertEqual(p.returncode, 0, "Unexpected error") self.assertEqual(data, expected_output) def test_main(): test.test_support.run_unittest(LockTests, RLockTests, EventTests, ConditionAsRLockTests, ConditionTests, SemaphoreTests, BoundedSemaphoreTests, ThreadTests, ThreadJoinOnShutdown, ThreadingExceptionTests, ) if __name__ == "__main__": test_main()
gpl-3.0
Tehsmash/nova
nova/scheduler/weights/metrics.py
53
4448
# Copyright (c) 2011 OpenStack Foundation # 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. """ Metrics Weigher. Weigh hosts by their metrics. This weigher can compute the weight based on the compute node host's various metrics. The to-be weighed metrics and their weighing ratio are specified in the configuration file as the followings: [metrics] weight_setting = name1=1.0, name2=-1.0 The final weight would be name1.value * 1.0 + name2.value * -1.0. """ from oslo_config import cfg from nova import exception from nova.scheduler import utils from nova.scheduler import weights metrics_weight_opts = [ cfg.FloatOpt('weight_multiplier', default=1.0, help='Multiplier used for weighing metrics.'), cfg.ListOpt('weight_setting', default=[], help='How the metrics are going to be weighed. This ' 'should be in the form of "<name1>=<ratio1>, ' '<name2>=<ratio2>, ...", where <nameX> is one ' 'of the metrics to be weighed, and <ratioX> is ' 'the corresponding ratio. So for "name1=1.0, ' 'name2=-1.0" The final weight would be ' 'name1.value * 1.0 + name2.value * -1.0.'), cfg.BoolOpt('required', default=True, help='How to treat the unavailable metrics. When a ' 'metric is NOT available for a host, if it is set ' 'to be True, it would raise an exception, so it ' 'is recommended to use the scheduler filter ' 'MetricFilter to filter out those hosts. If it is ' 'set to be False, the unavailable metric would be ' 'treated as a negative factor in weighing ' 'process, the returned value would be set by ' 'the option weight_of_unavailable.'), cfg.FloatOpt('weight_of_unavailable', default=float(-10000.0), help='The final weight value to be returned if ' 'required is set to False and any one of the ' 'metrics set by weight_setting is unavailable.'), ] CONF = cfg.CONF CONF.register_opts(metrics_weight_opts, group='metrics') class MetricsWeigher(weights.BaseHostWeigher): def __init__(self): self._parse_setting() def _parse_setting(self): self.setting = utils.parse_options(CONF.metrics.weight_setting, sep='=', converter=float, name="metrics.weight_setting") def weight_multiplier(self): """Override the weight multiplier.""" return CONF.metrics.weight_multiplier def _weigh_object(self, host_state, weight_properties): value = 0.0 for (name, ratio) in self.setting: try: value += host_state.metrics[name].value * ratio except KeyError: if CONF.metrics.required: raise exception.ComputeHostMetricNotFound( host=host_state.host, node=host_state.nodename, name=name) else: # We treat the unavailable metric as the most negative # factor, i.e. set the value to make this obj would be # at the end of the ordered weighed obj list # Do nothing if ratio or weight_multiplier is 0. if ratio * self.weight_multiplier() != 0: return CONF.metrics.weight_of_unavailable return value
apache-2.0
jeremiahmarks/sl4a
python/src/Lib/test/test_int.py
56
12905
import sys import unittest from test.test_support import run_unittest, have_unicode L = [ ('0', 0), ('1', 1), ('9', 9), ('10', 10), ('99', 99), ('100', 100), ('314', 314), (' 314', 314), ('314 ', 314), (' \t\t 314 \t\t ', 314), (repr(sys.maxint), sys.maxint), (' 1x', ValueError), (' 1 ', 1), (' 1\02 ', ValueError), ('', ValueError), (' ', ValueError), (' \t\t ', ValueError) ] if have_unicode: L += [ (unicode('0'), 0), (unicode('1'), 1), (unicode('9'), 9), (unicode('10'), 10), (unicode('99'), 99), (unicode('100'), 100), (unicode('314'), 314), (unicode(' 314'), 314), (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314), (unicode(' \t\t 314 \t\t '), 314), (unicode(' 1x'), ValueError), (unicode(' 1 '), 1), (unicode(' 1\02 '), ValueError), (unicode(''), ValueError), (unicode(' '), ValueError), (unicode(' \t\t '), ValueError), (unichr(0x200), ValueError), ] class IntTestCases(unittest.TestCase): def test_basic(self): self.assertEqual(int(314), 314) self.assertEqual(int(3.14), 3) self.assertEqual(int(314L), 314) # Check that conversion from float truncates towards zero self.assertEqual(int(-3.14), -3) self.assertEqual(int(3.9), 3) self.assertEqual(int(-3.9), -3) self.assertEqual(int(3.5), 3) self.assertEqual(int(-3.5), -3) # Different base: self.assertEqual(int("10",16), 16L) if have_unicode: self.assertEqual(int(unicode("10"),16), 16L) # Test conversion from strings and various anomalies for s, v in L: for sign in "", "+", "-": for prefix in "", " ", "\t", " \t\t ": ss = prefix + sign + s vv = v if sign == "-" and v is not ValueError: vv = -v try: self.assertEqual(int(ss), vv) except v: pass s = repr(-1-sys.maxint) x = int(s) self.assertEqual(x+1, -sys.maxint) self.assert_(isinstance(x, int)) # should return long self.assertEqual(int(s[1:]), sys.maxint+1) # should return long x = int(1e100) self.assert_(isinstance(x, long)) x = int(-1e100) self.assert_(isinstance(x, long)) # SF bug 434186: 0x80000000/2 != 0x80000000>>1. # Worked by accident in Windows release build, but failed in debug build. # Failed in all Linux builds. x = -1-sys.maxint self.assertEqual(x >> 1, x//2) self.assertRaises(ValueError, int, '123\0') self.assertRaises(ValueError, int, '53', 40) # SF bug 1545497: embedded NULs were not detected with # explicit base self.assertRaises(ValueError, int, '123\0', 10) self.assertRaises(ValueError, int, '123\x00 245', 20) x = int('1' * 600) self.assert_(isinstance(x, long)) if have_unicode: x = int(unichr(0x661) * 600) self.assert_(isinstance(x, long)) self.assertRaises(TypeError, int, 1, 12) self.assertEqual(int('0123', 0), 83) self.assertEqual(int('0x123', 16), 291) # Bug 1679: "0x" is not a valid hex literal self.assertRaises(ValueError, int, "0x", 16) self.assertRaises(ValueError, int, "0x", 0) self.assertRaises(ValueError, int, "0o", 8) self.assertRaises(ValueError, int, "0o", 0) self.assertRaises(ValueError, int, "0b", 2) self.assertRaises(ValueError, int, "0b", 0) # SF bug 1334662: int(string, base) wrong answers # Various representations of 2**32 evaluated to 0 # rather than 2**32 in previous versions self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296L) self.assertEqual(int('102002022201221111211', 3), 4294967296L) self.assertEqual(int('10000000000000000', 4), 4294967296L) self.assertEqual(int('32244002423141', 5), 4294967296L) self.assertEqual(int('1550104015504', 6), 4294967296L) self.assertEqual(int('211301422354', 7), 4294967296L) self.assertEqual(int('40000000000', 8), 4294967296L) self.assertEqual(int('12068657454', 9), 4294967296L) self.assertEqual(int('4294967296', 10), 4294967296L) self.assertEqual(int('1904440554', 11), 4294967296L) self.assertEqual(int('9ba461594', 12), 4294967296L) self.assertEqual(int('535a79889', 13), 4294967296L) self.assertEqual(int('2ca5b7464', 14), 4294967296L) self.assertEqual(int('1a20dcd81', 15), 4294967296L) self.assertEqual(int('100000000', 16), 4294967296L) self.assertEqual(int('a7ffda91', 17), 4294967296L) self.assertEqual(int('704he7g4', 18), 4294967296L) self.assertEqual(int('4f5aff66', 19), 4294967296L) self.assertEqual(int('3723ai4g', 20), 4294967296L) self.assertEqual(int('281d55i4', 21), 4294967296L) self.assertEqual(int('1fj8b184', 22), 4294967296L) self.assertEqual(int('1606k7ic', 23), 4294967296L) self.assertEqual(int('mb994ag', 24), 4294967296L) self.assertEqual(int('hek2mgl', 25), 4294967296L) self.assertEqual(int('dnchbnm', 26), 4294967296L) self.assertEqual(int('b28jpdm', 27), 4294967296L) self.assertEqual(int('8pfgih4', 28), 4294967296L) self.assertEqual(int('76beigg', 29), 4294967296L) self.assertEqual(int('5qmcpqg', 30), 4294967296L) self.assertEqual(int('4q0jto4', 31), 4294967296L) self.assertEqual(int('4000000', 32), 4294967296L) self.assertEqual(int('3aokq94', 33), 4294967296L) self.assertEqual(int('2qhxjli', 34), 4294967296L) self.assertEqual(int('2br45qb', 35), 4294967296L) self.assertEqual(int('1z141z4', 36), 4294967296L) # tests with base 0 # this fails on 3.0, but in 2.x the old octal syntax is allowed self.assertEqual(int(' 0123 ', 0), 83) self.assertEqual(int(' 0123 ', 0), 83) self.assertEqual(int('000', 0), 0) self.assertEqual(int('0o123', 0), 83) self.assertEqual(int('0x123', 0), 291) self.assertEqual(int('0b100', 0), 4) self.assertEqual(int(' 0O123 ', 0), 83) self.assertEqual(int(' 0X123 ', 0), 291) self.assertEqual(int(' 0B100 ', 0), 4) # without base still base 10 self.assertEqual(int('0123'), 123) self.assertEqual(int('0123', 10), 123) # tests with prefix and base != 0 self.assertEqual(int('0x123', 16), 291) self.assertEqual(int('0o123', 8), 83) self.assertEqual(int('0b100', 2), 4) self.assertEqual(int('0X123', 16), 291) self.assertEqual(int('0O123', 8), 83) self.assertEqual(int('0B100', 2), 4) # the code has special checks for the first character after the # type prefix self.assertRaises(ValueError, int, '0b2', 2) self.assertRaises(ValueError, int, '0b02', 2) self.assertRaises(ValueError, int, '0B2', 2) self.assertRaises(ValueError, int, '0B02', 2) self.assertRaises(ValueError, int, '0o8', 8) self.assertRaises(ValueError, int, '0o08', 8) self.assertRaises(ValueError, int, '0O8', 8) self.assertRaises(ValueError, int, '0O08', 8) self.assertRaises(ValueError, int, '0xg', 16) self.assertRaises(ValueError, int, '0x0g', 16) self.assertRaises(ValueError, int, '0Xg', 16) self.assertRaises(ValueError, int, '0X0g', 16) # SF bug 1334662: int(string, base) wrong answers # Checks for proper evaluation of 2**32 + 1 self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297L) self.assertEqual(int('102002022201221111212', 3), 4294967297L) self.assertEqual(int('10000000000000001', 4), 4294967297L) self.assertEqual(int('32244002423142', 5), 4294967297L) self.assertEqual(int('1550104015505', 6), 4294967297L) self.assertEqual(int('211301422355', 7), 4294967297L) self.assertEqual(int('40000000001', 8), 4294967297L) self.assertEqual(int('12068657455', 9), 4294967297L) self.assertEqual(int('4294967297', 10), 4294967297L) self.assertEqual(int('1904440555', 11), 4294967297L) self.assertEqual(int('9ba461595', 12), 4294967297L) self.assertEqual(int('535a7988a', 13), 4294967297L) self.assertEqual(int('2ca5b7465', 14), 4294967297L) self.assertEqual(int('1a20dcd82', 15), 4294967297L) self.assertEqual(int('100000001', 16), 4294967297L) self.assertEqual(int('a7ffda92', 17), 4294967297L) self.assertEqual(int('704he7g5', 18), 4294967297L) self.assertEqual(int('4f5aff67', 19), 4294967297L) self.assertEqual(int('3723ai4h', 20), 4294967297L) self.assertEqual(int('281d55i5', 21), 4294967297L) self.assertEqual(int('1fj8b185', 22), 4294967297L) self.assertEqual(int('1606k7id', 23), 4294967297L) self.assertEqual(int('mb994ah', 24), 4294967297L) self.assertEqual(int('hek2mgm', 25), 4294967297L) self.assertEqual(int('dnchbnn', 26), 4294967297L) self.assertEqual(int('b28jpdn', 27), 4294967297L) self.assertEqual(int('8pfgih5', 28), 4294967297L) self.assertEqual(int('76beigh', 29), 4294967297L) self.assertEqual(int('5qmcpqh', 30), 4294967297L) self.assertEqual(int('4q0jto5', 31), 4294967297L) self.assertEqual(int('4000001', 32), 4294967297L) self.assertEqual(int('3aokq95', 33), 4294967297L) self.assertEqual(int('2qhxjlj', 34), 4294967297L) self.assertEqual(int('2br45qc', 35), 4294967297L) self.assertEqual(int('1z141z5', 36), 4294967297L) def test_intconversion(self): # Test __int__() class ClassicMissingMethods: pass self.assertRaises(AttributeError, int, ClassicMissingMethods()) class MissingMethods(object): pass self.assertRaises(TypeError, int, MissingMethods()) class Foo0: def __int__(self): return 42 class Foo1(object): def __int__(self): return 42 class Foo2(int): def __int__(self): return 42 class Foo3(int): def __int__(self): return self class Foo4(int): def __int__(self): return 42L class Foo5(int): def __int__(self): return 42. self.assertEqual(int(Foo0()), 42) self.assertEqual(int(Foo1()), 42) self.assertEqual(int(Foo2()), 42) self.assertEqual(int(Foo3()), 0) self.assertEqual(int(Foo4()), 42L) self.assertRaises(TypeError, int, Foo5()) class Classic: pass for base in (object, Classic): class IntOverridesTrunc(base): def __int__(self): return 42 def __trunc__(self): return -12 self.assertEqual(int(IntOverridesTrunc()), 42) class JustTrunc(base): def __trunc__(self): return 42 self.assertEqual(int(JustTrunc()), 42) for trunc_result_base in (object, Classic): class Integral(trunc_result_base): def __int__(self): return 42 class TruncReturnsNonInt(base): def __trunc__(self): return Integral() self.assertEqual(int(TruncReturnsNonInt()), 42) class NonIntegral(trunc_result_base): def __trunc__(self): # Check that we avoid infinite recursion. return NonIntegral() class TruncReturnsNonIntegral(base): def __trunc__(self): return NonIntegral() try: int(TruncReturnsNonIntegral()) except TypeError as e: self.assertEquals(str(e), "__trunc__ returned non-Integral" " (type NonIntegral)") else: self.fail("Failed to raise TypeError with %s" % ((base, trunc_result_base),)) def test_main(): run_unittest(IntTestCases) if __name__ == "__main__": test_main()
apache-2.0
Caylo/easybuild-framework
easybuild/toolchains/intel.py
2
1694
## # Copyright 2012-2016 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for intel compiler toolchain (includes Intel compilers (icc, ifort), Intel MPI, Intel Math Kernel Library (MKL), and Intel FFTW wrappers). :author: Stijn De Weirdt (Ghent University) :author: Kenneth Hoste (Ghent University) """ from easybuild.toolchains.iimpi import Iimpi from easybuild.toolchains.fft.intelfftw import IntelFFTW from easybuild.toolchains.linalg.intelmkl import IntelMKL class Intel(Iimpi, IntelMKL, IntelFFTW): """ Compiler toolchain with Intel compilers (icc/ifort), Intel MPI, Intel Math Kernel Library (MKL) and Intel FFTW wrappers. """ NAME = 'intel' SUBTOOLCHAIN = Iimpi.NAME
gpl-2.0
undeath/joinmarket-clientserver
jmclient/test/test_psbt_wallet.py
2
28856
#! /usr/bin/env python '''Test of psbt creation, update, signing and finalizing using the functionality of the PSBT Wallet Mixin. Note that Joinmarket's PSBT code is a wrapper around bitcointx.core.psbt, and the basic test vectors for BIP174 are tested there, not here. ''' import copy import base64 from commontest import make_wallets, dummy_accept_callback, dummy_info_callback import jmbitcoin as bitcoin import pytest from jmbase import get_log, bintohex, hextobin, utxostr_to_utxo from jmclient import (load_test_config, jm_single, direct_send, SegwitLegacyWallet, SegwitWallet, LegacyWallet, VolatileStorage, get_network) from jmclient.wallet import PSBTWalletMixin log = get_log() def create_volatile_wallet(seedphrase, wallet_cls=SegwitWallet): storage = VolatileStorage() wallet_cls.initialize(storage, get_network(), max_mixdepth=4, entropy=wallet_cls.entropy_from_mnemonic(seedphrase)) storage.save() return wallet_cls(storage) @pytest.mark.parametrize('walletseed, xpub, spktype_wallet, spktype_destn, partial, psbt', [ ("prosper diamond marriage spy across start shift elevator job lunar edge gallery", "tpubDChjiEhsafnW2LcmK1C77XiEAgZddi6xZyxjMujBzUqZPTMRwsv3e5vSBYsdiPtCyc6TtoHTCjkxBjtF22tf8Z5ABRdeBUNwHCsqEyzR5wT", "p2wpkh", "p2sh-p2wpkh", False, "cHNidP8BAMQCAAAAA7uEliZeXLPfjeUiRBw6e5oZV1DtBrDmLthfDC4oaHQLAAAAAAD/////+X1Exketc4o5b9BPxsj70O+VlGvgiZz0KP1OMRtVLUQAAAAAAP////9r5ylMhQyxbJvCbU8aNE3NOPoXJwUaUZm4H3iT4RnaSwAAAAAA/////wKMz/AIAAAAABepFJwmRAefvZS7VQStD4k52Rn0k71Gh4zP8AgAAAAAFgAUA2shnTVftDXq+ssPwzml2UKdu1QAAAAAAAEBHwDh9QUAAAAAFgAUqw1Ifto4LztwcsxV6q+sQThIdloiBgMDZ5u3RN6Xum+OLkgAzwLFXGWFLwBUraMi7Oin4fYfrwzvYoLxAAAAAAAAAAAAAQEfAOH1BQAAAAAWABQpSCwoeMSghUoVflvtTPiqBPi+5yIGA/tAH4kVpqd3wzidaTNFxtwdpHTydkmB825us2w/3cAVDO9igvEAAAAAAQAAAAABAR8A4fUFAAAAABYAFEqM0KJ5FJ7ak2NL8PDqOPI0I1PaIgYD84aDwOqXKfGvEbre+bpNpuT0uZv6syESzz5PMu4RyLkM72KC8QAAAAACAAAAAAEAF6kUnCZEB5+9lLtVBK0PiTnZGfSTvUaHACICAw8k2gGGcF5sR8yKO5JeAkrkH15rmtCq8sCoDYbywTNzEO9igvEMAAAAIgAAAJQCAAAA"), ("prosper diamond marriage spy across start shift elevator job lunar edge gallery", "tpubDChjiEhsafnW2LcmK1C77XiEAgZddi6xZyxjMujBzUqZPTMRwsv3e5vSBYsdiPtCyc6TtoHTCjkxBjtF22tf8Z5ABRdeBUNwHCsqEyzR5wT", "p2wpkh", "p2wpkh", False, "cHNidP8BAMMCAAAAA7uEliZeXLPfjeUiRBw6e5oZV1DtBrDmLthfDC4oaHQLAAAAAAD/////+X1Exketc4o5b9BPxsj70O+VlGvgiZz0KP1OMRtVLUQAAAAAAP////9r5ylMhQyxbJvCbU8aNE3NOPoXJwUaUZm4H3iT4RnaSwAAAAAA/////wKMz/AIAAAAABYAFBaOTObQIdtCaryiPxaDV5rsGYWUjM/wCAAAAAAWABR9TJm5rcSoIMW7bE1bnj7REL/eygAAAAAAAQEfAOH1BQAAAAAWABSrDUh+2jgvO3ByzFXqr6xBOEh2WiIGAwNnm7dE3pe6b44uSADPAsVcZYUvAFStoyLs6Kfh9h+vDO9igvEAAAAAAAAAAAABAR8A4fUFAAAAABYAFClILCh4xKCFShV+W+1M+KoE+L7nIgYD+0AfiRWmp3fDOJ1pM0XG3B2kdPJ2SYHzbm6zbD/dwBUM72KC8QAAAAABAAAAAAEBHwDh9QUAAAAAFgAUSozQonkUntqTY0vw8Oo48jQjU9oiBgPzhoPA6pcp8a8Rut75uk2m5PS5m/qzIRLPPk8y7hHIuQzvYoLxAAAAAAIAAAAAACICAuqCicVUfcM5IiVSiB/0ZemodybG5Im9Fu8MLorQSE4UEO9igvEMAAAAIgAAAOkAAAAA"), ("prosper diamond marriage spy across start shift elevator job lunar edge gallery", "tpubDChjiEhsafnW2LcmK1C77XiEAgZddi6xZyxjMujBzUqZPTMRwsv3e5vSBYsdiPtCyc6TtoHTCjkxBjtF22tf8Z5ABRdeBUNwHCsqEyzR5wT", "p2wpkh", "p2wpkh", True, "cHNidP8BAMMCAAAAA7uEliZeXLPfjeUiRBw6e5oZV1DtBrDmLthfDC4oaHQLAAAAAAD/////+X1Exketc4o5b9BPxsj70O+VlGvgiZz0KP1OMRtVLUQAAAAAAP////9r5ylMhQyxbJvCbU8aNE3NOPoXJwUaUZm4H3iT4RnaSwAAAAAA/////wKMz/AIAAAAABYAFLH/IL11rTJ3wX1NcmUIsJ/T4j4jjM/wCAAAAAAWABR8GPNb1HUpCz8PKOc8aQXLD1wjcAAAAAAAAQEfAOH1BQAAAAAWABSrDUh+2jgvO3ByzFXqr6xBOEh2WiIGAwNnm7dE3pe6b44uSADPAsVcZYUvAFStoyLs6Kfh9h+vDE5vcGUAAAAAAAAAAAABAR8A4fUFAAAAABYAFClILCh4xKCFShV+W+1M+KoE+L7nIgYD+0AfiRWmp3fDOJ1pM0XG3B2kdPJ2SYHzbm6zbD/dwBUM72KC8QAAAAABAAAAAAEBHwDh9QUAAAAAFgAUSozQonkUntqTY0vw8Oo48jQjU9oiBgPzhoPA6pcp8a8Rut75uk2m5PS5m/qzIRLPPk8y7hHIuQzvYoLxAAAAAAIAAAAAACICAsQ7ZvU9tsbBoSje5rIJQBStlUkQaRCssKylEixre3AYEO9igvEMAAAAIgAAABcCAAAA"), ]) def test_sign_external_psbt(setup_psbt_wallet, walletseed, xpub, spktype_wallet, spktype_destn, partial, psbt): bitcoin.select_chain_params("bitcoin") wallet_cls = SegwitWallet if spktype_wallet == "p2wpkh" else SegwitLegacyWallet wallet = create_volatile_wallet(walletseed, wallet_cls=wallet_cls) # if we want to actually sign, our wallet has to recognize the fake utxos # as being in the wallet, so we inject them: class DummyUtxoManager(object): _utxo = {0:{}} def add_utxo(self, utxo, path, value, height): self._utxo[0][utxo] = (path, value, height) wallet._index_cache[0][0] = 1000 wallet._utxos = DummyUtxoManager() p0, p1, p2 = (wallet.get_path(0, 0, i) for i in range(3)) if not partial: wallet._utxos.add_utxo(utxostr_to_utxo( "0b7468282e0c5fd82ee6b006ed5057199a7b3a1c4422e58ddfb35c5e269684bb:0"), p0, 10000, 1) wallet._utxos.add_utxo(utxostr_to_utxo( "442d551b314efd28f49c89e06b9495efd0fbc8c64fd06f398a73ad47c6447df9:0"), p1, 10000, 1) wallet._utxos.add_utxo(utxostr_to_utxo( "4bda19e193781fb899511a052717fa38cd4d341a4f6dc29b6cb10c854c29e76b:0"), p2, 10000, 1) signresult_and_signedpsbt, err = wallet.sign_psbt(base64.b64decode( psbt.encode("ascii")),with_sign_result=True) assert not err signresult, signedpsbt = signresult_and_signedpsbt if partial: assert not signresult.is_final assert signresult.num_inputs_signed == 2 assert signresult.num_inputs_final == 2 else: assert signresult.is_final assert signresult.num_inputs_signed == 3 assert signresult.num_inputs_final == 3 print(PSBTWalletMixin.human_readable_psbt(signedpsbt)) bitcoin.select_chain_params("bitcoin/regtest") def test_create_and_sign_psbt_with_legacy(setup_psbt_wallet): """ The purpose of this test is to check that we can create and then partially sign a PSBT where we own one input and the other input is of legacy p2pkh type. """ wallet_service = make_wallets(1, [[1,0,0,0,0]], 1)[0]['wallet'] wallet_service.sync_wallet(fast=True) utxos = wallet_service.select_utxos(0, bitcoin.coins_to_satoshi(0.5)) assert len(utxos) == 1 # create a legacy address and make a payment into it legacy_addr = bitcoin.CCoinAddress.from_scriptPubKey( bitcoin.pubkey_to_p2pkh_script( bitcoin.privkey_to_pubkey(b"\x01"*33))) tx = direct_send(wallet_service, bitcoin.coins_to_satoshi(0.3), 0, str(legacy_addr), accept_callback=dummy_accept_callback, info_callback=dummy_info_callback, return_transaction=True) assert tx # this time we will have one utxo worth <~ 0.7 my_utxos = wallet_service.select_utxos(0, bitcoin.coins_to_satoshi(0.5)) assert len(my_utxos) == 1 # find the outpoint for the legacy address we're spending n = -1 for i, t in enumerate(tx.vout): if bitcoin.CCoinAddress.from_scriptPubKey(t.scriptPubKey) == legacy_addr: n = i assert n > -1 utxos = copy.deepcopy(my_utxos) utxos[(tx.GetTxid()[::-1], n)] ={"script": legacy_addr.to_scriptPubKey(), "value": bitcoin.coins_to_satoshi(0.3)} outs = [{"value": bitcoin.coins_to_satoshi(0.998), "address": wallet_service.get_addr(0,0,0)}] tx2 = bitcoin.mktx(list(utxos.keys()), outs) spent_outs = wallet_service.witness_utxos_to_psbt_utxos(my_utxos) spent_outs.append(tx) new_psbt = wallet_service.create_psbt_from_tx(tx2, spent_outs, force_witness_utxo=False) signed_psbt_and_signresult, err = wallet_service.sign_psbt( new_psbt.serialize(), with_sign_result=True) assert err is None signresult, signed_psbt = signed_psbt_and_signresult assert signresult.num_inputs_signed == 1 assert signresult.num_inputs_final == 1 assert not signresult.is_final @pytest.mark.parametrize('unowned_utxo, wallet_cls', [ (True, SegwitLegacyWallet), (False, SegwitLegacyWallet), (True, SegwitWallet), (False, SegwitWallet), (True, LegacyWallet), (False, LegacyWallet), ]) def test_create_psbt_and_sign(setup_psbt_wallet, unowned_utxo, wallet_cls): """ Plan of test: 1. Create a wallet and source 3 destination addresses. 2. Make, and confirm, transactions that fund the 3 addrs. 3. Create a new tx spending 2 of those 3 utxos and spending another utxo we don't own (extra is optional per `unowned_utxo`). 4. Create a psbt using the above transaction and corresponding `spent_outs` field to fill in the redeem script. 5. Compare resulting PSBT with expected structure. 6. Use the wallet's sign_psbt method to sign the whole psbt, which means signing each input we own. 7. Check that each input is finalized as per expected. Check that the whole PSBT is or is not finalized as per whether there is an unowned utxo. 8. In case where whole psbt is finalized, attempt to broadcast the tx. """ # steps 1 and 2: wallet_service = make_wallets(1, [[3,0,0,0,0]], 1, wallet_cls=wallet_cls)[0]['wallet'] wallet_service.sync_wallet(fast=True) utxos = wallet_service.select_utxos(0, bitcoin.coins_to_satoshi(1.5)) # for legacy wallets, psbt creation requires querying for the spending # transaction: if wallet_cls == LegacyWallet: fulltxs = [] for utxo, v in utxos.items(): fulltxs.append(jm_single().bc_interface.get_deser_from_gettransaction( jm_single().bc_interface.get_transaction(utxo[0]))) assert len(utxos) == 2 u_utxos = {} if unowned_utxo: # note: tx creation uses the key only; psbt creation uses the value, # which can be fake here; we do not intend to attempt to fully # finalize a psbt with an unowned input. See # https://github.com/Simplexum/python-bitcointx/issues/30 # the redeem script creation (which is artificial) will be # avoided in future. priv = b"\xaa"*32 + b"\x01" pub = bitcoin.privkey_to_pubkey(priv) script = bitcoin.pubkey_to_p2sh_p2wpkh_script(pub) redeem_script = bitcoin.pubkey_to_p2wpkh_script(pub) u_utxos[(b"\xaa"*32, 12)] = {"value": 1000, "script": script} utxos.update(u_utxos) # outputs aren't interesting for this test (we selected 1.5 but will get 2): outs = [{"value": bitcoin.coins_to_satoshi(1.999), "address": wallet_service.get_addr(0,0,0)}] tx = bitcoin.mktx(list(utxos.keys()), outs) if wallet_cls != LegacyWallet: spent_outs = wallet_service.witness_utxos_to_psbt_utxos(utxos) force_witness_utxo=True else: spent_outs = fulltxs # the extra input is segwit: if unowned_utxo: spent_outs.extend( wallet_service.witness_utxos_to_psbt_utxos(u_utxos)) force_witness_utxo=False newpsbt = wallet_service.create_psbt_from_tx(tx, spent_outs, force_witness_utxo=force_witness_utxo) # see note above if unowned_utxo: newpsbt.inputs[-1].redeem_script = redeem_script print(bintohex(newpsbt.serialize())) print("human readable: ") print(wallet_service.human_readable_psbt(newpsbt)) # we cannot compare with a fixed expected result due to wallet randomization, but we can # check psbt structure: expected_inputs_length = 3 if unowned_utxo else 2 assert len(newpsbt.inputs) == expected_inputs_length assert len(newpsbt.outputs) == 1 # note: redeem_script field is a CScript which is a bytes instance, # so checking length is best way to check for existence (comparison # with None does not work): if wallet_cls == SegwitLegacyWallet: assert len(newpsbt.inputs[0].redeem_script) != 0 assert len(newpsbt.inputs[1].redeem_script) != 0 if unowned_utxo: assert newpsbt.inputs[2].redeem_script == redeem_script signed_psbt_and_signresult, err = wallet_service.sign_psbt( newpsbt.serialize(), with_sign_result=True) assert err is None signresult, signed_psbt = signed_psbt_and_signresult expected_signed_inputs = len(utxos) if not unowned_utxo else len(utxos)-1 assert signresult.num_inputs_signed == expected_signed_inputs assert signresult.num_inputs_final == expected_signed_inputs if not unowned_utxo: assert signresult.is_final # only in case all signed do we try to broadcast: extracted_tx = signed_psbt.extract_transaction().serialize() assert jm_single().bc_interface.pushtx(extracted_tx) else: # transaction extraction must fail for not-fully-signed psbts: with pytest.raises(ValueError) as e: extracted_tx = signed_psbt.extract_transaction() @pytest.mark.parametrize('payment_amt, wallet_cls_sender, wallet_cls_receiver', [ (0.05, SegwitLegacyWallet, SegwitLegacyWallet), #(0.95, SegwitLegacyWallet, SegwitWallet), #(0.05, SegwitWallet, SegwitLegacyWallet), #(0.95, SegwitWallet, SegwitWallet), ]) def test_payjoin_workflow(setup_psbt_wallet, payment_amt, wallet_cls_sender, wallet_cls_receiver): """ Workflow step 1: Create a payment from a wallet, and create a finalized PSBT. This step is fairly trivial as the functionality is built-in to PSBTWalletMixin. Note that only Segwit* wallets are supported for PayJoin. Workflow step 2: Receiver creates a new partially signed PSBT with the same amount and at least one more utxo. Workflow step 3: Given a partially signed PSBT created by a receiver, here the sender completes (co-signs) the PSBT they are given. Note this code is a PSBT functionality check, and does NOT include the detailed checks that the sender should perform before agreeing to sign (see: https://github.com/btcpayserver/btcpayserver-doc/blob/eaac676866a4d871eda5fd7752b91b88fdf849ff/Payjoin-spec.md#receiver-side ). """ wallet_r = make_wallets(1, [[3,0,0,0,0]], 1, wallet_cls=wallet_cls_receiver)[0]["wallet"] wallet_s = make_wallets(1, [[3,0,0,0,0]], 1, wallet_cls=wallet_cls_sender)[0]["wallet"] for w in [wallet_r, wallet_s]: w.sync_wallet(fast=True) # destination address for payment: destaddr = str(bitcoin.CCoinAddress.from_scriptPubKey( bitcoin.pubkey_to_p2wpkh_script(bitcoin.privkey_to_pubkey(b"\x01"*33)))) payment_amt = bitcoin.coins_to_satoshi(payment_amt) # *** STEP 1 *** # ************** # create a normal tx from the sender wallet: payment_psbt = direct_send(wallet_s, payment_amt, 0, destaddr, accept_callback=dummy_accept_callback, info_callback=dummy_info_callback, with_final_psbt=True) print("Initial payment PSBT created:\n{}".format( wallet_s.human_readable_psbt(payment_psbt))) # ensure that the payemnt amount is what was intended: out_amts = [x.nValue for x in payment_psbt.unsigned_tx.vout] # NOTE this would have to change for more than 2 outputs: assert any([out_amts[i] == payment_amt for i in [0, 1]]) # ensure that we can actually broadcast the created tx: # (note that 'extract_transaction' represents an implicit # PSBT finality check). extracted_tx = payment_psbt.extract_transaction().serialize() # don't want to push the tx right now, because of test structure # (in production code this isn't really needed, we will not # produce invalid payment transactions). res = jm_single().bc_interface.testmempoolaccept(bintohex(extracted_tx)) assert res[0]["allowed"], "Payment transaction was rejected from mempool." # *** STEP 2 *** # ************** # Simple receiver utxo choice heuristic. # For more generality we test with two receiver-utxos, not one. all_receiver_utxos = wallet_r.get_all_utxos() # TODO is there a less verbose way to get any 2 utxos from the dict? receiver_utxos_keys = list(all_receiver_utxos.keys())[:2] receiver_utxos = {k: v for k, v in all_receiver_utxos.items( ) if k in receiver_utxos_keys} # receiver will do other checks as discussed above, including payment # amount; as discussed above, this is out of the scope of this PSBT test. # construct unsigned tx for payjoin-psbt: payjoin_tx_inputs = [(x.prevout.hash[::-1], x.prevout.n) for x in payment_psbt.unsigned_tx.vin] payjoin_tx_inputs.extend(receiver_utxos.keys()) # find payment output and change output pay_out = None change_out = None for o in payment_psbt.unsigned_tx.vout: jm_out_fmt = {"value": o.nValue, "address": str(bitcoin.CCoinAddress.from_scriptPubKey( o.scriptPubKey))} if o.nValue == payment_amt: assert pay_out is None pay_out = jm_out_fmt else: assert change_out is None change_out = jm_out_fmt # we now know there were two outputs and know which is payment. # bump payment output with our input: outs = [pay_out, change_out] our_inputs_val = sum([v["value"] for _, v in receiver_utxos.items()]) pay_out["value"] += our_inputs_val print("we bumped the payment output value by: ", our_inputs_val) print("It is now: ", pay_out["value"]) unsigned_payjoin_tx = bitcoin.make_shuffled_tx(payjoin_tx_inputs, outs, version=payment_psbt.unsigned_tx.nVersion, locktime=payment_psbt.unsigned_tx.nLockTime) print("we created this unsigned tx: ") print(bitcoin.human_readable_transaction(unsigned_payjoin_tx)) # to create the PSBT we need the spent_outs for each input, # in the right order: spent_outs = [] for i, inp in enumerate(unsigned_payjoin_tx.vin): input_found = False for j, inp2 in enumerate(payment_psbt.unsigned_tx.vin): if inp.prevout == inp2.prevout: spent_outs.append(payment_psbt.inputs[j].utxo) input_found = True break if input_found: continue # if we got here this input is ours, we must find # it from our original utxo choice list: for ru in receiver_utxos.keys(): if (inp.prevout.hash[::-1], inp.prevout.n) == ru: spent_outs.append( wallet_r.witness_utxos_to_psbt_utxos( {ru: receiver_utxos[ru]})[0]) input_found = True break # there should be no other inputs: assert input_found r_payjoin_psbt = wallet_r.create_psbt_from_tx(unsigned_payjoin_tx, spent_outs=spent_outs) print("Receiver created payjoin PSBT:\n{}".format( wallet_r.human_readable_psbt(r_payjoin_psbt))) signresultandpsbt, err = wallet_r.sign_psbt(r_payjoin_psbt.serialize(), with_sign_result=True) assert not err, err signresult, receiver_signed_psbt = signresultandpsbt assert signresult.num_inputs_final == len(receiver_utxos) assert not signresult.is_final print("Receiver signing successful. Payjoin PSBT is now:\n{}".format( wallet_r.human_readable_psbt(receiver_signed_psbt))) # *** STEP 3 *** # ************** # take the half-signed PSBT, validate and co-sign: signresultandpsbt, err = wallet_s.sign_psbt( receiver_signed_psbt.serialize(), with_sign_result=True) assert not err, err signresult, sender_signed_psbt = signresultandpsbt print("Sender's final signed PSBT is:\n{}".format( wallet_s.human_readable_psbt(sender_signed_psbt))) assert signresult.is_final # broadcast the tx extracted_tx = sender_signed_psbt.extract_transaction().serialize() assert jm_single().bc_interface.pushtx(extracted_tx) """ test vector data for human readable parsing only, they are taken from bitcointx/tests/test_psbt.py and in turn taken from BIP174 test vectors. TODO add more, but note we are not testing functionality here. """ hr_test_vectors = { # PSBT with one P2PKH input. Outputs are empty "one-p2pkh": '70736274ff0100750200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf60000000000feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e1300000100fda5010100000000010289a3c71eab4d20e0371bbba4cc698fa295c9463afa2e397f8533ccb62f9567e50100000017160014be18d152a9b012039daf3da7de4f53349eecb985ffffffff86f8aa43a71dff1448893a530a7237ef6b4608bbb2dd2d0171e63aec6a4890b40100000017160014fe3e9ef1a745e974d902c4355943abcb34bd5353ffffffff0200c2eb0b000000001976a91485cff1097fd9e008bb34af709c62197b38978a4888ac72fef84e2c00000017a914339725ba21efd62ac753a9bcd067d6c7a6a39d05870247304402202712be22e0270f394f568311dc7ca9a68970b8025fdd3b240229f07f8a5f3a240220018b38d7dcd314e734c9276bd6fb40f673325bc4baa144c800d2f2f02db2765c012103d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f210502483045022100d12b852d85dcd961d2f5f4ab660654df6eedcc794c0c33ce5cc309ffb5fce58d022067338a8e0e1725c197fb1a88af59f51e44e4255b20167c8684031c05d1f2592a01210223b72beef0965d10be0778efecd61fcac6f79a4ea169393380734464f84f2ab300000000000000', # PSBT with one P2PKH input and one P2SH-P2WPKH input. # First input is signed and finalized. Outputs are empty "first-input-signed": '70736274ff0100a00200000002ab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40000000000feffffffab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40100000000feffffff02603bea0b000000001976a914768a40bbd740cbe81d988e71de2a4d5c71396b1d88ac8e240000000000001976a9146f4620b553fa095e721b9ee0efe9fa039cca459788ac000000000001076a47304402204759661797c01b036b25928948686218347d89864b719e1f7fcf57d1e511658702205309eabf56aa4d8891ffd111fdf1336f3a29da866d7f8486d75546ceedaf93190121035cdc61fc7ba971c0b501a646a2a83b102cb43881217ca682dc86e2d73fa882920001012000e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787010416001485d13537f2e265405a34dbafa9e3dda01fb82308000000', # PSBT with one P2PKH input which has a non-final scriptSig # and has a sighash type specified. Outputs are empty "nonfinal-scriptsig": '70736274ff0100750200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf60000000000feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e1300000100fda5010100000000010289a3c71eab4d20e0371bbba4cc698fa295c9463afa2e397f8533ccb62f9567e50100000017160014be18d152a9b012039daf3da7de4f53349eecb985ffffffff86f8aa43a71dff1448893a530a7237ef6b4608bbb2dd2d0171e63aec6a4890b40100000017160014fe3e9ef1a745e974d902c4355943abcb34bd5353ffffffff0200c2eb0b000000001976a91485cff1097fd9e008bb34af709c62197b38978a4888ac72fef84e2c00000017a914339725ba21efd62ac753a9bcd067d6c7a6a39d05870247304402202712be22e0270f394f568311dc7ca9a68970b8025fdd3b240229f07f8a5f3a240220018b38d7dcd314e734c9276bd6fb40f673325bc4baa144c800d2f2f02db2765c012103d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f210502483045022100d12b852d85dcd961d2f5f4ab660654df6eedcc794c0c33ce5cc309ffb5fce58d022067338a8e0e1725c197fb1a88af59f51e44e4255b20167c8684031c05d1f2592a01210223b72beef0965d10be0778efecd61fcac6f79a4ea169393380734464f84f2ab30000000001030401000000000000', # PSBT with one P2PKH input and one P2SH-P2WPKH input both with # non-final scriptSigs. P2SH-P2WPKH input's redeemScript is available. # Outputs filled. "mixed-inputs-nonfinal": '70736274ff0100a00200000002ab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40000000000feffffffab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40100000000feffffff02603bea0b000000001976a914768a40bbd740cbe81d988e71de2a4d5c71396b1d88ac8e240000000000001976a9146f4620b553fa095e721b9ee0efe9fa039cca459788ac00000000000100df0200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf6000000006a473044022070b2245123e6bf474d60c5b50c043d4c691a5d2435f09a34a7662a9dc251790a022001329ca9dacf280bdf30740ec0390422422c81cb45839457aeb76fc12edd95b3012102657d118d3357b8e0f4c2cd46db7b39f6d9c38d9a70abcb9b2de5dc8dbfe4ce31feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e13000001012000e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787010416001485d13537f2e265405a34dbafa9e3dda01fb8230800220202ead596687ca806043edc3de116cdf29d5e9257c196cd055cf698c8d02bf24e9910b4a6ba670000008000000080020000800022020394f62be9df19952c5587768aeb7698061ad2c4a25c894f47d8c162b4d7213d0510b4a6ba6700000080010000800200008000', # PSBT with one P2SH-P2WSH input of a 2-of-2 multisig, redeemScript, # witnessScript, and keypaths are available. Contains one signature. "2-2-multisig-p2wsh": '70736274ff0100550200000001279a2323a5dfb51fc45f220fa58b0fc13e1e3342792a85d7e36cd6333b5cbc390000000000ffffffff01a05aea0b000000001976a914ffe9c0061097cc3b636f2cb0460fa4fc427d2b4588ac0000000000010120955eea0b0000000017a9146345200f68d189e1adc0df1c4d16ea8f14c0dbeb87220203b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd4646304302200424b58effaaa694e1559ea5c93bbfd4a89064224055cdf070b6771469442d07021f5c8eb0fea6516d60b8acb33ad64ede60e8785bfb3aa94b99bdf86151db9a9a010104220020771fd18ad459666dd49f3d564e3dbc42f4c84774e360ada16816a8ed488d5681010547522103b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd462103de55d1e1dac805e3f8a58c1fbf9b94c02f3dbaafe127fefca4995f26f82083bd52ae220603b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd4610b4a6ba67000000800000008004000080220603de55d1e1dac805e3f8a58c1fbf9b94c02f3dbaafe127fefca4995f26f82083bd10b4a6ba670000008000000080050000800000', # PSBT with unknown types in the inputs "unknown-input-types": '70736274ff01003f0200000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000ffffffff010000000000000000036a010000000000000a0f0102030405060708090f0102030405060708090a0b0c0d0e0f0000', # PSBT with `PSBT_GLOBAL_XPUB` "global-xpub": '70736274ff01009d0100000002710ea76ab45c5cb6438e607e59cc037626981805ae9e0dfd9089012abb0be5350100000000ffffffff190994d6a8b3c8c82ccbcfb2fba4106aa06639b872a8d447465c0d42588d6d670000000000ffffffff0200e1f505000000001976a914b6bc2c0ee5655a843d79afedd0ccc3f7dd64340988ac605af405000000001600141188ef8e4ce0449eaac8fb141cbf5a1176e6a088000000004f010488b21e039e530cac800000003dbc8a5c9769f031b17e77fea1518603221a18fd18f2b9a54c6c8c1ac75cbc3502f230584b155d1c7f1cd45120a653c48d650b431b67c5b2c13f27d7142037c1691027569c503100008000000080000000800001011f00e1f5050000000016001433b982f91b28f160c920b4ab95e58ce50dda3a4a220203309680f33c7de38ea6a47cd4ecd66f1f5a49747c6ffb8808ed09039243e3ad5c47304402202d704ced830c56a909344bd742b6852dccd103e963bae92d38e75254d2bb424502202d86c437195df46c0ceda084f2a291c3da2d64070f76bf9b90b195e7ef28f77201220603309680f33c7de38ea6a47cd4ecd66f1f5a49747c6ffb8808ed09039243e3ad5c1827569c5031000080000000800000008000000000010000000001011f00e1f50500000000160014388fb944307eb77ef45197d0b0b245e079f011de220202c777161f73d0b7c72b9ee7bde650293d13f095bc7656ad1f525da5fd2e10b11047304402204cb1fb5f869c942e0e26100576125439179ae88dca8a9dc3ba08f7953988faa60220521f49ca791c27d70e273c9b14616985909361e25be274ea200d7e08827e514d01220602c777161f73d0b7c72b9ee7bde650293d13f095bc7656ad1f525da5fd2e10b1101827569c5031000080000000800000008000000000000000000000220202d20ca502ee289686d21815bd43a80637b0698e1fbcdbe4caed445f6c1a0a90ef1827569c50310000800000008000000080000000000400000000', # PSBT with proprietary values "proprietary-values": '70736274ff0100550200000001ab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40100000000feffffff018e240000000000001976a9146f4620b553fa095e721b9ee0efe9fa039cca459788ac0000000015fc0a676c6f62616c5f706678016d756c7469706c790563686965660001012000e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787010416001485d13537f2e265405a34dbafa9e3dda01fb823080ffc06696e5f706678fde80377686174056672616d650afc00fe40420f0061736b077361746f7368690012fc076f75745f706678feffffff01636f726e05746967657217fc076f75745f706678ffffffffffffffffff707570707905647269766500' } def test_hr_psbt(setup_psbt_wallet): bitcoin.select_chain_params("bitcoin") for k, v in hr_test_vectors.items(): print(PSBTWalletMixin.human_readable_psbt( bitcoin.PartiallySignedTransaction.from_binary(hextobin(v)))) bitcoin.select_chain_params("bitcoin/regtest") @pytest.fixture(scope="module") def setup_psbt_wallet(): load_test_config()
gpl-3.0
vipul-sharma20/oh-mainline
vendor/packages/whoosh/src/whoosh/filedb/multiproc.py
16
12210
# Copyright 2010 Matt Chaput. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. 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 MATT CHAPUT ``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 MATT CHAPUT 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. # # The views and conclusions contained in the software and documentation are # those of the authors and should not be interpreted as representing official # policies, either expressed or implied, of Matt Chaput. import os import tempfile from multiprocessing import Process, Queue, cpu_count from whoosh.compat import dump, load, xrange, iteritems from whoosh.filedb.filetables import LengthWriter, LengthReader from whoosh.filedb.fileindex import Segment from whoosh.filedb.filewriting import SegmentWriter from whoosh.filedb.pools import (imerge, read_run, PoolBase, TempfilePool) from whoosh.filedb.structfile import StructFile from whoosh.writing import IndexWriter # Multiprocessing writer class SegmentWritingTask(Process): def __init__(self, storage, indexname, segname, kwargs, jobqueue, resultqueue, firstjob=None): Process.__init__(self) self.storage = storage self.indexname = indexname self.segname = segname self.kwargs = kwargs self.jobqueue = jobqueue self.resultqueue = resultqueue self.firstjob = firstjob self.segment = None self.running = True def _add_file(self, args): writer = self.writer filename, length = args f = open(filename, "rb") for _ in xrange(length): writer.add_document(**load(f)) f.close() os.remove(filename) def run(self): jobqueue = self.jobqueue ix = self.storage.open_index(self.indexname) writer = self.writer = SegmentWriter(ix, _lk=False, name=self.segname, **self.kwargs) if self.firstjob: self._add_file(self.firstjob) while self.running: args = jobqueue.get() if args is None: break self._add_file(args) if not self.running: writer.cancel() else: writer.pool.finish(writer.termswriter, writer.docnum, writer.lengthfile) writer._close_all() self.resultqueue.put(writer._getsegment()) def cancel(self): self.running = False class MultiSegmentWriter(IndexWriter): def __init__(self, ix, procs=None, batchsize=100, dir=None, **kwargs): self.index = ix self.procs = procs or cpu_count() self.bufferlimit = batchsize self.dir = dir self.kwargs = kwargs self.kwargs["dir"] = dir self.segnames = [] self.tasks = [] self.jobqueue = Queue(self.procs * 4) self.resultqueue = Queue() self.docbuffer = [] self.writelock = ix.lock("WRITELOCK") self.writelock.acquire() info = ix._read_toc() self.schema = info.schema self.segment_number = info.segment_counter self.generation = info.generation + 1 self.segments = info.segments self.storage = ix.storage def _new_task(self, firstjob): ix = self.index self.segment_number += 1 segmentname = Segment.basename(ix.indexname, self.segment_number) task = SegmentWritingTask(ix.storage, ix.indexname, segmentname, self.kwargs, self.jobqueue, self.resultqueue, firstjob) self.tasks.append(task) task.start() return task def _enqueue(self): doclist = self.docbuffer fd, filename = tempfile.mkstemp(".doclist", dir=self.dir) f = os.fdopen(fd, "wb") for doc in doclist: dump(doc, f, -1) f.close() args = (filename, len(doclist)) if len(self.tasks) < self.procs: self._new_task(args) else: self.jobqueue.put(args) self.docbuffer = [] def cancel(self): try: for task in self.tasks: task.cancel() finally: self.writelock.release() def add_document(self, **fields): self.docbuffer.append(fields) if len(self.docbuffer) >= self.bufferlimit: self._enqueue() def commit(self, **kwargs): try: # index the remaining stuff in self.docbuffer self._enqueue() for task in self.tasks: self.jobqueue.put(None) for task in self.tasks: task.join() for task in self.tasks: taskseg = self.resultqueue.get() assert isinstance(taskseg, Segment), type(taskseg) self.segments.append(taskseg) self.jobqueue.close() self.resultqueue.close() from whoosh.filedb.fileindex import _write_toc, _clean_files _write_toc(self.storage, self.schema, self.index.indexname, self.generation, self.segment_number, self.segments) # Delete leftover files _clean_files(self.storage, self.index.indexname, self.generation, self.segments) finally: self.writelock.release() # Multiprocessing pool class PoolWritingTask(Process): def __init__(self, schema, dir, jobqueue, resultqueue, limitmb, firstjob=None): Process.__init__(self) self.schema = schema self.dir = dir self.jobqueue = jobqueue self.resultqueue = resultqueue self.limitmb = limitmb self.firstjob = firstjob def _add_file(self, filename, length): subpool = self.subpool f = open(filename, "rb") for _ in xrange(length): code, args = load(f) if code == 0: subpool.add_content(*args) elif code == 1: subpool.add_posting(*args) elif code == 2: subpool.add_field_length(*args) f.close() os.remove(filename) def run(self): jobqueue = self.jobqueue rqueue = self.resultqueue subpool = self.subpool = TempfilePool(self.schema, limitmb=self.limitmb, dir=self.dir) if self.firstjob: self._add_file(*self.firstjob) while True: arg1, arg2 = jobqueue.get() if arg1 is None: doccount = arg2 break else: self._add_file(arg1, arg2) lenfd, lenfilename = tempfile.mkstemp(".lengths", dir=subpool.dir) lenf = os.fdopen(lenfd, "wb") subpool._write_lengths(StructFile(lenf), doccount) subpool.dump_run() rqueue.put((subpool.runs, subpool.fieldlength_totals(), subpool.fieldlength_mins(), subpool.fieldlength_maxes(), lenfilename)) class MultiPool(PoolBase): def __init__(self, schema, dir=None, procs=2, limitmb=32, batchsize=100, **kw): PoolBase.__init__(self, schema, dir=dir) self._make_dir() self.procs = procs self.limitmb = limitmb self.jobqueue = Queue(self.procs * 4) self.resultqueue = Queue() self.tasks = [] self.buffer = [] self.bufferlimit = batchsize def _new_task(self, firstjob): task = PoolWritingTask(self.schema, self.dir, self.jobqueue, self.resultqueue, self.limitmb, firstjob=firstjob) self.tasks.append(task) task.start() return task def _enqueue(self): commandlist = self.buffer fd, filename = tempfile.mkstemp(".commands", dir=self.dir) f = os.fdopen(fd, "wb") for command in commandlist: dump(command, f, -1) f.close() args = (filename, len(commandlist)) if len(self.tasks) < self.procs: self._new_task(args) else: self.jobqueue.put(args) self.buffer = [] def _append(self, item): self.buffer.append(item) if len(self.buffer) > self.bufferlimit: self._enqueue() def add_content(self, *args): self._append((0, args)) def add_posting(self, *args): self.postingqueue.put((1, args)) def add_field_length(self, *args): self.postingqueue.put((2, args)) def cancel(self): for task in self.tasks: task.terminate() self.cleanup() def cleanup(self): self._clean_temp_dir() def finish(self, termswriter, doccount, lengthfile): if self.buffer: self._enqueue() _fieldlength_totals = self._fieldlength_totals if not self.tasks: return jobqueue = self.jobqueue rqueue = self.resultqueue for task in self.tasks: jobqueue.put((None, doccount)) for task in self.tasks: task.join() runs = [] lenfilenames = [] for task in self.tasks: truns, flentotals, flenmins, flenmaxes, lenfilename = rqueue.get() runs.extend(truns) lenfilenames.append(lenfilename) for fieldname, total in iteritems(flentotals): _fieldlength_totals[fieldname] += total for fieldname, length in iteritems(flenmins): if length < self._fieldlength_maxes.get(fieldname, 9999999999): self._fieldlength_mins[fieldname] = length for fieldname, length in flenmaxes.iteritems(): if length > self._fieldlength_maxes.get(fieldname, 0): self._fieldlength_maxes[fieldname] = length jobqueue.close() rqueue.close() lw = LengthWriter(lengthfile, doccount) for lenfilename in lenfilenames: sublengths = LengthReader(StructFile(open(lenfilename, "rb")), doccount) lw.add_all(sublengths) os.remove(lenfilename) lw.close() lengths = lw.reader() # if len(runs) >= self.procs * 2: # pool = Pool(self.procs) # tempname = lambda: tempfile.mktemp(suffix=".run", dir=self.dir) # while len(runs) >= self.procs * 2: # runs2 = [(runs[i:i+4], tempname()) # for i in xrange(0, len(runs), 4)] # if len(runs) % 4: # last = runs2.pop()[0] # runs2[-1][0].extend(last) # runs = pool.map(merge_runs, runs2) # pool.close() iterator = imerge([read_run(rname, count) for rname, count in runs]) total = sum(count for runname, count in runs) termswriter.add_iter(iterator, lengths.get) for runname, count in runs: os.remove(runname) self.cleanup()
agpl-3.0
ThirdProject/android_external_chromium_org
chrome/test/functional/tracing/timeline_model.py
69
1823
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import os class TimelineModel(object): """A proxy for about:tracing's TimelineModel class. Test authors should never need to know that this class is a proxy. """ @staticmethod def _EscapeForQuotedJavascriptExecution(js): # Poor man's string escape. return js.replace('\'', '\\\''); def __init__(self, js_executor, shim_id): self._js_executor = js_executor self._shim_id = shim_id # Warning: The JSON serialization process removes cyclic references. # TODO(eatnumber): regenerate these cyclic references on deserialization. def _CallModelMethod(self, method_name, *args): result = self._js_executor( """window.timelineModelShims['%s'].invokeMethod('%s', '%s')""" % ( self._shim_id, self._EscapeForQuotedJavascriptExecution(method_name), self._EscapeForQuotedJavascriptExecution(json.dumps(args)) ) ) if result['success']: return result['data'] # TODO(eatnumber): Make these exceptions more reader friendly. raise RuntimeError(result) def __del__(self): self._js_executor(""" window.timelineModelShims['%s'] = undefined; window.domAutomationController.send(''); """ % self._shim_id) def GetAllThreads(self): return self._CallModelMethod('getAllThreads') def GetAllCpus(self): return self._CallModelMethod('getAllCpus') def GetAllProcesses(self): return self._CallModelMethod('getAllProcesses') def GetAllCounters(self): return self._CallModelMethod('getAllCounters') def FindAllThreadsNamed(self, name): return self._CallModelMethod('findAllThreadsNamed', name);
bsd-3-clause
Big-B702/python-for-android
python-modules/twisted/twisted/web/html.py
57
1178
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """I hold HTML generation helpers. """ from twisted.python import log #t.w imports from twisted.web import resource import traceback, string from cStringIO import StringIO from microdom import escape def PRE(text): "Wrap <pre> tags around some text and HTML-escape it." return "<pre>"+escape(text)+"</pre>" def UL(lst): io = StringIO() io.write("<ul>\n") for el in lst: io.write("<li> %s</li>\n" % el) io.write("</ul>") return io.getvalue() def linkList(lst): io = StringIO() io.write("<ul>\n") for hr, el in lst: io.write('<li> <a href="%s">%s</a></li>\n' % (hr, el)) io.write("</ul>") return io.getvalue() def output(func, *args, **kw): """output(func, *args, **kw) -> html string Either return the result of a function (which presumably returns an HTML-legal string) or a sparse HTMLized error message and a message in the server log. """ try: return func(*args, **kw) except: log.msg("Error calling %r:" % (func,)) log.err() return PRE("An error occurred.")
apache-2.0
40223229/2015cdb_g9
gear.py
204
19237
#@+leo-ver=5-thin #@+node:office.20150407074720.1: * @file gear.py #@@language python #@@tabwidth -4 #@+<<declarations>> #@+node:office.20150407074720.2: ** <<declarations>> (application) #@@language python import cherrypy import os import sys # 這個程式要計算正齒輪的齒面寬, 資料庫連結希望使用 pybean 與 SQLite # 導入 pybean 模組與所要使用的 Store 及 SQLiteWriter 方法 from pybean import Store, SQLiteWriter import math # 確定程式檔案所在目錄, 在 Windows 有最後的反斜線 _curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) # 將所在目錄設為系統搜尋目錄 sys.path.append(_curdir) if 'OPENSHIFT_REPO_DIR' in os.environ.keys(): # while program is executed in OpenShift download_root_dir = os.environ['OPENSHIFT_DATA_DIR'] data_dir = os.environ['OPENSHIFT_DATA_DIR'] else: # while program is executed in localhost download_root_dir = _curdir + "/local_data/" data_dir = _curdir + "/local_data/" # 這是 Gear 設計資料表的定義 ''' lewis.db 中有兩個資料表, steel 與 lewis CREATE TABLE steel ( serialno INTEGER, unsno TEXT, aisino TEXT, treatment TEXT, yield_str INTEGER, tensile_str INTEGER, stretch_ratio INTEGER, sectional_shr INTEGER, brinell INTEGER ); CREATE TABLE lewis ( serialno INTEGER PRIMARY KEY NOT NULL, gearno INTEGER, type1 NUMERIC, type4 NUMERIC, type3 NUMERIC, type2 NUMERIC ); ''' #@-<<declarations>> #@+others #@+node:office.20150407074720.3: ** class Gear class Gear(object): #@+others #@+node:office.20150407074720.4: *3* __init__ def __init__(self): # hope to create downloads and images directories  if not os.path.isdir(download_root_dir+"downloads"): try: os.makedirs(download_root_dir+"downloads") except: print("mkdir error") if not os.path.isdir(download_root_dir+"images"): try: os.makedirs(download_root_dir+"images") except: print("mkdir error") if not os.path.isdir(download_root_dir+"tmp"): try: os.makedirs(download_root_dir+"tmp") except: print("mkdir error") #@+node:office.20150407074720.5: *3* default @cherrypy.expose def default(self, attr='default', *args, **kwargs): raise cherrypy.HTTPRedirect("/") #@+node:office.20150407074720.6: *3* index # 各組利用 index 引導隨後的程式執行 @cherrypy.expose def index(self, *args, **kwargs): # 進行資料庫檔案連結, 並且取出所有資料 try: # 利用 Store 建立資料庫檔案對應物件, 並且設定 frozen=True 表示不要開放動態資料表的建立 # 因為程式以 application 所在目錄執行, 因此利用相對目錄連結 lewis.db 資料庫檔案 SQLite連結 = Store(SQLiteWriter(_curdir+"/lewis.db", frozen=True)) #material = SQLite連結.find_one("steel","serialno = ?",[序號]) # str(SQLite連結.count("steel")) 將傳回 70, 表示資料庫中有 70 筆資料 material = SQLite連結.find("steel") # 所傳回的 material 為 iterator ''' outstring = "" for material_item in material: outstring += str(material_item.serialno) + ":" + material_item.unsno + "_" + material_item.treatment + "<br />" return outstring ''' except: return "抱歉! 資料庫無法連線<br />" outstring = ''' <form id=entry method=post action="gear_width"> 請填妥下列參數,以完成適當的齒尺寸大小設計。<br /> 馬達馬力:<input type=text name=horsepower id=horsepower value=100 size=10>horse power<br /> 馬達轉速:<input type=text name=rpm id=rpm value=1120 size=10>rpm<br /> 齒輪減速比: <input type=text name=ratio id=ratio value=4 size=10><br /> 齒形:<select name=toothtype id=toothtype> <option value=type1>壓力角20度,a=0.8,b=1.0 <option value=type2>壓力角20度,a=1.0,b=1.25 <option value=type3>壓力角25度,a=1.0,b=1.25 <option value=type4>壓力角25度,a=1.0,b=1.35 </select><br /> 安全係數:<input type=text name=safetyfactor id=safetyfactor value=3 size=10><br /> 齒輪材質:<select name=material_serialno id=material_serialno> ''' for material_item in material: outstring += "<option value=" + str(material_item.serialno) + ">UNS - " + \ material_item.unsno + " - " + material_item.treatment outstring += "</select><br />" outstring += "小齒輪齒數:<input type=text name=npinion id=npinion value=18 size=10><br />" outstring += "<input type=submit id=submit value=進行運算>" outstring += "</form>" return outstring #@+node:office.20150407074720.7: *3* interpolation @cherrypy.expose def interpolation(self, small_gear_no=18, gear_type=1): SQLite連結 = Store(SQLiteWriter(_curdir+"/lewis.db", frozen=True)) # 使用內插法求值 # 找出比目標齒數大的其中的最小的,就是最鄰近的大值 lewis_factor = SQLite連結.find_one("lewis","gearno > ?",[small_gear_no]) if(gear_type == 1): larger_formfactor = lewis_factor.type1 elif(gear_type == 2): larger_formfactor = lewis_factor.type2 elif(gear_type == 3): larger_formfactor = lewis_factor.type3 else: larger_formfactor = lewis_factor.type4 larger_toothnumber = lewis_factor.gearno # 找出比目標齒數小的其中的最大的,就是最鄰近的小值 lewis_factor = SQLite連結.find_one("lewis","gearno < ? order by gearno DESC",[small_gear_no]) if(gear_type == 1): smaller_formfactor = lewis_factor.type1 elif(gear_type == 2): smaller_formfactor = lewis_factor.type2 elif(gear_type == 3): smaller_formfactor = lewis_factor.type3 else: smaller_formfactor = lewis_factor.type4 smaller_toothnumber = lewis_factor.gearno calculated_factor = larger_formfactor + (small_gear_no - larger_toothnumber) * (larger_formfactor - smaller_formfactor) / (larger_toothnumber - smaller_toothnumber) # 只傳回小數點後五位數 return str(round(calculated_factor, 5)) #@+node:office.20150407074720.8: *3* gear_width # 改寫為齒面寬的設計函式 @cherrypy.expose def gear_width(self, horsepower=100, rpm=1000, ratio=4, toothtype=1, safetyfactor=2, material_serialno=1, npinion=18): SQLite連結 = Store(SQLiteWriter(_curdir+"/lewis.db", frozen=True)) outstring = "" # 根據所選用的齒形決定壓力角 if(toothtype == 1 or toothtype == 2): 壓力角 = 20 else: 壓力角 = 25 # 根據壓力角決定最小齒數 if(壓力角== 20): 最小齒數 = 18 else: 最小齒數 = 12 # 直接設最小齒數 if int(npinion) <= 最小齒數: npinion = 最小齒數 # 大於400的齒數則視為齒條(Rack) if int(npinion) >= 400: npinion = 400 # 根據所選用的材料查詢強度值 # 由 material之序號查 steel 表以得材料之降伏強度S單位為 kpsi 因此查得的值要成乘上1000 # 利用 Store 建立資料庫檔案對應物件, 並且設定 frozen=True 表示不要開放動態資料表的建立 #SQLite連結 = Store(SQLiteWriter("lewis.db", frozen=True)) # 指定 steel 資料表 steel = SQLite連結.new("steel") # 資料查詢 #material = SQLite連結.find_one("steel","unsno=? and treatment=?",[unsno, treatment]) material = SQLite連結.find_one("steel","serialno=?",[material_serialno]) # 列出 steel 資料表中的資料筆數 #print(SQLite連結.count("steel")) #print (material.yield_str) strengthstress = material.yield_str*1000 # 由小齒輪的齒數與齒形類別,查詢lewis form factor # 先查驗是否有直接對應值 on_table = SQLite連結.count("lewis","gearno=?",[npinion]) if on_table == 1: # 直接進入設計運算 #print("直接運算") #print(on_table) lewis_factor = SQLite連結.find_one("lewis","gearno=?",[npinion]) #print(lewis_factor.type1) # 根據齒形查出 formfactor 值 if(toothtype == 1): formfactor = lewis_factor.type1 elif(toothtype == 2): formfactor = lewis_factor.type2 elif(toothtype == 3): formfactor = lewis_factor.type3 else: formfactor = lewis_factor.type4 else: # 沒有直接對應值, 必須進行查表內插運算後, 再執行設計運算 #print("必須內插") #print(interpolation(npinion, gear_type)) formfactor = self.interpolation(npinion, toothtype) # 開始進行設計運算 ngear = int(npinion) * int(ratio) # 重要的最佳化設計---儘量用整數的diametralpitch # 先嘗試用整數算若 diametralpitch 找到100 仍無所獲則改用 0.25 作為增量再不行則宣告 fail counter = 0 i = 0.1 facewidth = 0 circularpitch = 0 while (facewidth <= 3 * circularpitch or facewidth >= 5 * circularpitch): diametralpitch = i #circularpitch = 3.14159/diametralpitch circularpitch = math.pi/diametralpitch pitchdiameter = int(npinion)/diametralpitch #pitchlinevelocity = 3.14159*pitchdiameter*rpm/12 pitchlinevelocity = math.pi*pitchdiameter * float(rpm)/12 transmittedload = 33000*float(horsepower)/pitchlinevelocity velocityfactor = 1200/(1200 + pitchlinevelocity) # formfactor is Lewis form factor # formfactor need to get from table 13-3 and determined ty teeth number and type of tooth # formfactor = 0.293 # 90 is the value get from table corresponding to material type facewidth = transmittedload*diametralpitch*float(safetyfactor)/velocityfactor/formfactor/strengthstress if(counter>5000): outstring += "超過5000次的設計運算,仍無法找到答案!<br />" outstring += "可能所選用的傳遞功率過大,或無足夠強度的材料可以使用!<br />" # 離開while迴圈 break i += 0.1 counter += 1 facewidth = round(facewidth, 4) if(counter<5000): # 先載入 cube 程式測試 #outstring = self.cube_weblink() # 再載入 gear 程式測試 outstring = self.gear_weblink() outstring += "進行"+str(counter)+"次重複運算後,得到合用的facewidth值為:"+str(facewidth) return outstring #@+node:office.20150407074720.9: *3* cube_weblink @cherrypy.expose def cube_weblink(self): outstring = '''<script type="text/javascript" src="/static/weblink/pfcUtils.js"></script> <script type="text/javascript" src="/static/weblink/wl_header.js"> document.writeln ("Error loading Pro/Web.Link header!"); </script> <script type="text/javascript" language="JavaScript"> // 若第三輸入為 false, 表示僅載入 session, 但是不顯示 // ret 為 model open return var ret = document.pwl.pwlMdlOpen("cube.prt", "v:/tmp", false); if (!ret.Status) { alert("pwlMdlOpen failed (" + ret.ErrorCode + ")"); } //將 ProE 執行階段設為變數 session var session = pfcGetProESession(); // 在視窗中打開零件檔案, 並且顯示出來 var window = session.OpenFile(pfcCreate("pfcModelDescriptor").CreateFromFileName("cube.prt")); var solid = session.GetModel("cube.prt",pfcCreate("pfcModelType").MDL_PART); var length,width,myf,myn,i,j,volume,count,d1Value,d2Value; // 將模型檔中的 length 變數設為 javascript 中的 length 變數 length = solid.GetParam("a1"); // 將模型檔中的 width 變數設為 javascript 中的 width 變數 width = solid.GetParam("a2"); //改變零件尺寸 //myf=20; //myn=20; volume=0; count=0; try { // 以下採用 URL 輸入對應變數 //createParametersFromArguments (); // 以下則直接利用 javascript 程式改變零件參數 for(i=0;i<=5;i++) { //for(j=0;j<=2;j++) //{ myf=20.0; myn=10.0+i*0.5; // 設定變數值, 利用 ModelItem 中的 CreateDoubleParamValue 轉換成 Pro/Web.Link 所需要的浮點數值 d1Value = pfcCreate ("MpfcModelItem").CreateDoubleParamValue(myf); d2Value = pfcCreate ("MpfcModelItem").CreateDoubleParamValue(myn); // 將處理好的變數值, 指定給對應的零件變數 length.Value = d1Value; width.Value = d2Value; //零件尺寸重新設定後, 呼叫 Regenerate 更新模型 solid.Regenerate(void null); //利用 GetMassProperty 取得模型的質量相關物件 properties = solid.GetMassProperty(void null); //volume = volume + properties.Volume; volume = properties.Volume; count = count + 1; alert("執行第"+count+"次,零件總體積:"+volume); // 將零件存為新檔案 var newfile = document.pwl.pwlMdlSaveAs("cube.prt", "v:/tmp", "cube"+count+".prt"); if (!newfile.Status) { alert("pwlMdlSaveAs failed (" + newfile.ErrorCode + ")"); } //} // 內圈 for 迴圈 } //外圈 for 迴圈 //alert("共執行:"+count+"次,零件總體積:"+volume); //alert("零件體積:"+properties.Volume); //alert("零件體積取整數:"+Math.round(properties.Volume)); } catch(err) { alert ("Exception occurred: "+pfcGetExceptionType (err)); } </script> ''' return outstring #@+node:office.20150407074720.10: *3* gear_weblink @cherrypy.expose def gear_weblink(self, facewidth=5, n=18): outstring = '''<script type="text/javascript" src="/static/weblink/pfcUtils.js"></script> <script type="text/javascript" src="/static/weblink/wl_header.js">// <![CDATA[ document.writeln ("Error loading Pro/Web.Link header!"); // ]]></script> <script type="text/javascript" language="JavaScript">// <![CDATA[ if (!pfcIsWindows()) netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); // 若第三輸入為 false, 表示僅載入 session, 但是不顯示 // ret 為 model open return var ret = document.pwl.pwlMdlOpen("gear.prt", "v:/", false); if (!ret.Status) { alert("pwlMdlOpen failed (" + ret.ErrorCode + ")"); } //將 ProE 執行階段設為變數 session var session = pfcGetProESession(); // 在視窗中打開零件檔案, 並且顯示出來 var window = session.OpenFile(pfcCreate("pfcModelDescriptor").CreateFromFileName("gear.prt")); var solid = session.GetModel("gear.prt",pfcCreate("pfcModelType").MDL_PART); var length,width,myf,myn,i,j,volume,count,d1Value,d2Value; // 將模型檔中的 length 變數設為 javascript 中的 length 變數 length = solid.GetParam("n"); // 將模型檔中的 width 變數設為 javascript 中的 width 變數 width = solid.GetParam("face_width"); //改變零件尺寸 //myf=20; //myn=20; volume=0; count=0; try { // 以下採用 URL 輸入對應變數 //createParametersFromArguments (); // 以下則直接利用 javascript 程式改變零件參數 for(i=0;i<=5;i++) { //for(j=0;j<=2;j++) //{ myf=25+i*2; myn=10.0+i*0.5; // 設定變數值, 利用 ModelItem 中的 CreateDoubleParamValue 轉換成 Pro/Web.Link 所需要的浮點數值 //d1Value = pfcCreate ("MpfcModelItem").CreateDoubleParamValue(myf); d1Value = pfcCreate ("MpfcModelItem").CreateIntParamValue(myf); d2Value = pfcCreate ("MpfcModelItem").CreateDoubleParamValue(myn); // 將處理好的變數值, 指定給對應的零件變數 length.Value = d1Value; width.Value = d2Value; //零件尺寸重新設定後, 呼叫 Regenerate 更新模型 solid.Regenerate(void null); //利用 GetMassProperty 取得模型的質量相關物件 properties = solid.GetMassProperty(void null); //volume = volume + properties.Volume; volume = properties.Volume; count = count + 1; alert("執行第"+count+"次,零件總體積:"+volume); // 將零件存為新檔案 var newfile = document.pwl.pwlMdlSaveAs("gear.prt", "v:/", "mygear_"+count+".prt"); if (!newfile.Status) { alert("pwlMdlSaveAs failed (" + newfile.ErrorCode + ")"); } //} // 內圈 for 迴圈 } //外圈 for 迴圈 //alert("共執行:"+count+"次,零件總體積:"+volume); //alert("零件體積:"+properties.Volume); //alert("零件體積取整數:"+Math.round(properties.Volume)); } catch(err) { alert ("Exception occurred: "+pfcGetExceptionType (err)); } // ]]></script> ''' return outstring #@-others #@-others root = Gear() # setup static, images and downloads directories application_conf = { '/static':{ 'tools.staticdir.on': True, 'tools.staticdir.dir': _curdir+"/static"}, '/images':{ 'tools.staticdir.on': True, 'tools.staticdir.dir': data_dir+"/images"}, '/downloads':{ 'tools.staticdir.on': True, 'tools.staticdir.dir': data_dir+"/downloads"} } # if inOpenshift ('OPENSHIFT_REPO_DIR' exists in environment variables) or not inOpenshift if __name__ == '__main__': if 'OPENSHIFT_REPO_DIR' in os.environ.keys(): # operate in OpenShift application = cherrypy.Application(root, config = application_conf) else: # operate in localhost cherrypy.quickstart(root, config = application_conf) #@-leo
gpl-2.0
krafczyk/spack
var/spack/repos/builtin/packages/py-qtconsole/package.py
4
2032
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of 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 program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class PyQtconsole(PythonPackage): """Jupyter Qt console""" homepage = "http://ipython.org" url = "https://pypi.io/packages/source/q/qtconsole/qtconsole-4.2.1.tar.gz" version('4.2.1', 'c08ebebc7a60629ebadf685361ca0798') variant('doc', default=False, description='Build documentation') depends_on('py-ipykernel@4.1:', type=('build', 'run')) depends_on('py-jupyter-client@4.1:', type=('build', 'run')) depends_on('py-jupyter-core', type=('build', 'run')) depends_on('py-pygments', type=('build', 'run')) depends_on('py-traitlets', type=('build', 'run')) depends_on('py-sphinx@1.3:', type=('build', 'run'), when='+docs') depends_on('py-mock', type='test', when='^python@2.7:2.8')
lgpl-2.1
mitmedialab/MediaCloud-Web-Tools
server/util/request.py
1
3666
import logging import os from functools import wraps from flask import jsonify, request from mediacloud.error import MCException logger = logging.getLogger(__name__) def validate_params_exist(form, params): for param in params: if param not in form: raise ValueError('Missing required value for '+param) def json_error_response(message, status_code=400): response = jsonify({ 'statusCode': status_code, 'message': message, }) response.status_code = status_code return response def filters_from_args(request_args): """ Helper to centralize reading filters from url params """ timespans_id = safely_read_arg('timespanId') snapshots_id = safely_read_arg('snapshotId') foci_id = safely_read_arg('focusId') q = request_args['q'] if ('q' in request_args) and (request_args['q'] != 'undefined') else None return snapshots_id, timespans_id, foci_id, q def arguments_required(*expected_args): """ Handy decorator for ensuring that request params exist """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: logger.debug(request.args) validate_params_exist(request.args, expected_args) return func(*args, **kwargs) except ValueError as e: logger.exception("Missing a required arg") return json_error_response(e.args[0]) return wrapper return decorator def form_fields_required(*expected_form_fields): """ Handy decorator for ensuring that the form has the fields you need """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: logger.debug(request.form) validate_params_exist(request.form, expected_form_fields) return func(*args, **kwargs) except ValueError as e: logger.exception("Missing a required form field") return json_error_response(e.args[0]) return wrapper return decorator def api_error_handler(func): """ Handy decorator that catches any exception from the Media Cloud API and sends it back to the browser as a nicely formatted JSON error. The idea is that the client code can catch these at a low level and display error messages. """ @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except MCException as e: logger.exception(e) return json_error_response(e.message, e.status_code) return wrapper def is_csv(filename): filename, file_extension = os.path.splitext(filename) return file_extension.lower() in ['.csv'] def csv_required(func): """ Validates a file is supplied in the request and that it has a csv extension. """ @wraps(func) def wrapper(*args, **kwargs): try: if 'file' not in request.files: return json_error_response('No file part') uploaded_file = request.files['file'] if uploaded_file.filename == '': return json_error_response('No selected file') if not (uploaded_file and is_csv(uploaded_file.filename)): return json_error_response('Invalid file') return func(*args, **kwargs) except MCException as e: logger.exception(e) return json_error_response(e.message, e.status_code) return wrapper def safely_read_arg(arg_name, default=None): return request.args[arg_name] if arg_name in request.args else default
apache-2.0
GeoNode/geonode
geonode/layers/populate_layers_data.py
4
6742
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 <http://www.gnu.org/licenses/>. # ######################################################################### from django.conf import settings from geonode.layers.models import Style, Attribute, Layer ogc_location = settings.OGC_SERVER['default']['LOCATION'] styles = [{"name": "test_style_1", "sld_url": f"{ogc_location}rest/styles/test_style.sld", "sld_body": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sld:StyledLayerDescriptor \ xmlns=\"http://www.opengis.net/sld\" xmlns:sld=\"http://www.opengis.net/sld\" \ xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:gml=\"http://www.opengis.net/gml\" \ version=\"1.0.0\"><sld:NamedLayer><sld:Name>test_style_1</sld:Name><sld:UserStyle>\ <sld:Name>test_style_1</sld:Name><sld:Title/><sld:FeatureTypeStyle><sld:Name>name</sld:Name>\ <sld:Rule><sld:PolygonSymbolizer><sld:Fill><sld:CssParameter name=\"fill\">#888800</sld:CssParameter>\ </sld:Fill><sld:Stroke><sld:CssParameter name=\"stroke\">#ffffbb</sld:CssParameter>\ <sld:CssParameter name=\"stroke-width\">0.7</sld:CssParameter></sld:Stroke>\ </sld:PolygonSymbolizer></sld:Rule></sld:FeatureTypeStyle></sld:UserStyle>\ </sld:NamedLayer></sld:StyledLayerDescriptor>", }, {"name": "test_style_2", "sld_url": f"{ogc_location}rest/styles/test_style.sld", "sld_body": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sld:StyledLayerDescriptor \ xmlns=\"http://www.opengis.net/sld\" xmlns:sld=\"http://www.opengis.net/sld\" \ xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:gml=\"http://www.opengis.net/gml\" \ version=\"1.0.0\"><sld:NamedLayer><sld:Name>test_style_2</sld:Name><sld:UserStyle>\ <sld:Name>test_style_2</sld:Name><sld:Title/><sld:FeatureTypeStyle><sld:Name>name</sld:Name>\ <sld:Rule><sld:PolygonSymbolizer><sld:Fill><sld:CssParameter name=\"fill\">#888800</sld:CssParameter>\ </sld:Fill><sld:Stroke><sld:CssParameter name=\"stroke\">#ffffbb</sld:CssParameter>\ <sld:CssParameter name=\"stroke-width\">0.7</sld:CssParameter></sld:Stroke></sld:PolygonSymbolizer>\ </sld:Rule></sld:FeatureTypeStyle></sld:UserStyle></sld:NamedLayer></sld:StyledLayerDescriptor>", }, {"name": "test_style_3", "sld_url": f"{ogc_location}rest/styles/test_style.sld", "sld_body": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sld:StyledLayerDescriptor \ xmlns=\"http://www.opengis.net/sld\" xmlns:sld=\"http://www.opengis.net/sld\" \ xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:gml=\"http://www.opengis.net/gml\" \ version=\"1.0.0\"><sld:NamedLayer><sld:Name>test_style_3</sld:Name><sld:UserStyle>\ <sld:Name>test_style_3</sld:Name><sld:Title/><sld:FeatureTypeStyle><sld:Name>name</sld:Name>\ <sld:Rule><sld:PolygonSymbolizer><sld:Fill><sld:CssParameter name=\"fill\">#888800</sld:CssParameter>\ </sld:Fill><sld:Stroke><sld:CssParameter name=\"stroke\">#ffffbb</sld:CssParameter><sld:CssParameter \ name=\"stroke-width\">0.7</sld:CssParameter></sld:Stroke></sld:PolygonSymbolizer></sld:Rule>\ </sld:FeatureTypeStyle></sld:UserStyle></sld:NamedLayer></sld:StyledLayerDescriptor>", }, {"name": "Evaluación", "sld_url": f"{ogc_location}rest/styles/test_style.sld", "sld_body": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sld:StyledLayerDescriptor \ xmlns=\"http://www.opengis.net/sld\" xmlns:sld=\"http://www.opengis.net/sld\" \ xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:gml=\"http://www.opengis.net/gml\" version=\"1.0.0\">\ <sld:NamedLayer><sld:Name>test_style_3</sld:Name><sld:UserStyle><sld:Name>test_style_3</sld:Name>\ <sld:Title/><sld:FeatureTypeStyle><sld:Name>name</sld:Name><sld:Rule><sld:PolygonSymbolizer><sld:Fill>\ <sld:CssParameter name=\"fill\">#888800</sld:CssParameter></sld:Fill><sld:Stroke><sld:CssParameter \ name=\"stroke\">#ffffbb</sld:CssParameter><sld:CssParameter name=\"stroke-width\">0.7</sld:CssParameter>\ </sld:Stroke></sld:PolygonSymbolizer></sld:Rule></sld:FeatureTypeStyle></sld:UserStyle></sld:NamedLayer>\ </sld:StyledLayerDescriptor>", }] attributes = [ { "attribute": 'N\xfamero_De_M\xe9dicos', "attribute_label": 'N\xfamero_De_M\xe9dicos', "attribute_type": "xsd:string", "visible": True, "display_order": 4 }, { "attribute": "the_geom", "attribute_label": "Shape", "attribute_type": "gml:Geometry", "visible": False, "display_order": 3 }, { "attribute": "description", "attribute_label": "Description", "attribute_type": "xsd:string", "visible": True, "display_order": 2 }, { "attribute": "place_name", "attribute_label": "Place Name", "attribute_type": "xsd:string", "visible": True, "display_order": 1 } ] def create_layer_data(object_id=None): layer = Layer.objects.get(pk=object_id) if object_id else\ Layer.objects.all().first() for style in styles: new_style = Style.objects.create( name=style['name'], sld_url=style['sld_url'], sld_body=style['sld_body']) layer.styles.add(new_style) layer.default_style = new_style layer.save() for attr in attributes: Attribute.objects.create(layer=layer, attribute=attr['attribute'], attribute_label=attr['attribute_label'], attribute_type=attr['attribute_type'], visible=attr['visible'], display_order=attr['display_order'] )
gpl-3.0
CiscoSystems/tempest
tempest/api/object_storage/test_crossdomain.py
5
2167
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # Author: Joe H. Rahme <joe.hakim.rahme@enovance.com> # # 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 tempest.api.object_storage import base from tempest.common import custom_matchers from tempest import test class CrossdomainTest(base.BaseObjectTest): @classmethod def resource_setup(cls): super(CrossdomainTest, cls).resource_setup() cls.xml_start = '<?xml version="1.0"?>\n' \ '<!DOCTYPE cross-domain-policy SYSTEM ' \ '"http://www.adobe.com/xml/dtds/cross-domain-policy.' \ 'dtd" >\n<cross-domain-policy>\n' cls.xml_end = "</cross-domain-policy>" def setUp(self): super(CrossdomainTest, self).setUp() # Turning http://.../v1/foobar into http://.../ self.account_client.skip_path() @test.attr('gate') @test.requires_ext(extension='crossdomain', service='object') def test_get_crossdomain_policy(self): resp, body = self.account_client.get("crossdomain.xml", {}) self.assertTrue(body.startswith(self.xml_start) and body.endswith(self.xml_end)) # The target of the request is not any Swift resource. Therefore, the # existence of response header is checked without a custom matcher. self.assertIn('content-length', resp) self.assertIn('content-type', resp) self.assertIn('x-trans-id', resp) self.assertIn('date', resp) # Check only the format of common headers with custom matcher self.assertThat(resp, custom_matchers.AreAllWellFormatted())
apache-2.0
mattclay/ansible-modules-core
network/nxos/nxos_ntp_options.py
13
15517
#!/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 <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: nxos_ntp_options version_added: "2.2" short_description: Manages NTP options. description: - Manages NTP options, e.g. authoritative server and logging. extends_documentation_fragment: nxos author: - Jason Edelman (@jedelman8) notes: - At least one of C(master) or C(logging) params must be supplied. - When C(state=absent), boolean parameters are flipped, e.g. C(master=true) will disable the authoritative server. - When C(state=absent) and C(master=true), the stratum will be removed as well. - When C(state=absent) and C(master=false), the stratum will be configured to its default value, 8. options: master: description: - Sets whether the device is an authoritative NTP server. required: false default: null choices: ['true','false'] stratum: description: - If C(master=true), an optional stratum can be supplied (1-15). The device default is 8. required: false default: null logging: description: - Sets whether NTP logging is enabled on the device. required: false default: null choices: ['true','false'] state: description: - Manage the state of the resource. required: false default: present choices: ['present','absent'] ''' EXAMPLES = ''' # Basic NTP options configuration - nxos_ntp_options: master: true stratum: 12 logging: false host: "{{ inventory_hostname }}" username: "{{ un }}" password: "{{ pwd }}" ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: always type: dict sample: {"logging": false, "master": true, "stratum": "11"} existing: description: - k/v pairs of existing ntp options type: dict sample: {"logging": true, "master": true, "stratum": "8"} end_state: description: k/v pairs of ntp options after module execution returned: always type: dict sample: {"logging": false, "master": true, "stratum": "11"} updates: description: command sent to the device returned: always type: list sample: ["no ntp logging", "ntp master 11"] changed: description: check to see if a change was made on the device returned: always type: boolean sample: true ''' import json # COMMON CODE FOR MIGRATION import re from ansible.module_utils.basic import get_exception from ansible.module_utils.netcfg import NetworkConfig, ConfigLine from ansible.module_utils.shell import ShellError try: from ansible.module_utils.nxos import get_module except ImportError: from ansible.module_utils.nxos import NetworkModule def to_list(val): if isinstance(val, (list, tuple)): return list(val) elif val is not None: return [val] else: return list() class CustomNetworkConfig(NetworkConfig): def expand_section(self, configobj, S=None): if S is None: S = list() S.append(configobj) for child in configobj.children: if child in S: continue self.expand_section(child, S) return S def get_object(self, path): for item in self.items: if item.text == path[-1]: parents = [p.text for p in item.parents] if parents == path[:-1]: return item def to_block(self, section): return '\n'.join([item.raw for item in section]) def get_section(self, path): try: section = self.get_section_objects(path) return self.to_block(section) except ValueError: return list() def get_section_objects(self, path): if not isinstance(path, list): path = [path] obj = self.get_object(path) if not obj: raise ValueError('path does not exist in config') return self.expand_section(obj) def add(self, lines, parents=None): """Adds one or lines of configuration """ ancestors = list() offset = 0 obj = None ## global config command if not parents: for line in to_list(lines): item = ConfigLine(line) item.raw = line if item not in self.items: self.items.append(item) else: for index, p in enumerate(parents): try: i = index + 1 obj = self.get_section_objects(parents[:i])[0] ancestors.append(obj) except ValueError: # add parent to config offset = index * self.indent obj = ConfigLine(p) obj.raw = p.rjust(len(p) + offset) if ancestors: obj.parents = list(ancestors) ancestors[-1].children.append(obj) self.items.append(obj) ancestors.append(obj) # add child objects for line in to_list(lines): # check if child already exists for child in ancestors[-1].children: if child.text == line: break else: offset = len(parents) * self.indent item = ConfigLine(line) item.raw = line.rjust(len(line) + offset) item.parents = ancestors ancestors[-1].children.append(item) self.items.append(item) def get_network_module(**kwargs): try: return get_module(**kwargs) except NameError: return NetworkModule(**kwargs) def get_config(module, include_defaults=False): config = module.params['config'] if not config: try: config = module.get_config() except AttributeError: defaults = module.params['include_defaults'] config = module.config.get_config(include_defaults=defaults) return CustomNetworkConfig(indent=2, contents=config) def load_config(module, candidate): config = get_config(module) commands = candidate.difference(config) commands = [str(c).strip() for c in commands] save_config = module.params['save'] result = dict(changed=False) if commands: if not module.check_mode: try: module.configure(commands) except AttributeError: module.config(commands) if save_config: try: module.config.save_config() except AttributeError: module.execute(['copy running-config startup-config']) result['changed'] = True result['updates'] = commands return result # END OF COMMON CODE def execute_config_command(commands, module): try: module.configure(commands) except ShellError: clie = get_exception() module.fail_json(msg='Error sending CLI commands', error=str(clie), commands=commands) except AttributeError: try: commands.insert(0, 'configure') module.cli.add_commands(commands, output='config') module.cli.run_commands() except ShellError: clie = get_exception() module.fail_json(msg='Error sending CLI commands', error=str(clie), commands=commands) def get_cli_body_ssh(command, response, module): """Get response for when transport=cli. This is kind of a hack and mainly needed because these modules were originally written for NX-API. And not every command supports "| json" when using cli/ssh. As such, we assume if | json returns an XML string, it is a valid command, but that the resource doesn't exist yet. Instead, the output will be a raw string when issuing commands containing 'show run'. """ if 'xml' in response[0] or response[0] == '\n': body = [] elif 'show run' in command: body = response else: try: body = [json.loads(response[0])] except ValueError: module.fail_json(msg='Command does not support JSON output', command=command) return body def execute_show(cmds, module, command_type=None): command_type_map = { 'cli_show': 'json', 'cli_show_ascii': 'text' } try: if command_type: response = module.execute(cmds, command_type=command_type) else: response = module.execute(cmds) except ShellError: clie = get_exception() module.fail_json(msg='Error sending {0}'.format(cmds), error=str(clie)) except AttributeError: try: if command_type: command_type = command_type_map.get(command_type) module.cli.add_commands(cmds, output=command_type) response = module.cli.run_commands() else: module.cli.add_commands(cmds, raw=True) response = module.cli.run_commands() except ShellError: clie = get_exception() module.fail_json(msg='Error sending {0}'.format(cmds), error=str(clie)) return response def execute_show_command(command, module, command_type='cli_show'): if module.params['transport'] == 'cli': if 'show run' not in command: command += ' | json' cmds = [command] response = execute_show(cmds, module) body = get_cli_body_ssh(command, response, module) elif module.params['transport'] == 'nxapi': cmds = [command] body = execute_show(cmds, module, command_type=command_type) return body def flatten_list(command_lists): flat_command_list = [] for command in command_lists: if isinstance(command, list): flat_command_list.extend(command) else: flat_command_list.append(command) return flat_command_list def apply_key_map(key_map, table): new_dict = {} for key, value in table.items(): new_key = key_map.get(key) if new_key: value = table.get(key) if value: new_dict[new_key] = str(value) else: new_dict[new_key] = value return new_dict def get_ntp_master(module): command = 'show run | inc ntp.master' master_string = execute_show_command(command, module, command_type='cli_show_ascii') if master_string: if master_string[0]: master = True else: master = False else: master = False if master is True: stratum = str(master_string[0].split()[2]) else: stratum = None return master, stratum def get_ntp_log(module): command = 'show ntp logging' body = execute_show_command(command, module)[0] logging_string = body['loggingstatus'] if 'enabled' in logging_string: ntp_log = True else: ntp_log = False return ntp_log def get_ntp_options(module): existing = {} existing['logging'] = get_ntp_log(module) existing['master'], existing['stratum'] = get_ntp_master(module) return existing def config_ntp_options(delta, flip=False): master = delta.get('master') stratum = delta.get('stratum') log = delta.get('logging') ntp_cmds = [] if flip: log = not log master = not master if log is not None: if log is True: ntp_cmds.append('ntp logging') elif log is False: ntp_cmds.append('no ntp logging') if master is not None: if master is True: if not stratum: stratum = '' ntp_cmds.append('ntp master {0}'.format(stratum)) elif master is False: ntp_cmds.append('no ntp master') return ntp_cmds def main(): argument_spec = dict( master=dict(required=False, type='bool'), stratum=dict(type='str'), logging=dict(required=False, type='bool'), state=dict(choices=['absent', 'present'], default='present'), ) module = get_network_module(argument_spec=argument_spec, required_one_of=[['master', 'logging']], supports_check_mode=True) master = module.params['master'] stratum = module.params['stratum'] logging = module.params['logging'] state = module.params['state'] if stratum: if master is None: module.fail_json(msg='The master param must be supplied when ' 'stratum is supplied') try: stratum_int = int(stratum) if stratum_int < 1 or stratum_int > 15: raise ValueError except ValueError: module.fail_json(msg='Stratum must be an integer between 1 and 15') existing = get_ntp_options(module) end_state = existing args = dict(master=master, stratum=stratum, logging=logging) changed = False proposed = dict((k, v) for k, v in args.iteritems() if v is not None) if master is False: proposed['stratum'] = None stratum = None delta = dict(set(proposed.iteritems()).difference(existing.iteritems())) delta_stratum = delta.get('stratum') if delta_stratum: delta['master'] = True commands = [] if state == 'present': if delta: command = config_ntp_options(delta) if command: commands.append(command) elif state == 'absent': if existing: isection = dict(set(proposed.iteritems()).intersection( existing.iteritems())) command = config_ntp_options(isection, flip=True) if command: commands.append(command) cmds = flatten_list(commands) if cmds: if module.check_mode: module.exit_json(changed=True, commands=cmds) else: changed = True execute_config_command(cmds, module) end_state = get_ntp_options(module) if 'configure' in cmds: cmds.pop(0) results = {} results['proposed'] = proposed results['existing'] = existing results['updates'] = cmds results['changed'] = changed results['end_state'] = end_state module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
mancoast/CPythonPyc_test
cpython/252_test_hexoct.py
34
4922
"""Test correct treatment of hex/oct constants. This is complex because of changes due to PEP 237. """ import sys platform_long_is_32_bits = sys.maxint == 2147483647 import unittest from test import test_support import warnings warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning, "<string>") class TextHexOct(unittest.TestCase): def test_hex_baseline(self): # Baseline tests self.assertEqual(0x0, 0) self.assertEqual(0x10, 16) if platform_long_is_32_bits: self.assertEqual(0x7fffffff, 2147483647) else: self.assertEqual(0x7fffffffffffffff, 9223372036854775807) # Ditto with a minus sign and parentheses self.assertEqual(-(0x0), 0) self.assertEqual(-(0x10), -16) if platform_long_is_32_bits: self.assertEqual(-(0x7fffffff), -2147483647) else: self.assertEqual(-(0x7fffffffffffffff), -9223372036854775807) # Ditto with a minus sign and NO parentheses self.assertEqual(-0x0, 0) self.assertEqual(-0x10, -16) if platform_long_is_32_bits: self.assertEqual(-0x7fffffff, -2147483647) else: self.assertEqual(-0x7fffffffffffffff, -9223372036854775807) def test_hex_unsigned(self): if platform_long_is_32_bits: # Positive constants self.assertEqual(0x80000000, 2147483648L) self.assertEqual(0xffffffff, 4294967295L) # Ditto with a minus sign and parentheses self.assertEqual(-(0x80000000), -2147483648L) self.assertEqual(-(0xffffffff), -4294967295L) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-0x80000000, -2147483648L) self.assertEqual(-0xffffffff, -4294967295L) else: # Positive constants self.assertEqual(0x8000000000000000, 9223372036854775808L) self.assertEqual(0xffffffffffffffff, 18446744073709551615L) # Ditto with a minus sign and parentheses self.assertEqual(-(0x8000000000000000), -9223372036854775808L) self.assertEqual(-(0xffffffffffffffff), -18446744073709551615L) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-0x8000000000000000, -9223372036854775808L) self.assertEqual(-0xffffffffffffffff, -18446744073709551615L) def test_oct_baseline(self): # Baseline tests self.assertEqual(00, 0) self.assertEqual(020, 16) if platform_long_is_32_bits: self.assertEqual(017777777777, 2147483647) else: self.assertEqual(0777777777777777777777, 9223372036854775807) # Ditto with a minus sign and parentheses self.assertEqual(-(00), 0) self.assertEqual(-(020), -16) if platform_long_is_32_bits: self.assertEqual(-(017777777777), -2147483647) else: self.assertEqual(-(0777777777777777777777), -9223372036854775807) # Ditto with a minus sign and NO parentheses self.assertEqual(-00, 0) self.assertEqual(-020, -16) if platform_long_is_32_bits: self.assertEqual(-017777777777, -2147483647) else: self.assertEqual(-0777777777777777777777, -9223372036854775807) def test_oct_unsigned(self): if platform_long_is_32_bits: # Positive constants self.assertEqual(020000000000, 2147483648L) self.assertEqual(037777777777, 4294967295L) # Ditto with a minus sign and parentheses self.assertEqual(-(020000000000), -2147483648L) self.assertEqual(-(037777777777), -4294967295L) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-020000000000, -2147483648L) self.assertEqual(-037777777777, -4294967295L) else: # Positive constants self.assertEqual(01000000000000000000000, 9223372036854775808L) self.assertEqual(01777777777777777777777, 18446744073709551615L) # Ditto with a minus sign and parentheses self.assertEqual(-(01000000000000000000000), -9223372036854775808L) self.assertEqual(-(01777777777777777777777), -18446744073709551615L) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-01000000000000000000000, -9223372036854775808L) self.assertEqual(-01777777777777777777777, -18446744073709551615L) def test_main(): test_support.run_unittest(TextHexOct) if __name__ == "__main__": test_main()
gpl-3.0
MoritzS/django
tests/staticfiles_tests/test_finders.py
29
3831
import os from django.conf import settings from django.contrib.staticfiles import finders, storage from django.core.exceptions import ImproperlyConfigured from django.test import SimpleTestCase, override_settings from .cases import StaticFilesTestCase from .settings import TEST_ROOT class TestFinders: """ Base finder test mixin. On Windows, sometimes the case of the path we ask the finders for and the path(s) they find can differ. Compare them using os.path.normcase() to avoid false negatives. """ def test_find_first(self): src, dst = self.find_first found = self.finder.find(src) self.assertEqual(os.path.normcase(found), os.path.normcase(dst)) def test_find_all(self): src, dst = self.find_all found = self.finder.find(src, all=True) found = [os.path.normcase(f) for f in found] dst = [os.path.normcase(d) for d in dst] self.assertEqual(found, dst) class TestFileSystemFinder(TestFinders, StaticFilesTestCase): """ Test FileSystemFinder. """ def setUp(self): super().setUp() self.finder = finders.FileSystemFinder() test_file_path = os.path.join(TEST_ROOT, 'project', 'documents', 'test', 'file.txt') self.find_first = (os.path.join('test', 'file.txt'), test_file_path) self.find_all = (os.path.join('test', 'file.txt'), [test_file_path]) class TestAppDirectoriesFinder(TestFinders, StaticFilesTestCase): """ Test AppDirectoriesFinder. """ def setUp(self): super().setUp() self.finder = finders.AppDirectoriesFinder() test_file_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test', 'file1.txt') self.find_first = (os.path.join('test', 'file1.txt'), test_file_path) self.find_all = (os.path.join('test', 'file1.txt'), [test_file_path]) class TestDefaultStorageFinder(TestFinders, StaticFilesTestCase): """ Test DefaultStorageFinder. """ def setUp(self): super().setUp() self.finder = finders.DefaultStorageFinder( storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT)) test_file_path = os.path.join(settings.MEDIA_ROOT, 'media-file.txt') self.find_first = ('media-file.txt', test_file_path) self.find_all = ('media-file.txt', [test_file_path]) @override_settings( STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder'], STATICFILES_DIRS=[os.path.join(TEST_ROOT, 'project', 'documents')], ) class TestMiscFinder(SimpleTestCase): """ A few misc finder tests. """ def test_get_finder(self): self.assertIsInstance(finders.get_finder( 'django.contrib.staticfiles.finders.FileSystemFinder'), finders.FileSystemFinder) def test_get_finder_bad_classname(self): with self.assertRaises(ImportError): finders.get_finder('django.contrib.staticfiles.finders.FooBarFinder') def test_get_finder_bad_module(self): with self.assertRaises(ImportError): finders.get_finder('foo.bar.FooBarFinder') def test_cache(self): finders.get_finder.cache_clear() for n in range(10): finders.get_finder('django.contrib.staticfiles.finders.FileSystemFinder') cache_info = finders.get_finder.cache_info() self.assertEqual(cache_info.hits, 9) self.assertEqual(cache_info.currsize, 1) def test_searched_locations(self): finders.find('spam') self.assertEqual( finders.searched_locations, [os.path.join(TEST_ROOT, 'project', 'documents')] ) @override_settings(MEDIA_ROOT='') def test_location_empty(self): with self.assertRaises(ImproperlyConfigured): finders.DefaultStorageFinder()
bsd-3-clause
iwschris/ezodf2
tests/test_pages.py
1
3894
#!/usr/bin/env python #coding:utf-8 # Purpose: test spreadpage body # Created: 29.01.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT from __future__ import unicode_literals, print_function, division __author__ = "mozman <mozman@gmx.at>" # Standard Library import unittest # trusted or separately tested modules from ezodf2.xmlns import CN from lxml.etree import Element from ezodf2.drawingpage import DrawingPage as Page # objects to test from ezodf2.pages import Pages class TestPagesManagement(unittest.TestCase): def setUp(self): self.pages = Pages(Element(CN('office:drawing'))) def test_empty_body(self): self.assertEqual(len(self.pages), 0) def test_has_one_table(self): self.pages.append(Page(name='Page1')) self.assertEqual(len(self.pages), 1) def test_get_page_by_name(self): self.pages.append(Page(name='Page1')) page = self.pages['Page1'] self.assertEqual(page.name, 'Page1') def test_page_not_found_error(self): with self.assertRaises(KeyError): self.pages['Morgenstern'] def test_get_page_by_index(self): self.pages += Page(name='Page1') self.pages += Page(name='Page2') self.pages += Page(name='Page3') page = self.pages[2] self.assertEqual(page.name, 'Page3') def test_get_last_page_by_index(self): self.pages += Page(name='Page1') self.pages += Page(name='Page2') self.pages += Page(name='Page3') page = self.pages[-1] self.assertEqual(page.name, 'Page3') def test_page_index_0_error(self): with self.assertRaises(IndexError): self.pages[0] def test_page_index_1_error(self): self.pages += Page(name='Page1') with self.assertRaises(IndexError): self.pages[1] def test_set_page_by_index(self): self.pages += Page(name='Page1') self.pages[0] = Page(name='Page2') self.assertEqual(len(self.pages), 1) self.assertEqual(self.pages[0].name, 'Page2') def test_set_page_by_name(self): self.pages += Page(name='Page1') self.pages['Page1'] = Page(name='Page2') self.assertEqual(len(self.pages), 1) self.assertEqual(self.pages[0].name, 'Page2') def test_remove_page_by_index(self): self.pages += Page(name='Page1') self.pages += Page(name='Page2') del self.pages[0] self.assertEqual(len(self.pages), 1) self.assertEqual(self.pages[0].name, 'Page2') def test_remove_page_by_index(self): self.pages += Page(name='Page1') self.pages += Page(name='Page2') del self.pages['Page1'] self.assertEqual(len(self.pages), 1) self.assertEqual(self.pages[0].name, 'Page2') def test_is_same_object(self): self.pages += Page(name='Page1') object1 = self.pages['Page1'] object2 = self.pages['Page1'] self.assertTrue(object1 is object2) def test_page_names(self): self.pages += Page(name='Page1') self.pages += Page(name='Page2') self.pages += Page(name='Page3') self.assertEqual(list(self.pages.names()), ['Page1', 'Page2', 'Page3']) def test_page_index(self): self.pages += Page(name='Page1') self.pages += Page(name='Page2') self.pages += Page(name='Page3') self.assertEqual(self.pages.index(self.pages['Page3']), 2) def test_page_insert(self): self.pages += Page(name='Page1') self.pages += Page(name='Page2') self.pages.insert(1, Page(name='Page3')) self.assertEqual(self.pages[1].name, 'Page3') self.assertEqual(len(self.pages), 3) if __name__=='__main__': unittest.main()
mit
cbrucks/Federated_Python-Swiftclient
swiftclient/contrib/federated/protocols/rax.py
1
2519
import urllib import urllib2 import json import getpass import BaseHTTPServer import os import webbrowser from swiftclient.contrib.federated import federated_exceptions, federated_utils import ssl ## Sends the authentication request to the IdP along # @param idpEndpoint The IdP address # @param idpRequest The authentication request returned by Keystone def getIdPResponse(idpEndpoint, idpRequest, realm=None): print "\nInitiating Authentication against: "+realm["name"]+"\n" # Get the unscoped token # 1. Get the user name chosen = False user = None while not chosen: try: user = raw_input("Please enter your username: ") chosen = True except: print "Invalid input, please try again" # 2. Get the password chosen = False password = None while not chosen: try: password = getpass.getpass() chosen = True except: print "Invalid input, please try again" # Insert creds req = json.loads(idpRequest) req['auth']['passwordCredentials']['username'] = user req['auth']['passwordCredentials']['password'] = password # Contact Keystone V2 unscoped = json.loads(request(idpEndpoint+'/tokens', method='POST', data=req).read()) print "Successfully Logged In\n" # Get the list of tenants tenants = json.loads(request(idpEndpoint+'/tenants', method='GET', header={'X-Auth-Token':unscoped['access']['token']['id']}).read()) # Offer the user the choice of tenants tenant = federated_utils.selectTenantOrDomain(tenants['tenants'],serverName=realm["name"]) # Get the scoped token newReq = {"auth":{"tenantName": tenant["name"], "token":{"id":unscoped["access"]["token"]["id"]}}} scoped = json.loads(request(idpEndpoint+'/tokens', method='POST', data=newReq).read()) print "\nSuccessfully Authorised to access: "+tenant["name"]+"\n" # Return scoped token return scoped ## Send a request that will be process by the V2 Keystone def request(keystoneEndpoint, data={}, method="GET", header={}): headers = header if method == "GET": data = urllib.urlencode(data) req = urllib2.Request(keystoneEndpoint + data, headers = header) response = urllib2.urlopen(req) elif method == "POST": data = json.dumps(data) headers['Content-Type'] = 'application/json' req = urllib2.Request(keystoneEndpoint, data, header) response = urllib2.urlopen(req) return response
apache-2.0
NaturalHistoryMuseum/inselect
inselect/gui/views/boxes/box_item.py
1
8872
import sys from itertools import chain from PyQt5.QtCore import Qt, QRect, QRectF from PyQt5.QtGui import QPen from PyQt5.QtWidgets import QGraphicsItem, QGraphicsRectItem from inselect.lib.utils import debug_print from inselect.gui.colours import colour_scheme_choice from inselect.gui.utils import painter_state from .resize_handle import ResizeHandle from .reticle import Reticle class BoxItem(QGraphicsRectItem): # Might be some relevant stuff here: # http://stackoverflow.com/questions/10590881/events-and-signals-in-qts-qgraphicsitem-how-is-this-supposed-to-work # The width of the line (in pixels) drawn around the box. # A width of 1 on Mac OS X is too thin. 2 is too thick on Windows. BOX_WIDTH = 2 if 'darwin' == sys.platform else 1 def __init__(self, x, y, w, h, isvalid, parent=None): super(BoxItem, self).__init__(x, y, w, h, parent) self.setFlags(QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemSendsGeometryChanges | QGraphicsItem.ItemIsMovable) self.setCursor(Qt.OpenHandCursor) self.setAcceptHoverEvents(True) # True if the box has valid metadata self._isvalid = isvalid # Points of interest as represented by instances of Reticle self._pois = [] # Resize handles positions = (Qt.TopLeftCorner, Qt.TopRightCorner, Qt.BottomLeftCorner, Qt.BottomRightCorner) self._handles = [] self._handles = [self._create_handle(pos) for pos in positions] self._layout_children() self._set_z_index() def paint(self, painter, option, widget=None): """QGraphicsRectItem virtual """ # TODO LH Is there a way to clip to overlapping # QAbstractGraphicsItems with a larger zorder # TODO LH Get pixmap without tight coupling to scene if not self.has_mouse(): painter.drawPixmap(self.boundingRect(), self.scene().pixmap, self.sceneBoundingRect()) with painter_state(painter): outline_colour, fill_colour = self.colours # Cosmetic pens "...draw strokes that have a constant width # regardless of any transformations applied to the QPainter they are # used with." pen = QPen(outline_colour, self.BOX_WIDTH, Qt.SolidLine) pen.setCosmetic(True) painter.setPen(pen) r = self.boundingRect() painter.drawRect(r) if fill_colour: painter.fillRect(r, fill_colour) def has_mouse(self): """True if self or self._handles has grabbed the mouse """ return self.scene().mouseGrabberItem() in chain([self], self._handles) @property def colours(self): """Tuple of two QColors to use for the box's border and fill respectively. Fill might be None. """ colours = colour_scheme_choice().current['Colours'] has_mouse = self.has_mouse() if has_mouse: outline = colours['Resizing'] elif self.isSelected(): outline = colours['Selected'] elif self._isvalid: outline = colours['Valid'] else: outline = colours['Invalid'] if not self._isvalid and not has_mouse: fill = colours['InvalidFill'] else: fill = None return outline, fill def update(self, rect=QRectF()): """QGraphicsRectItem function """ # TODO LH QGraphicsRectItem::update is not a virtual function - is it # OK to implement this function and call the base class's # implementation? super(BoxItem, self).update(rect) for item in self._handles: item.update() def hoverEnterEvent(self, event): """QGraphicsRectItem virtual """ debug_print('BoxItem.hoverEnterEvent') super(BoxItem, self).hoverEnterEvent(event) self._set_handles_visible(True) self._set_z_index() self.update() def hoverLeaveEvent(self, event): """QGraphicsRectItem virtual """ debug_print('BoxItem.hoverLeaveEvent') super(BoxItem, self).hoverLeaveEvent(event) self._set_handles_visible(False) self._set_z_index() self.update() def _set_handles_visible(self, visible): for handle in self._handles: handle.setVisible(visible) def _create_handle(self, corner): # Creates and returns a new ResizeHandle at the given Qt.Corner handle = ResizeHandle(corner, self) handle.setVisible(False) handle.setFlags(QGraphicsItem.ItemStacksBehindParent | QGraphicsItem.ItemIgnoresTransformations) return handle def _layout_children(self): """Moves child graphics items to the appropriate positions """ bounding = self.boundingRect() for child in chain(self._handles, self._pois): child.layout(bounding) def setRect(self, rect): """QGraphicsRectItem function """ debug_print('BoxItem.setRect') super(BoxItem, self).setRect(rect) self._set_z_index() self._layout_children() def mousePressEvent(self, event): """QGraphicsRectItem virtual """ debug_print('BoxItem.mousePressEvent') super(BoxItem, self).mousePressEvent(event) self._set_z_index() if Qt.ShiftModifier == event.modifiers(): # Add a point of interest self.append_point_of_interest(event.pos()) else: # Starting a move self.setCursor(Qt.ClosedHandCursor) self.update() def mouseReleaseEvent(self, event): """QGraphicsRectItem virtual """ debug_print('BoxItem.mouseReleaseEvent') super(BoxItem, self).mouseReleaseEvent(event) self.setCursor(Qt.OpenHandCursor) self._set_z_index() self.update() def itemChange(self, change, value): """QGraphicsItem virtual """ if change == self.ItemSelectedHasChanged: # Clear points of interest scene = self.scene() while self._pois: scene.removeItem(self._pois.pop()) # Item has gained or lost selection self._set_z_index() return super(BoxItem, self).itemChange(change, value) def set_rect(self, new_rect): """Sets a new QRect in integer coordinates """ # Cumbersome conversion to ints current = self.sceneBoundingRect() current = QRect(current.left(), current.top(), current.width(), current.height()) if current != new_rect: msg = 'Update rect for [{0}] from [{1}] to [{2}]' debug_print(msg.format(self, current, new_rect)) self.prepareGeometryChange() # setrect() expects floating point rect self.setRect(QRectF(new_rect)) def set_isvalid(self, isvalid): """Sets a new 'is valid' """ if isvalid != self._isvalid: self._isvalid = isvalid self.update() def _set_z_index(self): """Updates the Z-index of the box This sorts the boxes such that the bigger the area of a box, the lower it's Z-index is; and boxes that are selected and have mouse or keyboard focus are always above other boxes. """ rect = self.rect() # Smaller items have a higher z z = 1.0 if rect.width() and rect.height(): z += + 1.0 / float(rect.width() * rect.height()) if self.isSelected(): z += 1.0 else: # Newly created items have zero width and height pass self.setZValue(z) def adjust_rect(self, dx1, dy1, dx2, dy2): """Adjusts rect """ r = self.rect() r.adjust(dx1, dy1, dx2, dy2) if r.width() > 1.0 and r.height() > 1.0: self.prepareGeometryChange() self.setRect(r) def append_point_of_interest(self, pos): """Appends pos (a QPoint relative to the top-left of this box) to the list of points of interest """ debug_print('New point of interest at [{0}]'.format(pos)) self._pois.append(Reticle(pos - self.boundingRect().topLeft(), self)) self._pois[-1].layout(self.boundingRect()) self._pois[-1].setFlags(QGraphicsItem.ItemIgnoresTransformations) @property def points_of_interest(self): """An iterable of QPointFs in item coordinates """ return [poi.offset for poi in self._pois]
bsd-3-clause
dpwrussell/openmicroscopy
components/tools/OmeroWeb/omeroweb/urls.py
6
3485
#!/usr/bin/env python # -*- coding: utf-8 -*- # # # # Copyright (c) 2008-2014 University of Dundee. # # 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 <http://www.gnu.org/licenses/>. # # Author: Aleksandra Tarkowska <A(dot)Tarkowska(at)dundee(dot)ac(dot)uk>, 2008. # # Version: 1.0 # from django.conf import settings from django.apps import AppConfig from django.conf.urls import url, patterns, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.shortcuts import redirect from django.core.urlresolvers import reverse from django.utils.functional import lazy from django.views.generic import RedirectView from django.views.decorators.cache import never_cache # error handler handler404 = "omeroweb.feedback.views.handler404" handler500 = "omeroweb.feedback.views.handler500" reverse_lazy = lazy(reverse, str) def redirect_urlpatterns(): """ Helper function to return a URL pattern for index page http://host/. """ if settings.INDEX_TEMPLATE is None: return patterns( '', url(r'^$', never_cache( RedirectView.as_view(url=reverse_lazy('webindex'), permanent=True)), name="index") ) else: return patterns( '', url(r'^$', never_cache( RedirectView.as_view(url=reverse_lazy('webindex_custom'), permanent=True)), name="index"), ) # url patterns urlpatterns = patterns('',) for app in settings.ADDITIONAL_APPS: if isinstance(app, AppConfig): app_config = app else: app_config = AppConfig.create(app) label = app_config.label # Depending on how we added the app to INSTALLED_APPS in settings.py, # include the urls the same way if 'omeroweb.%s' % app in settings.INSTALLED_APPS: urlmodule = 'omeroweb.%s.urls' % app else: urlmodule = '%s.urls' % app try: __import__(urlmodule) except ImportError: pass else: regex = '^(?i)%s/' % label urlpatterns += patterns('', (regex, include(urlmodule)),) urlpatterns += patterns( '', (r'^favicon\.ico$', lambda request: redirect('%swebgateway/img/ome.ico' % settings.STATIC_URL)), (r'^(?i)webgateway/', include('omeroweb.webgateway.urls')), (r'^(?i)webadmin/', include('omeroweb.webadmin.urls')), (r'^(?i)webclient/', include('omeroweb.webclient.urls')), (r'^(?i)url/', include('omeroweb.webredirect.urls')), (r'^(?i)feedback/', include('omeroweb.feedback.urls')), (r'^(?i)api/', include('omeroweb.api.urls')), url(r'^index/$', 'omeroweb.webclient.views.custom_index', name="webindex_custom"), ) urlpatterns += redirect_urlpatterns() if settings.DEBUG: urlpatterns += staticfiles_urlpatterns()
gpl-2.0
dplorimer/osf
website/addons/github/utils.py
9
4025
import hmac import uuid import urllib import hashlib import httplib as http from github3.repos.branch import Branch from framework.exceptions import HTTPError from website.addons.base.exceptions import HookError from website.addons.github.api import GitHub MESSAGE_BASE = 'via the Open Science Framework' MESSAGES = { 'add': 'Added {0}'.format(MESSAGE_BASE), 'update': 'Updated {0}'.format(MESSAGE_BASE), 'delete': 'Deleted {0}'.format(MESSAGE_BASE), } def make_hook_secret(): return str(uuid.uuid4()).replace('-', '') HOOK_SIGNATURE_KEY = 'X-Hub-Signature' def verify_hook_signature(node_settings, data, headers): """Verify hook signature. :param AddonGithubNodeSettings node_settings: :param dict data: JSON response body :param dict headers: Request headers :raises: HookError if signature is missing or invalid """ if node_settings.hook_secret is None: raise HookError('No secret key') digest = hmac.new( str(node_settings.hook_secret), data, digestmod=hashlib.sha1 ).hexdigest() signature = headers.get(HOOK_SIGNATURE_KEY, '').replace('sha1=', '') if digest != signature: raise HookError('Invalid signature') def get_path(kwargs, required=True): path = kwargs.get('path') if path: return urllib.unquote_plus(path) elif required: raise HTTPError(http.BAD_REQUEST) def get_refs(addon, branch=None, sha=None, connection=None): """Get the appropriate branch name and sha given the addon settings object, and optionally the branch and sha from the request arguments. :param str branch: Branch name. If None, return the default branch from the repo settings. :param str sha: The SHA. :param GitHub connection: GitHub API object. If None, one will be created from the addon's user settings. """ connection = connection or GitHub.from_settings(addon.user_settings) if sha and not branch: raise HTTPError(http.BAD_REQUEST) # Get default branch if not provided if not branch: repo = connection.repo(addon.user, addon.repo) if repo is None: return None, None, None branch = repo.default_branch # Get registered branches if provided registered_branches = ( [Branch.from_json(b) for b in addon.registration_data.get('branches', [])] if addon.owner.is_registration else [] ) registered_branch_names = [ each.name for each in registered_branches ] # Fail if registered and branch not in registration data if registered_branches and branch not in registered_branch_names: raise HTTPError(http.BAD_REQUEST) # Get data from GitHub API if not registered branches = registered_branches or connection.branches(addon.user, addon.repo) # Use registered SHA if provided for each in branches: if branch == each.name: sha = each.commit.sha break return branch, sha, branches def check_permissions(node_settings, auth, connection, branch, sha=None, repo=None): user_settings = node_settings.user_settings has_access = False has_auth = bool(user_settings and user_settings.has_auth) if has_auth: repo = repo or connection.repo( node_settings.user, node_settings.repo ) has_access = ( repo is not None and ( 'permissions' not in repo.to_json() or repo.to_json()['permissions']['push'] ) ) if sha: branches = connection.branches( node_settings.user, node_settings.repo, branch ) # TODO Will I ever return false? is_head = next((True for branch in branches if sha == branch.commit.sha), None) else: is_head = True can_edit = ( node_settings.owner.can_edit(auth) and not node_settings.owner.is_registration and has_access and is_head ) return can_edit
apache-2.0
joshowen/django-allauth
allauth/socialaccount/tests.py
3
22781
import json import random import warnings from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.contrib.messages.middleware import MessageMiddleware from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sites.models import Site from django.test.client import RequestFactory from django.test.utils import override_settings from . import providers from ..account import app_settings as account_settings from ..account.models import EmailAddress from ..account.utils import user_email, user_username from ..compat import parse_qs, reverse, urlparse from ..tests import MockedResponse, TestCase, mocked_response from ..utils import get_user_model from .helpers import complete_social_login from .models import SocialAccount, SocialApp, SocialLogin from .views import signup class OAuthTestsMixin(object): provider_id = None def get_mocked_response(self): pass def setUp(self): super(OAuthTestsMixin, self).setUp() self.provider = providers.registry.by_id(self.provider_id) app = SocialApp.objects.create( provider=self.provider.id, name=self.provider.id, client_id='app123id', key=self.provider.id, secret='dummy') app.sites.add(Site.objects.get_current()) @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=False) def test_login(self): resp_mocks = self.get_mocked_response() if resp_mocks is None: warnings.warn("Cannot test provider %s, no oauth mock" % self.provider.id) return resp = self.login(resp_mocks) self.assertRedirects(resp, reverse('socialaccount_signup')) resp = self.client.get(reverse('socialaccount_signup')) sociallogin = resp.context['form'].sociallogin data = dict(email=user_email(sociallogin.user), username=str(random.randrange(1000, 10000000))) resp = self.client.post(reverse('socialaccount_signup'), data=data) self.assertRedirects( resp, "/accounts/profile/", fetch_redirect_response=False ) user = resp.context['user'] self.assertFalse(user.has_usable_password()) account = SocialAccount.objects.get( user=user, provider=self.provider.id) # The following lines don't actually test that much, but at least # we make sure that the code is hit. provider_account = account.get_provider_account() provider_account.get_avatar_url() provider_account.get_profile_url() provider_account.get_brand() provider_account.to_str() return account @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=True, SOCIALACCOUNT_EMAIL_REQUIRED=False, ACCOUNT_EMAIL_REQUIRED=False) def test_auto_signup(self): resp_mocks = self.get_mocked_response() if not resp_mocks: warnings.warn("Cannot test provider %s, no oauth mock" % self.provider.id) return resp = self.login(resp_mocks) self.assertRedirects( resp, "/accounts/profile/", fetch_redirect_response=False ) self.assertFalse(resp.context['user'].has_usable_password()) def login(self, resp_mocks, process='login'): with mocked_response(MockedResponse(200, 'oauth_token=token&' 'oauth_token_secret=psst', {'content-type': 'text/html'})): resp = self.client.get(reverse(self.provider.id + '_login'), dict(process=process)) p = urlparse(resp['location']) q = parse_qs(p.query) complete_url = reverse(self.provider.id + '_callback') self.assertGreater(q['oauth_callback'][0] .find(complete_url), 0) with mocked_response(self.get_access_token_response(), *resp_mocks): resp = self.client.get(complete_url) return resp def get_access_token_response(self): return MockedResponse( 200, 'oauth_token=token&oauth_token_secret=psst', {'content-type': 'text/html'}) def test_authentication_error(self): resp = self.client.get(reverse(self.provider.id + '_callback')) self.assertTemplateUsed( resp, 'socialaccount/authentication_error.%s' % getattr( settings, 'ACCOUNT_TEMPLATE_EXTENSION', 'html')) # For backward-compatibility with third-party provider tests that call # create_oauth_tests() rather than using the mixin directly. def create_oauth_tests(provider): class Class(OAuthTestsMixin, TestCase): provider_id = provider.id Class.__name__ = 'OAuthTests_' + provider.id return Class class OAuth2TestsMixin(object): provider_id = None def get_mocked_response(self): pass def get_login_response_json(self, with_refresh_token=True): rt = '' if with_refresh_token: rt = ',"refresh_token": "testrf"' return """{ "uid":"weibo", "access_token":"testac" %s }""" % rt def setUp(self): super(OAuth2TestsMixin, self).setUp() self.provider = providers.registry.by_id(self.provider_id) app = SocialApp.objects.create(provider=self.provider.id, name=self.provider.id, client_id='app123id', key=self.provider.id, secret='dummy') app.sites.add(Site.objects.get_current()) @override_settings(SOCIALACCOUNT_AUTO_SIGNUP=False) def test_login(self): resp_mock = self.get_mocked_response() if not resp_mock: warnings.warn("Cannot test provider %s, no oauth mock" % self.provider.id) return resp = self.login(resp_mock,) self.assertRedirects(resp, reverse('socialaccount_signup')) def test_account_tokens(self, multiple_login=False): email = "user@example.com" user = get_user_model().objects.create( username='user', is_active=True, email=email) user.set_password('test') user.save() EmailAddress.objects.create(user=user, email=email, primary=True, verified=True) self.client.login(username=user.username, password='test') self.login(self.get_mocked_response(), process='connect') if multiple_login: self.login( self.get_mocked_response(), with_refresh_token=False, process='connect') # get account sa = SocialAccount.objects.filter(user=user, provider=self.provider.id).get() # The following lines don't actually test that much, but at least # we make sure that the code is hit. provider_account = sa.get_provider_account() provider_account.get_avatar_url() provider_account.get_profile_url() provider_account.get_brand() provider_account.to_str() # get token t = sa.socialtoken_set.get() # verify access_token and refresh_token self.assertEqual('testac', t.token) self.assertEqual(t.token_secret, json.loads(self.get_login_response_json( with_refresh_token=True)).get( 'refresh_token', '')) def test_account_refresh_token_saved_next_login(self): """ fails if a login missing a refresh token, deletes the previously saved refresh token. Systems such as google's oauth only send a refresh token on first login. """ self.test_account_tokens(multiple_login=True) def login(self, resp_mock, process='login', with_refresh_token=True): resp = self.client.get(reverse(self.provider.id + '_login'), dict(process=process)) p = urlparse(resp['location']) q = parse_qs(p.query) complete_url = reverse(self.provider.id + '_callback') self.assertGreater(q['redirect_uri'][0] .find(complete_url), 0) response_json = self \ .get_login_response_json(with_refresh_token=with_refresh_token) with mocked_response( MockedResponse( 200, response_json, {'content-type': 'application/json'}), resp_mock): resp = self.client.get(complete_url, {'code': 'test', 'state': q['state'][0]}) return resp def test_authentication_error(self): resp = self.client.get(reverse(self.provider.id + '_callback')) self.assertTemplateUsed( resp, 'socialaccount/authentication_error.%s' % getattr( settings, 'ACCOUNT_TEMPLATE_EXTENSION', 'html')) # For backward-compatibility with third-party provider tests that call # create_oauth2_tests() rather than using the mixin directly. def create_oauth2_tests(provider): class Class(OAuth2TestsMixin, TestCase): provider_id = provider.id Class.__name__ = 'OAuth2Tests_' + provider.id return Class class SocialAccountTests(TestCase): def setUp(self): super(SocialAccountTests, self).setUp() site = Site.objects.get_current() for provider in providers.registry.get_list(): app = SocialApp.objects.create( provider=provider.id, name=provider.id, client_id='app123id', key='123', secret='dummy') app.sites.add(site) @override_settings( SOCIALACCOUNT_AUTO_SIGNUP=True, ACCOUNT_SIGNUP_FORM_CLASS=None, ACCOUNT_EMAIL_VERIFICATION=account_settings.EmailVerificationMethod.NONE # noqa ) def test_email_address_created(self): factory = RequestFactory() request = factory.get('/accounts/login/callback/') request.user = AnonymousUser() SessionMiddleware().process_request(request) MessageMiddleware().process_request(request) User = get_user_model() user = User() setattr(user, account_settings.USER_MODEL_USERNAME_FIELD, 'test') setattr( user, account_settings.USER_MODEL_EMAIL_FIELD, "test@example.com" ) account = SocialAccount(provider='openid', uid='123') sociallogin = SocialLogin(user=user, account=account) complete_social_login(request, sociallogin) user = User.objects.get( **{account_settings.USER_MODEL_USERNAME_FIELD: 'test'} ) self.assertTrue( SocialAccount.objects.filter(user=user, uid=account.uid).exists() ) self.assertTrue( EmailAddress.objects.filter(user=user, email=user_email(user)).exists() ) @override_settings( ACCOUNT_EMAIL_REQUIRED=True, ACCOUNT_UNIQUE_EMAIL=True, ACCOUNT_USERNAME_REQUIRED=True, ACCOUNT_AUTHENTICATION_METHOD='email', SOCIALACCOUNT_AUTO_SIGNUP=True) def test_email_address_clash_username_required(self): """Test clash on both username and email""" request, resp = self._email_address_clash( 'test', 'test@example.com') self.assertEqual( resp['location'], reverse('socialaccount_signup')) # POST different username/email to social signup form request.method = 'POST' request.POST = { 'username': 'other', 'email': 'other@example.com'} resp = signup(request) self.assertEqual( resp['location'], '/accounts/profile/') user = get_user_model().objects.get( **{account_settings.USER_MODEL_EMAIL_FIELD: 'other@example.com'}) self.assertEqual(user_username(user), 'other') @override_settings( ACCOUNT_EMAIL_REQUIRED=True, ACCOUNT_UNIQUE_EMAIL=True, ACCOUNT_USERNAME_REQUIRED=False, ACCOUNT_AUTHENTICATION_METHOD='email', SOCIALACCOUNT_AUTO_SIGNUP=True) def test_email_address_clash_username_not_required(self): """Test clash while username is not required""" request, resp = self._email_address_clash( 'test', 'test@example.com') self.assertEqual( resp['location'], reverse('socialaccount_signup')) # POST email to social signup form (username not present) request.method = 'POST' request.POST = { 'email': 'other@example.com'} resp = signup(request) self.assertEqual( resp['location'], '/accounts/profile/') user = get_user_model().objects.get( **{account_settings.USER_MODEL_EMAIL_FIELD: 'other@example.com'}) self.assertNotEqual(user_username(user), 'test') @override_settings( ACCOUNT_EMAIL_REQUIRED=True, ACCOUNT_UNIQUE_EMAIL=True, ACCOUNT_USERNAME_REQUIRED=False, ACCOUNT_AUTHENTICATION_METHOD='email', SOCIALACCOUNT_AUTO_SIGNUP=True) def test_email_address_clash_username_auto_signup(self): # Clash on username, but auto signup still works request, resp = self._email_address_clash('test', 'other@example.com') self.assertEqual( resp['location'], '/accounts/profile/') user = get_user_model().objects.get( **{account_settings.USER_MODEL_EMAIL_FIELD: 'other@example.com'}) self.assertNotEqual(user_username(user), 'test') @override_settings( ACCOUNT_EMAIL_REQUIRED=True, ACCOUNT_USERNAME_BLACKLIST=['username', 'username1', 'username2'], ACCOUNT_UNIQUE_EMAIL=True, ACCOUNT_USERNAME_REQUIRED=True, ACCOUNT_AUTHENTICATION_METHOD='email', SOCIALACCOUNT_AUTO_SIGNUP=True) def test_populate_username_in_blacklist(self): factory = RequestFactory() request = factory.get('/accounts/twitter/login/callback/') request.user = AnonymousUser() SessionMiddleware().process_request(request) MessageMiddleware().process_request(request) User = get_user_model() user = User() setattr(user, account_settings.USER_MODEL_USERNAME_FIELD, 'username') setattr(user, account_settings.USER_MODEL_EMAIL_FIELD, 'username@example.com') account = SocialAccount(provider='twitter', uid='123') sociallogin = SocialLogin(user=user, account=account) complete_social_login(request, sociallogin) self.assertNotIn(request.user.username, account_settings.USERNAME_BLACKLIST) def _email_address_clash(self, username, email): User = get_user_model() # Some existig user exi_user = User() user_username(exi_user, 'test') user_email(exi_user, 'test@example.com') exi_user.save() # A social user being signed up... account = SocialAccount( provider='twitter', uid='123') user = User() user_username(user, username) user_email(user, email) sociallogin = SocialLogin(user=user, account=account) # Signing up, should pop up the social signup form factory = RequestFactory() request = factory.get('/accounts/twitter/login/callback/') request.user = AnonymousUser() SessionMiddleware().process_request(request) MessageMiddleware().process_request(request) resp = complete_social_login(request, sociallogin) return request, resp def test_disconnect(self): User = get_user_model() # Some existig user user = User() user_username(user, 'test') user_email(user, 'test@example.com') user.set_password('test') user.save() account = SocialAccount.objects.create( uid='123', provider='twitter', user=user) self.client.login( username=user.username, password=user.username) resp = self.client.get(reverse('socialaccount_connections')) self.assertTemplateUsed(resp, 'socialaccount/connections.html') resp = self.client.post( reverse('socialaccount_connections'), {'account': account.pk}) self.assertFalse( SocialAccount.objects.filter(pk=account.pk).exists()) @override_settings( ACCOUNT_EMAIL_REQUIRED=True, ACCOUNT_EMAIL_VERIFICATION='mandatory', ACCOUNT_UNIQUE_EMAIL=True, ACCOUNT_USERNAME_REQUIRED=False, ACCOUNT_AUTHENTICATION_METHOD='email', SOCIALACCOUNT_AUTO_SIGNUP=False) def test_verified_email_change_at_signup(self): """ Test scenario for when the user changes email at social signup. Current behavior is that both the unverified and verified email are added, and that the user is allowed to pass because he did provide a verified one. """ session = self.client.session User = get_user_model() sociallogin = SocialLogin( user=User(email="verified@example.com"), account=SocialAccount( provider='google' ), email_addresses=[ EmailAddress( email="verified@example.com", verified=True, primary=True)]) session['socialaccount_sociallogin'] = sociallogin.serialize() session.save() resp = self.client.get(reverse('socialaccount_signup')) form = resp.context['form'] self.assertEqual(form["email"].value(), "verified@example.com") resp = self.client.post( reverse('socialaccount_signup'), data={'email': "unverified@example.org"}) self.assertRedirects( resp, '/accounts/profile/', fetch_redirect_response=False) user = User.objects.all()[0] self.assertEqual(user_email(user), "verified@example.com") self.assertTrue( EmailAddress.objects.filter( user=user, email="verified@example.com", verified=True, primary=True ).exists()) self.assertTrue( EmailAddress.objects.filter( user=user, email="unverified@example.org", verified=False, primary=False ).exists()) @override_settings( ACCOUNT_EMAIL_REQUIRED=True, ACCOUNT_EMAIL_VERIFICATION='mandatory', ACCOUNT_UNIQUE_EMAIL=True, ACCOUNT_USERNAME_REQUIRED=False, ACCOUNT_AUTHENTICATION_METHOD='email', SOCIALACCOUNT_AUTO_SIGNUP=False) def test_unverified_email_change_at_signup(self): """ Test scenario for when the user changes email at social signup, while his provider did not provide a verified email. In that case, email verification will kick in. Here, both email addresses are added as well. """ session = self.client.session User = get_user_model() sociallogin = SocialLogin( user=User(email="unverified@example.com"), account=SocialAccount( provider='google' ), email_addresses=[ EmailAddress( email="unverified@example.com", verified=False, primary=True)]) session['socialaccount_sociallogin'] = sociallogin.serialize() session.save() resp = self.client.get(reverse('socialaccount_signup')) form = resp.context['form'] self.assertEqual(form["email"].value(), "unverified@example.com") resp = self.client.post( reverse('socialaccount_signup'), data={'email': "unverified@example.org"}) self.assertRedirects(resp, reverse('account_email_verification_sent')) user = User.objects.all()[0] self.assertEqual(user_email(user), "unverified@example.org") self.assertTrue( EmailAddress.objects.filter( user=user, email="unverified@example.com", verified=False, primary=False ).exists()) self.assertTrue( EmailAddress.objects.filter( user=user, email="unverified@example.org", verified=False, primary=True ).exists()) @override_settings( ACCOUNT_EMAIL_REQUIRED=True, ACCOUNT_EMAIL_VERIFICATION='mandatory', ACCOUNT_UNIQUE_EMAIL=True, ACCOUNT_USERNAME_REQUIRED=False, ACCOUNT_AUTHENTICATION_METHOD='email', SOCIALACCOUNT_AUTO_SIGNUP=False) def test_unique_email_validation_signup(self): session = self.client.session User = get_user_model() User.objects.create(email="me@example.com") sociallogin = SocialLogin( user=User(email="me@example.com"), account=SocialAccount( provider='google' ), email_addresses=[ EmailAddress( email="me@example.com", verified=True, primary=True)]) session['socialaccount_sociallogin'] = sociallogin.serialize() session.save() resp = self.client.get(reverse('socialaccount_signup')) form = resp.context['form'] self.assertEqual(form['email'].value(), "me@example.com") resp = self.client.post( reverse('socialaccount_signup'), data={'email': "me@example.com"}) self.assertFormError( resp, 'form', 'email', 'An account already exists with this e-mail address.' ' Please sign in to that account first, then connect' ' your Google account.')
mit
sebady/selenium
py/test/selenium/webdriver/firefox/__init__.py
57
1247
# Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google 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. # Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google 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.
apache-2.0
kustodian/ansible-modules-core
packaging/os/apt.py
8
20940
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Flowroute LLC # Written by Matthew Williams <matthew@flowroute.com> # Based on yum module written by Seth Vidal <skvidal at fedoraproject.org> # # This module 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 software 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 software. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = ''' --- module: apt short_description: Manages apt-packages description: - Manages I(apt) packages (such as for Debian/Ubuntu). version_added: "0.0.2" options: name: description: - A package name, like C(foo), or package specifier with version, like C(foo=1.0). Wildcards (fnmatch) like apt* are also supported. required: false default: null state: description: - Indicates the desired package state. C(latest) ensures that the latest version is installed. required: false default: present choices: [ "latest", "absent", "present" ] update_cache: description: - Run the equivalent of C(apt-get update) before the operation. Can be run as part of the package installation or as a separate step. required: false default: no choices: [ "yes", "no" ] cache_valid_time: description: - If C(update_cache) is specified and the last run is less or equal than I(cache_valid_time) seconds ago, the C(update_cache) gets skipped. required: false default: no purge: description: - Will force purging of configuration files if the module state is set to I(absent). required: false default: no choices: [ "yes", "no" ] default_release: description: - Corresponds to the C(-t) option for I(apt) and sets pin priorities required: false default: null install_recommends: description: - Corresponds to the C(--no-install-recommends) option for I(apt). Default behavior (C(yes)) replicates apt's default behavior; C(no) does not install recommended packages. Suggested packages are never installed. required: false default: yes choices: [ "yes", "no" ] force: description: - If C(yes), force installs/removes. required: false default: "no" choices: [ "yes", "no" ] upgrade: description: - 'If yes or safe, performs an aptitude safe-upgrade.' - 'If full, performs an aptitude full-upgrade.' - 'If dist, performs an apt-get dist-upgrade.' - 'Note: This does not upgrade a specific package, use state=latest for that.' version_added: "1.1" required: false default: "yes" choices: [ "yes", "safe", "full", "dist"] dpkg_options: description: - Add dpkg options to apt command. Defaults to '-o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold"' - Options should be supplied as comma separated list required: false default: 'force-confdef,force-confold' deb: description: - Path to a .deb package on the remote machine. required: false version_added: "1.6" requirements: [ python-apt, aptitude ] author: Matthew Williams notes: - Three of the upgrade modes (C(full), C(safe) and its alias C(yes)) require C(aptitude), otherwise C(apt-get) suffices. ''' EXAMPLES = ''' # Update repositories cache and install "foo" package - apt: name=foo update_cache=yes # Remove "foo" package - apt: name=foo state=absent # Install the package "foo" - apt: name=foo state=present # Install the version '1.00' of package "foo" - apt: name=foo=1.00 state=present # Update the repository cache and update package "nginx" to latest version using default release squeeze-backport - apt: name=nginx state=latest default_release=squeeze-backports update_cache=yes # Install latest version of "openjdk-6-jdk" ignoring "install-recommends" - apt: name=openjdk-6-jdk state=latest install_recommends=no # Update all packages to the latest version - apt: upgrade=dist # Run the equivalent of "apt-get update" as a separate step - apt: update_cache=yes # Only run "update_cache=yes" if the last one is more than 3600 seconds ago - apt: update_cache=yes cache_valid_time=3600 # Pass options to dpkg on run - apt: upgrade=dist update_cache=yes dpkg_options='force-confold,force-confdef' # Install a .deb package - apt: deb=/tmp/mypackage.deb ''' import traceback # added to stave off future warnings about apt api import warnings warnings.filterwarnings('ignore', "apt API not stable yet", FutureWarning) import os import datetime import fnmatch # APT related constants APT_ENV_VARS = dict( DEBIAN_FRONTEND = 'noninteractive', DEBIAN_PRIORITY = 'critical', LANG = 'C' ) DPKG_OPTIONS = 'force-confdef,force-confold' APT_GET_ZERO = "0 upgraded, 0 newly installed" APTITUDE_ZERO = "0 packages upgraded, 0 newly installed" APT_LISTS_PATH = "/var/lib/apt/lists" APT_UPDATE_SUCCESS_STAMP_PATH = "/var/lib/apt/periodic/update-success-stamp" HAS_PYTHON_APT = True try: import apt import apt.debfile import apt_pkg except ImportError: HAS_PYTHON_APT = False def package_split(pkgspec): parts = pkgspec.split('=') if len(parts) > 1: return parts[0], parts[1] else: return parts[0], None def package_status(m, pkgname, version, cache, state): try: # get the package from the cache, as well as the # the low-level apt_pkg.Package object which contains # state fields not directly acccesible from the # higher-level apt.package.Package object. pkg = cache[pkgname] ll_pkg = cache._cache[pkgname] # the low-level package object except KeyError: if state == 'install': if cache.get_providing_packages(pkgname): return False, True, False m.fail_json(msg="No package matching '%s' is available" % pkgname) else: return False, False, False try: has_files = len(pkg.installed_files) > 0 except UnicodeDecodeError: has_files = True except AttributeError: has_files = False # older python-apt cannot be used to determine non-purged try: package_is_installed = ll_pkg.current_state == apt_pkg.CURSTATE_INSTALLED except AttributeError: # python-apt 0.7.X has very weak low-level object try: # might not be necessary as python-apt post-0.7.X should have current_state property package_is_installed = pkg.is_installed except AttributeError: # assume older version of python-apt is installed package_is_installed = pkg.isInstalled if version and package_is_installed: try: installed_version = pkg.installed.version except AttributeError: installed_version = pkg.installedVersion return package_is_installed and fnmatch.fnmatch(installed_version, version), False, has_files else: try: package_is_upgradable = pkg.is_upgradable except AttributeError: # assume older version of python-apt is installed package_is_upgradable = pkg.isUpgradable return package_is_installed, package_is_upgradable, has_files def expand_dpkg_options(dpkg_options_compressed): options_list = dpkg_options_compressed.split(',') dpkg_options = "" for dpkg_option in options_list: dpkg_options = '%s -o "Dpkg::Options::=--%s"' \ % (dpkg_options, dpkg_option) return dpkg_options.strip() def expand_pkgspec_from_fnmatches(m, pkgspec, cache): new_pkgspec = [] for pkgname_or_fnmatch_pattern in pkgspec: # note that any of these chars is not allowed in a (debian) pkgname if [c for c in pkgname_or_fnmatch_pattern if c in "*?[]!"]: if "=" in pkgname_or_fnmatch_pattern: m.fail_json(msg="pkgname wildcard and version can not be mixed") # handle multiarch pkgnames, the idea is that "apt*" should # only select native packages. But "apt*:i386" should still work if not ":" in pkgname_or_fnmatch_pattern: matches = fnmatch.filter( [pkg.name for pkg in cache if not ":" in pkg.name], pkgname_or_fnmatch_pattern) else: matches = fnmatch.filter( [pkg.name for pkg in cache], pkgname_or_fnmatch_pattern) if len(matches) == 0: m.fail_json(msg="No package(s) matching '%s' available" % str(pkgname_or_fnmatch_pattern)) else: new_pkgspec.extend(matches) else: new_pkgspec.append(pkgname_or_fnmatch_pattern) return new_pkgspec def install(m, pkgspec, cache, upgrade=False, default_release=None, install_recommends=True, force=False, dpkg_options=expand_dpkg_options(DPKG_OPTIONS)): packages = "" pkgspec = expand_pkgspec_from_fnmatches(m, pkgspec, cache) for package in pkgspec: name, version = package_split(package) installed, upgradable, has_files = package_status(m, name, version, cache, state='install') if not installed or (upgrade and upgradable): packages += "'%s' " % package if len(packages) != 0: if force: force_yes = '--force-yes' else: force_yes = '' if m.check_mode: check_arg = '--simulate' else: check_arg = '' for (k,v) in APT_ENV_VARS.iteritems(): os.environ[k] = v cmd = "%s -y %s %s %s install %s" % (APT_GET_CMD, dpkg_options, force_yes, check_arg, packages) if default_release: cmd += " -t '%s'" % (default_release,) if not install_recommends: cmd += " --no-install-recommends" rc, out, err = m.run_command(cmd) if rc: return (False, dict(msg="'apt-get install %s' failed: %s" % (packages, err), stdout=out, stderr=err)) else: return (True, dict(changed=True, stdout=out, stderr=err)) else: return (True, dict(changed=False)) def install_deb(m, debs, cache, force, install_recommends, dpkg_options): changed=False deps_to_install = [] pkgs_to_install = [] for deb_file in debs.split(','): pkg = apt.debfile.DebPackage(deb_file) # Check if it's already installed if pkg.compare_to_version_in_cache() == pkg.VERSION_SAME: continue # Check if package is installable if not pkg.check(): m.fail_json(msg=pkg._failure_string) # add any missing deps to the list of deps we need # to install so they're all done in one shot deps_to_install.extend(pkg.missing_deps) # and add this deb to the list of packages to install pkgs_to_install.append(deb_file) # install the deps through apt retvals = {} if len(deps_to_install) > 0: (success, retvals) = install(m=m, pkgspec=deps_to_install, cache=cache, install_recommends=install_recommends, dpkg_options=expand_dpkg_options(dpkg_options)) if not success: m.fail_json(**retvals) changed = retvals.get('changed', False) if len(pkgs_to_install) > 0: options = ' '.join(["--%s"% x for x in dpkg_options.split(",")]) if m.check_mode: options += " --simulate" if force: options += " --force-yes" cmd = "dpkg %s -i %s" % (options, " ".join(pkgs_to_install)) rc, out, err = m.run_command(cmd) if "stdout" in retvals: stdout = retvals["stdout"] + out else: stdout = out if "stderr" in retvals: stderr = retvals["stderr"] + err else: stderr = err if rc == 0: m.exit_json(changed=True, stdout=stdout, stderr=stderr) else: m.fail_json(msg="%s failed" % cmd, stdout=stdout, stderr=stderr) else: m.exit_json(changed=changed, stdout=retvals.get('stdout',''), stderr=retvals.get('stderr','')) def remove(m, pkgspec, cache, purge=False, dpkg_options=expand_dpkg_options(DPKG_OPTIONS)): packages = "" pkgspec = expand_pkgspec_from_fnmatches(m, pkgspec, cache) for package in pkgspec: name, version = package_split(package) installed, upgradable, has_files = package_status(m, name, version, cache, state='remove') if installed or (has_files and purge): packages += "'%s' " % package if len(packages) == 0: m.exit_json(changed=False) else: if purge: purge = '--purge' else: purge = '' for (k,v) in APT_ENV_VARS.iteritems(): os.environ[k] = v cmd = "%s -q -y %s %s remove %s" % (APT_GET_CMD, dpkg_options, purge, packages) if m.check_mode: m.exit_json(changed=True) rc, out, err = m.run_command(cmd) if rc: m.fail_json(msg="'apt-get remove %s' failed: %s" % (packages, err), stdout=out, stderr=err) m.exit_json(changed=True, stdout=out, stderr=err) def upgrade(m, mode="yes", force=False, default_release=None, dpkg_options=expand_dpkg_options(DPKG_OPTIONS)): if m.check_mode: check_arg = '--simulate' else: check_arg = '' apt_cmd = None if mode == "dist": # apt-get dist-upgrade apt_cmd = APT_GET_CMD upgrade_command = "dist-upgrade" elif mode == "full": # aptitude full-upgrade apt_cmd = APTITUDE_CMD upgrade_command = "full-upgrade" else: # aptitude safe-upgrade # mode=yes # default apt_cmd = APTITUDE_CMD upgrade_command = "safe-upgrade" if force: if apt_cmd == APT_GET_CMD: force_yes = '--force-yes' else: force_yes = '' else: force_yes = '' apt_cmd_path = m.get_bin_path(apt_cmd, required=True) for (k,v) in APT_ENV_VARS.iteritems(): os.environ[k] = v cmd = '%s -y %s %s %s %s' % (apt_cmd_path, dpkg_options, force_yes, check_arg, upgrade_command) if default_release: cmd += " -t '%s'" % (default_release,) rc, out, err = m.run_command(cmd) if rc: m.fail_json(msg="'%s %s' failed: %s" % (apt_cmd, upgrade_command, err), stdout=out) if (apt_cmd == APT_GET_CMD and APT_GET_ZERO in out) or (apt_cmd == APTITUDE_CMD and APTITUDE_ZERO in out): m.exit_json(changed=False, msg=out, stdout=out, stderr=err) m.exit_json(changed=True, msg=out, stdout=out, stderr=err) def main(): module = AnsibleModule( argument_spec = dict( state = dict(default='installed', choices=['installed', 'latest', 'removed', 'absent', 'present']), update_cache = dict(default=False, aliases=['update-cache'], type='bool'), cache_valid_time = dict(type='int'), purge = dict(default=False, type='bool'), package = dict(default=None, aliases=['pkg', 'name'], type='list'), deb = dict(default=None), default_release = dict(default=None, aliases=['default-release']), install_recommends = dict(default='yes', aliases=['install-recommends'], type='bool'), force = dict(default='no', type='bool'), upgrade = dict(choices=['yes', 'safe', 'full', 'dist']), dpkg_options = dict(default=DPKG_OPTIONS) ), mutually_exclusive = [['package', 'upgrade', 'deb']], required_one_of = [['package', 'upgrade', 'update_cache', 'deb']], supports_check_mode = True ) if not HAS_PYTHON_APT: try: module.run_command('apt-get update && apt-get install python-apt -y -q', use_unsafe_shell=True, check_rc=True) global apt, apt_pkg import apt import apt_pkg except ImportError: module.fail_json(msg="Could not import python modules: apt, apt_pkg. Please install python-apt package.") global APTITUDE_CMD APTITUDE_CMD = module.get_bin_path("aptitude", False) global APT_GET_CMD APT_GET_CMD = module.get_bin_path("apt-get") p = module.params if not APTITUDE_CMD and p.get('upgrade', None) in [ 'full', 'safe', 'yes' ]: module.fail_json(msg="Could not find aptitude. Please ensure it is installed.") install_recommends = p['install_recommends'] dpkg_options = expand_dpkg_options(p['dpkg_options']) try: cache = apt.Cache() if p['default_release']: try: apt_pkg.config['APT::Default-Release'] = p['default_release'] except AttributeError: apt_pkg.Config['APT::Default-Release'] = p['default_release'] # reopen cache w/ modified config cache.open(progress=None) if p['update_cache']: # Default is: always update the cache cache_valid = False if p['cache_valid_time']: tdelta = datetime.timedelta(seconds=p['cache_valid_time']) try: mtime = os.stat(APT_UPDATE_SUCCESS_STAMP_PATH).st_mtime except: mtime = False if mtime is False: # Looks like the update-success-stamp is not available # Fallback: Checking the mtime of the lists try: mtime = os.stat(APT_LISTS_PATH).st_mtime except: mtime = False if mtime is False: # No mtime could be read - looks like lists are not there # We update the cache to be safe cache_valid = False else: mtimestamp = datetime.datetime.fromtimestamp(mtime) if mtimestamp + tdelta >= datetime.datetime.now(): # dont update the cache # the old cache is less than cache_valid_time seconds old - so still valid cache_valid = True if cache_valid is not True: cache.update() cache.open(progress=None) if not p['package'] and not p['upgrade'] and not p['deb']: module.exit_json(changed=False) force_yes = p['force'] if p['upgrade']: upgrade(module, p['upgrade'], force_yes, p['default_release'], dpkg_options) if p['deb']: if p['state'] != "installed": module.fail_json(msg="deb only supports state=installed") install_deb(module, p['deb'], cache, install_recommends=install_recommends, force=force_yes, dpkg_options=p['dpkg_options']) packages = p['package'] latest = p['state'] == 'latest' for package in packages: if package.count('=') > 1: module.fail_json(msg="invalid package spec: %s" % package) if latest and '=' in package: module.fail_json(msg='version number inconsistent with state=latest: %s' % package) if p['state'] == 'latest': result = install(module, packages, cache, upgrade=True, default_release=p['default_release'], install_recommends=install_recommends, force=force_yes, dpkg_options=dpkg_options) (success, retvals) = result if success: module.exit_json(**retvals) else: module.fail_json(**retvals) elif p['state'] in [ 'installed', 'present' ]: result = install(module, packages, cache, default_release=p['default_release'], install_recommends=install_recommends,force=force_yes, dpkg_options=dpkg_options) (success, retvals) = result if success: module.exit_json(**retvals) else: module.fail_json(**retvals) elif p['state'] in [ 'removed', 'absent' ]: remove(module, packages, cache, p['purge'], dpkg_options) except apt.cache.LockFailedException: module.fail_json(msg="Failed to lock apt for exclusive operation") # import module snippets from ansible.module_utils.basic import * main()
gpl-3.0
openfun/edx-platform
lms/djangoapps/mobile_api/social_facebook/test_utils.py
104
6489
""" Test utils for Facebook functionality """ import httpretty import json from rest_framework.test import APITestCase from django.conf import settings from django.core.urlresolvers import reverse from social.apps.django_app.default.models import UserSocialAuth from student.models import CourseEnrollment from student.views import login_oauth_token from openedx.core.djangoapps.user_api.preferences.api import get_user_preference, set_user_preference from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from courseware.tests.factories import UserFactory class SocialFacebookTestCase(ModuleStoreTestCase, APITestCase): """ Base Class for social test cases """ USERS = { 1: {'USERNAME': "TestUser One", 'EMAIL': "test_one@ebnotions.com", 'PASSWORD': "edx", 'FB_ID': "11111111111111111"}, 2: {'USERNAME': "TestUser Two", 'EMAIL': "test_two@ebnotions.com", 'PASSWORD': "edx", 'FB_ID': "22222222222222222"}, 3: {'USERNAME': "TestUser Three", 'EMAIL': "test_three@ebnotions.com", 'PASSWORD': "edx", 'FB_ID': "33333333333333333"} } BACKEND = "facebook" USER_URL = "https://graph.facebook.com/me" UID_FIELD = "id" _FB_USER_ACCESS_TOKEN = 'ThisIsAFakeFacebookToken' users = {} def setUp(self): super(SocialFacebookTestCase, self).setUp() def set_facebook_interceptor_for_access_token(self): """ Facebook interceptor for groups access_token """ httpretty.register_uri( httpretty.GET, 'https://graph.facebook.com/oauth/access_token?client_secret=' + settings.FACEBOOK_APP_SECRET + '&grant_type=client_credentials&client_id=' + settings.FACEBOOK_APP_ID, body='FakeToken=FakeToken', status=200 ) def set_facebook_interceptor_for_groups(self, data, status): """ Facebook interceptor for groups test """ httpretty.register_uri( httpretty.POST, 'https://graph.facebook.com/' + settings.FACEBOOK_API_VERSION + '/' + settings.FACEBOOK_APP_ID + '/groups', body=json.dumps(data), status=status ) def set_facebook_interceptor_for_members(self, data, status, group_id, member_id): """ Facebook interceptor for group members tests """ httpretty.register_uri( httpretty.POST, 'https://graph.facebook.com/' + settings.FACEBOOK_API_VERSION + '/' + group_id + '/members?member=' + member_id + '&access_token=FakeToken', body=json.dumps(data), status=status ) def set_facebook_interceptor_for_friends(self, data): """ Facebook interceptor for friends tests """ httpretty.register_uri( httpretty.GET, "https://graph.facebook.com/v2.2/me/friends", body=json.dumps(data), status=201 ) def delete_group(self, group_id): """ Invoke the delete groups view """ url = reverse('create-delete-group', kwargs={'group_id': group_id}) response = self.client.delete(url) return response def invite_to_group(self, group_id, member_ids): """ Invoke the invite to group view """ url = reverse('add-remove-member', kwargs={'group_id': group_id, 'member_id': ''}) return self.client.post(url, {'member_ids': member_ids}) def remove_from_group(self, group_id, member_id): """ Invoke the remove from group view """ url = reverse('add-remove-member', kwargs={'group_id': group_id, 'member_id': member_id}) response = self.client.delete(url) self.assertEqual(response.status_code, 200) def link_edx_account_to_social(self, user, backend, social_uid): """ Register the user to the social auth backend """ reverse(login_oauth_token, kwargs={"backend": backend}) UserSocialAuth.objects.create(user=user, provider=backend, uid=social_uid) def set_sharing_preferences(self, user, boolean_value): """ Sets self.user's share settings to boolean_value """ # Note that setting the value to boolean will result in the conversion to the unicode form of the boolean. set_user_preference(user, 'share_with_facebook_friends', boolean_value) self.assertEqual(get_user_preference(user, 'share_with_facebook_friends'), unicode(boolean_value)) def _change_enrollment(self, action, course_id=None, email_opt_in=None): """ Change the student's enrollment status in a course. Args: action (string): The action to perform (either "enroll" or "unenroll") Keyword Args: course_id (unicode): If provided, use this course ID. Otherwise, use the course ID created in the setup for this test. email_opt_in (unicode): If provided, pass this value along as an additional GET parameter. """ if course_id is None: course_id = unicode(self.course.id) params = { 'enrollment_action': action, 'course_id': course_id } if email_opt_in: params['email_opt_in'] = email_opt_in return self.client.post(reverse('change_enrollment'), params) def user_create_and_signin(self, user_number): """ Create a user and sign them in """ self.users[user_number] = UserFactory.create( username=self.USERS[user_number]['USERNAME'], email=self.USERS[user_number]['EMAIL'], password=self.USERS[user_number]['PASSWORD'] ) self.client.login(username=self.USERS[user_number]['USERNAME'], password=self.USERS[user_number]['PASSWORD']) def enroll_in_course(self, user, course): """ Enroll a user in the course """ resp = self._change_enrollment('enroll', course_id=course.id) self.assertEqual(resp.status_code, 200) self.assertTrue(CourseEnrollment.is_enrolled(user, course.id)) course_mode, is_active = CourseEnrollment.enrollment_mode_for_user(user, course.id) self.assertTrue(is_active) self.assertEqual(course_mode, 'honor')
agpl-3.0
sunu/oh-missions-oppia-beta
core/storage/base_model/gae_models_test.py
5
2820
# coding: utf-8 # # Copyright 2014 The Oppia 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. __author__ = 'Sean Lip' from core.platform import models (base_models,) = models.Registry.import_models([ models.NAMES.base_model]) import feconf import test_utils import unittest class BaseModelUnitTests(test_utils.GenericTestBase): """Test the generic base model.""" def tearDown(self): """Deletes all model entities.""" for entity in base_models.BaseModel.get_all(): entity.delete() super(BaseModelUnitTests, self).tearDown() def test_error_cases_for_get_method(self): with self.assertRaises(base_models.BaseModel.EntityNotFoundError): base_models.BaseModel.get('Invalid id') with self.assertRaises(base_models.BaseModel.EntityNotFoundError): base_models.BaseModel.get('Invalid id', strict=True) self.assertIsNone( base_models.BaseModel.get('Invalid id', strict=False)) def test_generic_query_put_get_and_delete_operations(self): model = base_models.BaseModel() all_models = [m for m in base_models.BaseModel.get_all()] self.assertEqual(len(all_models), 0) model.put() all_models = [m for m in base_models.BaseModel.get_all()] self.assertEqual(len(all_models), 1) self.assertEqual(all_models[0], model) model_id = all_models[0].id self.assertEqual(model, base_models.BaseModel.get(model_id)) model.delete() all_models = [m for m in base_models.BaseModel.get_all()] self.assertEqual(len(all_models), 0) with self.assertRaises(base_models.BaseModel.EntityNotFoundError): model.get(model_id) def test_get_new_id_method_returns_unique_ids(self): ids = set([]) for item in range(100): new_id = base_models.BaseModel.get_new_id('') self.assertNotIn(new_id, ids) base_models.BaseModel(id=new_id).put() ids.add(new_id) def test_get_new_id_method_does_not_fail_with_bad_names(self): base_models.BaseModel.get_new_id(None) base_models.BaseModel.get_new_id('¡Hola!') base_models.BaseModel.get_new_id(12345) base_models.BaseModel.get_new_id({'a': 'b'})
apache-2.0
SrNetoChan/Quantum-GIS
tests/src/python/test_qgsfloatingwidget.py
45
8058
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsFloatingWidget. .. note:: 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__ = 'Nyall Dawson' __date__ = '26/04/2016' __copyright__ = 'Copyright 2016, The QGIS Project' import qgis # NOQA from qgis.PyQt.QtWidgets import QWidget, QGridLayout from qgis.gui import QgsFloatingWidget from qgis.testing import start_app, unittest start_app() class TestQgsFloatingWidget(unittest.TestCase): def testAnchor(self): """ test setting anchor point for widget """ main_frame = QWidget() gl = QGridLayout() main_frame.setLayout(gl) main_frame.setMinimumSize(800, 600) anchor_widget = QWidget(main_frame) anchor_widget.setMinimumSize(300, 200) main_frame.layout().addWidget(anchor_widget, 1, 1) gl.setColumnStretch(0, 1) gl.setColumnStretch(1, 0) gl.setColumnStretch(2, 1) gl.setRowStretch(0, 1) gl.setRowStretch(1, 0) gl.setRowStretch(2, 1) # 103 = WA_DontShowOnScreen (not available in PyQt) main_frame.setAttribute(103) main_frame.show() fw = qgis.gui.QgsFloatingWidget(main_frame) fw.setMinimumSize(100, 50) fw.setAnchorWidget(anchor_widget) tests = [{'anchorPoint': QgsFloatingWidget.TopLeft, 'widgetAnchorPoint': QgsFloatingWidget.TopLeft, 'x': 250, 'y': 200}, {'anchorPoint': QgsFloatingWidget.TopMiddle, 'widgetAnchorPoint': QgsFloatingWidget.TopLeft, 'x': 200, 'y': 200}, {'anchorPoint': QgsFloatingWidget.TopRight, 'widgetAnchorPoint': QgsFloatingWidget.TopLeft, 'x': 150, 'y': 200}, {'anchorPoint': QgsFloatingWidget.MiddleLeft, 'widgetAnchorPoint': QgsFloatingWidget.TopLeft, 'x': 250, 'y': 175}, {'anchorPoint': QgsFloatingWidget.Middle, 'widgetAnchorPoint': QgsFloatingWidget.TopLeft, 'x': 200, 'y': 175}, {'anchorPoint': QgsFloatingWidget.MiddleRight, 'widgetAnchorPoint': QgsFloatingWidget.TopLeft, 'x': 150, 'y': 175}, {'anchorPoint': QgsFloatingWidget.BottomLeft, 'widgetAnchorPoint': QgsFloatingWidget.TopLeft, 'x': 250, 'y': 150}, {'anchorPoint': QgsFloatingWidget.BottomMiddle, 'widgetAnchorPoint': QgsFloatingWidget.TopLeft, 'x': 200, 'y': 150}, {'anchorPoint': QgsFloatingWidget.BottomRight, 'widgetAnchorPoint': QgsFloatingWidget.TopLeft, 'x': 150, 'y': 150}, {'anchorPoint': QgsFloatingWidget.TopLeft, 'widgetAnchorPoint': QgsFloatingWidget.TopMiddle, 'x': 400, 'y': 200}, {'anchorPoint': QgsFloatingWidget.TopLeft, 'widgetAnchorPoint': QgsFloatingWidget.TopRight, 'x': 550, 'y': 200}, {'anchorPoint': QgsFloatingWidget.TopLeft, 'widgetAnchorPoint': QgsFloatingWidget.MiddleLeft, 'x': 250, 'y': 300}, {'anchorPoint': QgsFloatingWidget.TopLeft, 'widgetAnchorPoint': QgsFloatingWidget.Middle, 'x': 400, 'y': 300}, {'anchorPoint': QgsFloatingWidget.TopLeft, 'widgetAnchorPoint': QgsFloatingWidget.MiddleRight, 'x': 550, 'y': 300}, {'anchorPoint': QgsFloatingWidget.TopLeft, 'widgetAnchorPoint': QgsFloatingWidget.BottomLeft, 'x': 250, 'y': 400}, {'anchorPoint': QgsFloatingWidget.TopLeft, 'widgetAnchorPoint': QgsFloatingWidget.BottomMiddle, 'x': 400, 'y': 400}, {'anchorPoint': QgsFloatingWidget.TopLeft, 'widgetAnchorPoint': QgsFloatingWidget.BottomRight, 'x': 550, 'y': 400}] for t in tests: fw.setAnchorPoint(t['anchorPoint']) fw.setAnchorWidgetPoint(t['widgetAnchorPoint']) self.assertEqual(fw.pos().x(), t['x']) self.assertEqual(fw.pos().y(), t['y']) def testMovingResizingAnchorWidget(self): """ test that moving or resizing the anchor widget updates the floating widget position """ main_frame = QWidget() gl = QGridLayout() main_frame.setLayout(gl) main_frame.setMinimumSize(800, 600) anchor_widget = QWidget(main_frame) anchor_widget.setFixedSize(300, 200) main_frame.layout().addWidget(anchor_widget, 1, 1) gl.setColumnStretch(0, 1) gl.setColumnStretch(1, 0) gl.setColumnStretch(2, 1) gl.setRowStretch(0, 1) gl.setRowStretch(1, 0) gl.setRowStretch(2, 1) # 103 = WA_DontShowOnScreen (not available in PyQt) main_frame.setAttribute(103) main_frame.show() fw = qgis.gui.QgsFloatingWidget(main_frame) fw.setMinimumSize(100, 50) fw.setAnchorWidget(anchor_widget) fw.setAnchorPoint(QgsFloatingWidget.TopLeft) fw.setAnchorWidgetPoint(QgsFloatingWidget.TopLeft) self.assertEqual(fw.pos().x(), 250) self.assertEqual(fw.pos().y(), 200) # now resize anchor widget anchor_widget.setFixedSize(400, 300) # force layout recalculation main_frame.layout().invalidate() main_frame.layout().activate() self.assertEqual(fw.pos().x(), 200) self.assertEqual(fw.pos().y(), 150) # now move anchor widget anchor_widget.move(100, 110) self.assertEqual(fw.pos().x(), 100) self.assertEqual(fw.pos().y(), 110) def testResizingParentWidget(self): """ test resizing parent widget correctly repositions floating widget""" main_frame = QWidget() gl = QGridLayout() main_frame.setLayout(gl) main_frame.setMinimumSize(800, 600) anchor_widget = QWidget(main_frame) anchor_widget.setFixedSize(300, 200) main_frame.layout().addWidget(anchor_widget, 1, 1) gl.setColumnStretch(0, 1) gl.setColumnStretch(1, 0) gl.setColumnStretch(2, 1) gl.setRowStretch(0, 1) gl.setRowStretch(1, 0) gl.setRowStretch(2, 1) # 103 = WA_DontShowOnScreen (not available in PyQt) main_frame.setAttribute(103) main_frame.show() fw = qgis.gui.QgsFloatingWidget(main_frame) fw.setMinimumSize(100, 50) fw.setAnchorWidget(anchor_widget) fw.setAnchorPoint(QgsFloatingWidget.TopLeft) fw.setAnchorWidgetPoint(QgsFloatingWidget.TopLeft) self.assertEqual(fw.pos().x(), 250) self.assertEqual(fw.pos().y(), 200) # now resize parent widget main_frame.setFixedSize(1000, 800) # force layout recalculation main_frame.layout().invalidate() main_frame.layout().activate() self.assertEqual(fw.pos().x(), 350) self.assertEqual(fw.pos().y(), 300) def testPositionConstrainedToParent(self): """ test that floating widget will be placed inside parent when possible """ main_frame = QWidget() gl = QGridLayout() main_frame.setLayout(gl) main_frame.setMinimumSize(800, 600) anchor_widget = QWidget(main_frame) anchor_widget.setFixedSize(300, 200) main_frame.layout().addWidget(anchor_widget, 1, 1) gl.setColumnStretch(0, 1) gl.setColumnStretch(1, 0) gl.setColumnStretch(2, 1) gl.setRowStretch(0, 1) gl.setRowStretch(1, 0) gl.setRowStretch(2, 1) main_frame.setAttribute(103) main_frame.show() fw = qgis.gui.QgsFloatingWidget(main_frame) fw.setMinimumSize(300, 50) fw.setAnchorWidget(anchor_widget) fw.setAnchorPoint(QgsFloatingWidget.TopRight) fw.setAnchorWidgetPoint(QgsFloatingWidget.TopLeft) # x-position should be 0, not -50 self.assertEqual(fw.pos().x(), 0) fw.setAnchorPoint(QgsFloatingWidget.TopLeft) fw.setAnchorWidgetPoint(QgsFloatingWidget.TopRight) # x-position should be 500, not 600 self.assertEqual(fw.pos().x(), 500) if __name__ == '__main__': unittest.main()
gpl-2.0
agrista/odoo-saas
addons/purchase_analytic_plans/__init__.py
441
1220
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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 <http://www.gnu.org/licenses/>. # ############################################################################## #---------------------------------------------------------- # Init Sales #---------------------------------------------------------- import purchase_analytic_plans # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
theflofly/tensorflow
tensorflow/contrib/distributions/python/ops/bijectors/masked_autoregressive.py
15
23796
# Copyright 2017 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. # ============================================================================== """MaskedAutoregressiveFlow bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.layers import core as layers from tensorflow.python.ops import array_ops from tensorflow.python.ops import clip_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import template as template_ops from tensorflow.python.ops import variable_scope as variable_scope_lib from tensorflow.python.ops.distributions import bijector from tensorflow.python.util import deprecation __all__ = [ "MaskedAutoregressiveFlow", "masked_autoregressive_default_template", "masked_dense", ] class MaskedAutoregressiveFlow(bijector.Bijector): """Affine MaskedAutoregressiveFlow bijector for vector-valued events. The affine autoregressive flow [(Papamakarios et al., 2016)][3] provides a relatively simple framework for user-specified (deep) architectures to learn a distribution over vector-valued events. Regarding terminology, "Autoregressive models decompose the joint density as a product of conditionals, and model each conditional in turn. Normalizing flows transform a base density (e.g. a standard Gaussian) into the target density by an invertible transformation with tractable Jacobian." [(Papamakarios et al., 2016)][3] In other words, the "autoregressive property" is equivalent to the decomposition, `p(x) = prod{ p(x[i] | x[0:i]) : i=0, ..., d }`. The provided `shift_and_log_scale_fn`, `masked_autoregressive_default_template`, achieves this property by zeroing out weights in its `masked_dense` layers. In the `tfp` framework, a "normalizing flow" is implemented as a `tfp.bijectors.Bijector`. The `forward` "autoregression" is implemented using a `tf.while_loop` and a deep neural network (DNN) with masked weights such that the autoregressive property is automatically met in the `inverse`. A `TransformedDistribution` using `MaskedAutoregressiveFlow(...)` uses the (expensive) forward-mode calculation to draw samples and the (cheap) reverse-mode calculation to compute log-probabilities. Conversely, a `TransformedDistribution` using `Invert(MaskedAutoregressiveFlow(...))` uses the (expensive) forward-mode calculation to compute log-probabilities and the (cheap) reverse-mode calculation to compute samples. See "Example Use" [below] for more details. Given a `shift_and_log_scale_fn`, the forward and inverse transformations are (a sequence of) affine transformations. A "valid" `shift_and_log_scale_fn` must compute each `shift` (aka `loc` or "mu" in [Germain et al. (2015)][1]) and `log(scale)` (aka "alpha" in [Germain et al. (2015)][1]) such that each are broadcastable with the arguments to `forward` and `inverse`, i.e., such that the calculations in `forward`, `inverse` [below] are possible. For convenience, `masked_autoregressive_default_template` is offered as a possible `shift_and_log_scale_fn` function. It implements the MADE architecture [(Germain et al., 2015)][1]. MADE is a feed-forward network that computes a `shift` and `log(scale)` using `masked_dense` layers in a deep neural network. Weights are masked to ensure the autoregressive property. It is possible that this architecture is suboptimal for your task. To build alternative networks, either change the arguments to `masked_autoregressive_default_template`, use the `masked_dense` function to roll-out your own, or use some other architecture, e.g., using `tf.layers`. Warning: no attempt is made to validate that the `shift_and_log_scale_fn` enforces the "autoregressive property". Assuming `shift_and_log_scale_fn` has valid shape and autoregressive semantics, the forward transformation is ```python def forward(x): y = zeros_like(x) event_size = x.shape[-1] for _ in range(event_size): shift, log_scale = shift_and_log_scale_fn(y) y = x * math_ops.exp(log_scale) + shift return y ``` and the inverse transformation is ```python def inverse(y): shift, log_scale = shift_and_log_scale_fn(y) return (y - shift) / math_ops.exp(log_scale) ``` Notice that the `inverse` does not need a for-loop. This is because in the forward pass each calculation of `shift` and `log_scale` is based on the `y` calculated so far (not `x`). In the `inverse`, the `y` is fully known, thus is equivalent to the scaling used in `forward` after `event_size` passes, i.e., the "last" `y` used to compute `shift`, `log_scale`. (Roughly speaking, this also proves the transform is bijective.) #### Examples ```python import tensorflow_probability as tfp tfd = tfp.distributions tfb = tfp.bijectors dims = 5 # A common choice for a normalizing flow is to use a Gaussian for the base # distribution. (However, any continuous distribution would work.) E.g., maf = tfd.TransformedDistribution( distribution=tfd.Normal(loc=0., scale=1.), bijector=tfb.MaskedAutoregressiveFlow( shift_and_log_scale_fn=tfb.masked_autoregressive_default_template( hidden_layers=[512, 512])), event_shape=[dims]) x = maf.sample() # Expensive; uses `tf.while_loop`, no Bijector caching. maf.log_prob(x) # Almost free; uses Bijector caching. maf.log_prob(0.) # Cheap; no `tf.while_loop` despite no Bijector caching. # [Papamakarios et al. (2016)][3] also describe an Inverse Autoregressive # Flow [(Kingma et al., 2016)][2]: iaf = tfd.TransformedDistribution( distribution=tfd.Normal(loc=0., scale=1.), bijector=tfb.Invert(tfb.MaskedAutoregressiveFlow( shift_and_log_scale_fn=tfb.masked_autoregressive_default_template( hidden_layers=[512, 512]))), event_shape=[dims]) x = iaf.sample() # Cheap; no `tf.while_loop` despite no Bijector caching. iaf.log_prob(x) # Almost free; uses Bijector caching. iaf.log_prob(0.) # Expensive; uses `tf.while_loop`, no Bijector caching. # In many (if not most) cases the default `shift_and_log_scale_fn` will be a # poor choice. Here's an example of using a "shift only" version and with a # different number/depth of hidden layers. shift_only = True maf_no_scale_hidden2 = tfd.TransformedDistribution( distribution=tfd.Normal(loc=0., scale=1.), bijector=tfb.MaskedAutoregressiveFlow( tfb.masked_autoregressive_default_template( hidden_layers=[32], shift_only=shift_only), is_constant_jacobian=shift_only), event_shape=[dims]) ``` #### References [1]: Mathieu Germain, Karol Gregor, Iain Murray, and Hugo Larochelle. MADE: Masked Autoencoder for Distribution Estimation. In _International Conference on Machine Learning_, 2015. https://arxiv.org/abs/1502.03509 [2]: Diederik P. Kingma, Tim Salimans, Rafal Jozefowicz, Xi Chen, Ilya Sutskever, and Max Welling. Improving Variational Inference with Inverse Autoregressive Flow. In _Neural Information Processing Systems_, 2016. https://arxiv.org/abs/1606.04934 [3]: George Papamakarios, Theo Pavlakou, and Iain Murray. Masked Autoregressive Flow for Density Estimation. In _Neural Information Processing Systems_, 2017. https://arxiv.org/abs/1705.07057 """ @deprecation.deprecated( "2018-10-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.contrib.distributions`.", warn_once=True) def __init__(self, shift_and_log_scale_fn, is_constant_jacobian=False, validate_args=False, unroll_loop=False, name=None): """Creates the MaskedAutoregressiveFlow bijector. Args: shift_and_log_scale_fn: Python `callable` which computes `shift` and `log_scale` from both the forward domain (`x`) and the inverse domain (`y`). Calculation must respect the "autoregressive property" (see class docstring). Suggested default `masked_autoregressive_default_template(hidden_layers=...)`. Typically the function contains `tf.Variables` and is wrapped using `tf.make_template`. Returning `None` for either (both) `shift`, `log_scale` is equivalent to (but more efficient than) returning zero. is_constant_jacobian: Python `bool`. Default: `False`. When `True` the implementation assumes `log_scale` does not depend on the forward domain (`x`) or inverse domain (`y`) values. (No validation is made; `is_constant_jacobian=False` is always safe but possibly computationally inefficient.) validate_args: Python `bool` indicating whether arguments should be checked for correctness. unroll_loop: Python `bool` indicating whether the `tf.while_loop` in `_forward` should be replaced with a static for loop. Requires that the final dimension of `x` be known at graph construction time. Defaults to `False`. name: Python `str`, name given to ops managed by this object. """ name = name or "masked_autoregressive_flow" self._shift_and_log_scale_fn = shift_and_log_scale_fn self._unroll_loop = unroll_loop super(MaskedAutoregressiveFlow, self).__init__( forward_min_event_ndims=1, is_constant_jacobian=is_constant_jacobian, validate_args=validate_args, name=name) def _forward(self, x): if self._unroll_loop: event_size = tensor_shape.dimension_value( x.shape.with_rank_at_least(1)[-1]) if event_size is None: raise ValueError( "The final dimension of `x` must be known at graph construction " "time if `unroll_loop=True`. `x.shape: %r`" % x.shape) y = array_ops.zeros_like(x, name="y0") for _ in range(event_size): shift, log_scale = self._shift_and_log_scale_fn(y) # next_y = scale * x + shift next_y = x if log_scale is not None: next_y *= math_ops.exp(log_scale) if shift is not None: next_y += shift y = next_y return y event_size = array_ops.shape(x)[-1] # If the event size is available at graph construction time, we can inform # the graph compiler of the maximum number of steps. If not, # static_event_size will be None, and the maximum_iterations argument will # have no effect. static_event_size = tensor_shape.dimension_value( x.shape.with_rank_at_least(1)[-1]) y0 = array_ops.zeros_like(x, name="y0") # call the template once to ensure creation _ = self._shift_and_log_scale_fn(y0) def _loop_body(index, y0): """While-loop body for autoregression calculation.""" # Set caching device to avoid re-getting the tf.Variable for every while # loop iteration. with variable_scope_lib.variable_scope( variable_scope_lib.get_variable_scope()) as vs: if vs.caching_device is None: vs.set_caching_device(lambda op: op.device) shift, log_scale = self._shift_and_log_scale_fn(y0) y = x if log_scale is not None: y *= math_ops.exp(log_scale) if shift is not None: y += shift return index + 1, y _, y = control_flow_ops.while_loop( cond=lambda index, _: index < event_size, body=_loop_body, loop_vars=(0, y0), maximum_iterations=static_event_size) return y def _inverse(self, y): shift, log_scale = self._shift_and_log_scale_fn(y) x = y if shift is not None: x -= shift if log_scale is not None: x *= math_ops.exp(-log_scale) return x def _inverse_log_det_jacobian(self, y): _, log_scale = self._shift_and_log_scale_fn(y) if log_scale is None: return constant_op.constant(0., dtype=y.dtype, name="ildj") return -math_ops.reduce_sum(log_scale, axis=-1) MASK_INCLUSIVE = "inclusive" MASK_EXCLUSIVE = "exclusive" @deprecation.deprecated( "2018-10-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.contrib.distributions`.", warn_once=True) def _gen_slices(num_blocks, n_in, n_out, mask_type=MASK_EXCLUSIVE): """Generate the slices for building an autoregressive mask.""" # TODO(b/67594795): Better support of dynamic shape. slices = [] col = 0 d_in = n_in // num_blocks d_out = n_out // num_blocks row = d_out if mask_type == MASK_EXCLUSIVE else 0 for _ in range(num_blocks): row_slice = slice(row, None) col_slice = slice(col, col + d_in) slices.append([row_slice, col_slice]) col += d_in row += d_out return slices @deprecation.deprecated( "2018-10-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.contrib.distributions`.", warn_once=True) def _gen_mask(num_blocks, n_in, n_out, mask_type=MASK_EXCLUSIVE, dtype=dtypes.float32): """Generate the mask for building an autoregressive dense layer.""" # TODO(b/67594795): Better support of dynamic shape. mask = np.zeros([n_out, n_in], dtype=dtype.as_numpy_dtype()) slices = _gen_slices(num_blocks, n_in, n_out, mask_type=mask_type) for [row_slice, col_slice] in slices: mask[row_slice, col_slice] = 1 return mask @deprecation.deprecated( "2018-10-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.contrib.distributions`.", warn_once=True) def masked_dense(inputs, units, num_blocks=None, exclusive=False, kernel_initializer=None, reuse=None, name=None, *args, **kwargs): """A autoregressively masked dense layer. Analogous to `tf.layers.dense`. See [Germain et al. (2015)][1] for detailed explanation. Arguments: inputs: Tensor input. units: Python `int` scalar representing the dimensionality of the output space. num_blocks: Python `int` scalar representing the number of blocks for the MADE masks. exclusive: Python `bool` scalar representing whether to zero the diagonal of the mask, used for the first layer of a MADE. kernel_initializer: Initializer function for the weight matrix. If `None` (default), weights are initialized using the `tf.glorot_random_initializer`. reuse: Python `bool` scalar representing whether to reuse the weights of a previous layer by the same name. name: Python `str` used to describe ops managed by this function. *args: `tf.layers.dense` arguments. **kwargs: `tf.layers.dense` keyword arguments. Returns: Output tensor. Raises: NotImplementedError: if rightmost dimension of `inputs` is unknown prior to graph execution. #### References [1]: Mathieu Germain, Karol Gregor, Iain Murray, and Hugo Larochelle. MADE: Masked Autoencoder for Distribution Estimation. In _International Conference on Machine Learning_, 2015. https://arxiv.org/abs/1502.03509 """ # TODO(b/67594795): Better support of dynamic shape. input_depth = tensor_shape.dimension_value( inputs.shape.with_rank_at_least(1)[-1]) if input_depth is None: raise NotImplementedError( "Rightmost dimension must be known prior to graph execution.") mask = _gen_mask(num_blocks, input_depth, units, MASK_EXCLUSIVE if exclusive else MASK_INCLUSIVE).T if kernel_initializer is None: kernel_initializer = init_ops.glorot_normal_initializer() def masked_initializer(shape, dtype=None, partition_info=None): return mask * kernel_initializer(shape, dtype, partition_info) with ops.name_scope(name, "masked_dense", [inputs, units, num_blocks]): layer = layers.Dense( units, kernel_initializer=masked_initializer, kernel_constraint=lambda x: mask * x, name=name, dtype=inputs.dtype.base_dtype, _scope=name, _reuse=reuse, *args, **kwargs) return layer.apply(inputs) @deprecation.deprecated( "2018-10-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.contrib.distributions`.", warn_once=True) def masked_autoregressive_default_template( hidden_layers, shift_only=False, activation=nn_ops.relu, log_scale_min_clip=-5., log_scale_max_clip=3., log_scale_clip_gradient=False, name=None, *args, **kwargs): """Build the Masked Autoregressive Density Estimator (Germain et al., 2015). This will be wrapped in a make_template to ensure the variables are only created once. It takes the input and returns the `loc` ("mu" in [Germain et al. (2015)][1]) and `log_scale` ("alpha" in [Germain et al. (2015)][1]) from the MADE network. Warning: This function uses `masked_dense` to create randomly initialized `tf.Variables`. It is presumed that these will be fit, just as you would any other neural architecture which uses `tf.layers.dense`. #### About Hidden Layers Each element of `hidden_layers` should be greater than the `input_depth` (i.e., `input_depth = tf.shape(input)[-1]` where `input` is the input to the neural network). This is necessary to ensure the autoregressivity property. #### About Clipping This function also optionally clips the `log_scale` (but possibly not its gradient). This is useful because if `log_scale` is too small/large it might underflow/overflow making it impossible for the `MaskedAutoregressiveFlow` bijector to implement a bijection. Additionally, the `log_scale_clip_gradient` `bool` indicates whether the gradient should also be clipped. The default does not clip the gradient; this is useful because it still provides gradient information (for fitting) yet solves the numerical stability problem. I.e., `log_scale_clip_gradient = False` means `grad[exp(clip(x))] = grad[x] exp(clip(x))` rather than the usual `grad[clip(x)] exp(clip(x))`. Args: hidden_layers: Python `list`-like of non-negative integer, scalars indicating the number of units in each hidden layer. Default: `[512, 512]. shift_only: Python `bool` indicating if only the `shift` term shall be computed. Default: `False`. activation: Activation function (callable). Explicitly setting to `None` implies a linear activation. log_scale_min_clip: `float`-like scalar `Tensor`, or a `Tensor` with the same shape as `log_scale`. The minimum value to clip by. Default: -5. log_scale_max_clip: `float`-like scalar `Tensor`, or a `Tensor` with the same shape as `log_scale`. The maximum value to clip by. Default: 3. log_scale_clip_gradient: Python `bool` indicating that the gradient of `tf.clip_by_value` should be preserved. Default: `False`. name: A name for ops managed by this function. Default: "masked_autoregressive_default_template". *args: `tf.layers.dense` arguments. **kwargs: `tf.layers.dense` keyword arguments. Returns: shift: `Float`-like `Tensor` of shift terms (the "mu" in [Germain et al. (2015)][1]). log_scale: `Float`-like `Tensor` of log(scale) terms (the "alpha" in [Germain et al. (2015)][1]). Raises: NotImplementedError: if rightmost dimension of `inputs` is unknown prior to graph execution. #### References [1]: Mathieu Germain, Karol Gregor, Iain Murray, and Hugo Larochelle. MADE: Masked Autoencoder for Distribution Estimation. In _International Conference on Machine Learning_, 2015. https://arxiv.org/abs/1502.03509 """ name = name or "masked_autoregressive_default_template" with ops.name_scope(name, values=[log_scale_min_clip, log_scale_max_clip]): def _fn(x): """MADE parameterized via `masked_autoregressive_default_template`.""" # TODO(b/67594795): Better support of dynamic shape. input_depth = tensor_shape.dimension_value( x.shape.with_rank_at_least(1)[-1]) if input_depth is None: raise NotImplementedError( "Rightmost dimension must be known prior to graph execution.") input_shape = (np.int32(x.shape.as_list()) if x.shape.is_fully_defined() else array_ops.shape(x)) for i, units in enumerate(hidden_layers): x = masked_dense( inputs=x, units=units, num_blocks=input_depth, exclusive=True if i == 0 else False, activation=activation, *args, **kwargs) x = masked_dense( inputs=x, units=(1 if shift_only else 2) * input_depth, num_blocks=input_depth, activation=None, *args, **kwargs) if shift_only: x = array_ops.reshape(x, shape=input_shape) return x, None x = array_ops.reshape( x, shape=array_ops.concat([input_shape, [2]], axis=0)) shift, log_scale = array_ops.unstack(x, num=2, axis=-1) which_clip = (math_ops.clip_by_value if log_scale_clip_gradient else _clip_by_value_preserve_grad) log_scale = which_clip(log_scale, log_scale_min_clip, log_scale_max_clip) return shift, log_scale return template_ops.make_template(name, _fn) @deprecation.deprecated( "2018-10-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.contrib.distributions`.", warn_once=True) def _clip_by_value_preserve_grad(x, clip_value_min, clip_value_max, name=None): """Clips input while leaving gradient unaltered.""" with ops.name_scope(name, "clip_by_value_preserve_grad", [x, clip_value_min, clip_value_max]): clip_x = clip_ops.clip_by_value(x, clip_value_min, clip_value_max) return x + array_ops.stop_gradient(clip_x - x)
apache-2.0
Oga-Jun/DECAF
decaf/roms/seabios/tools/checkstack.py
38
7820
#!/usr/bin/env python # Script that tries to find how much stack space each function in an # object is using. # # Copyright (C) 2008 Kevin O'Connor <kevin@koconnor.net> # # This file may be distributed under the terms of the GNU GPLv3 license. # Usage: # objdump -m i386 -M i8086 -M suffix -d out/rom16.o | tools/checkstack.py import sys import re # Functions that change stacks STACKHOP = ['__send_disk_op'] # List of functions we can assume are never called. #IGNORE = ['panic', '__dprintf'] IGNORE = ['panic'] OUTPUTDESC = """ #funcname1[preamble_stack_usage,max_usage_with_callers]: # insn_addr:called_function [usage_at_call_point+caller_preamble,total_usage] # #funcname2[p,m,max_usage_to_yield_point]: # insn_addr:called_function [u+c,t,usage_to_yield_point] """ # Find out maximum stack usage for a function def calcmaxstack(funcs, funcaddr): info = funcs[funcaddr] # Find max of all nested calls. maxusage = info[1] maxyieldusage = doesyield = 0 if info[3] is not None: maxyieldusage = info[3] doesyield = 1 info[2] = maxusage info[4] = info[3] seenbefore = {} totcalls = 0 for insnaddr, calladdr, usage in info[6]: callinfo = funcs.get(calladdr) if callinfo is None: continue if callinfo[2] is None: calcmaxstack(funcs, calladdr) if callinfo[0] not in seenbefore: seenbefore[callinfo[0]] = 1 totcalls += 1 + callinfo[5] funcnameroot = callinfo[0].split('.')[0] if funcnameroot in IGNORE: # This called function is ignored - don't contribute it to # the max stack. continue if funcnameroot in STACKHOP: if usage > maxusage: maxusage = usage if callinfo[4] is not None: doesyield = 1 if usage > maxyieldusage: maxyieldusage = usage continue totusage = usage + callinfo[2] if totusage > maxusage: maxusage = totusage if callinfo[4] is not None: doesyield = 1 totyieldusage = usage + callinfo[4] if totyieldusage > maxyieldusage: maxyieldusage = totyieldusage info[2] = maxusage if doesyield: info[4] = maxyieldusage info[5] = totcalls # Try to arrange output so that functions that call each other are # near each other. def orderfuncs(funcaddrs, availfuncs): l = [(availfuncs[funcaddr][5], availfuncs[funcaddr][0], funcaddr) for funcaddr in funcaddrs if funcaddr in availfuncs] l.sort() l.reverse() out = [] while l: count, name, funcaddr = l.pop(0) if funcaddr not in availfuncs: continue calladdrs = [calls[1] for calls in availfuncs[funcaddr][6]] del availfuncs[funcaddr] out = out + orderfuncs(calladdrs, availfuncs) + [funcaddr] return out # Update function info with a found "yield" point. def noteYield(info, stackusage): prevyield = info[3] if prevyield is None or prevyield < stackusage: info[3] = stackusage # Update function info with a found "call" point. def noteCall(info, subfuncs, insnaddr, calladdr, stackusage): if (calladdr, stackusage) in subfuncs: # Already noted a nearly identical call - ignore this one. return info[6].append((insnaddr, calladdr, stackusage)) subfuncs[(calladdr, stackusage)] = 1 hex_s = r'[0-9a-f]+' re_func = re.compile(r'^(?P<funcaddr>' + hex_s + r') <(?P<func>.*)>:$') re_asm = re.compile( r'^[ ]*(?P<insnaddr>' + hex_s + r'):\t.*\t(addr32 )?(?P<insn>.+?)[ ]*((?P<calladdr>' + hex_s + r') <(?P<ref>.*)>)?$') re_usestack = re.compile( r'^(push[f]?[lw])|(sub.* [$](?P<num>0x' + hex_s + r'),%esp)$') def calc(): # funcs[funcaddr] = [funcname, basicstackusage, maxstackusage # , yieldusage, maxyieldusage, totalcalls # , [(insnaddr, calladdr, stackusage), ...]] funcs = {-1: ['<indirect>', 0, 0, None, None, 0, []]} cur = None atstart = 0 stackusage = 0 # Parse input lines for line in sys.stdin.readlines(): m = re_func.match(line) if m is not None: # Found function funcaddr = int(m.group('funcaddr'), 16) funcs[funcaddr] = cur = [m.group('func'), 0, None, None, None, 0, []] stackusage = 0 atstart = 1 subfuncs = {} continue m = re_asm.match(line) if m is not None: insn = m.group('insn') im = re_usestack.match(insn) if im is not None: if insn.startswith('pushl') or insn.startswith('pushfl'): stackusage += 4 continue elif insn.startswith('pushw') or insn.startswith('pushfw'): stackusage += 2 continue stackusage += int(im.group('num'), 16) if atstart: if insn == 'movl %esp,%ebp': # Still part of initial header continue cur[1] = stackusage atstart = 0 insnaddr = m.group('insnaddr') calladdr = m.group('calladdr') if calladdr is None: if insn.startswith('lcallw'): noteCall(cur, subfuncs, insnaddr, -1, stackusage + 4) noteYield(cur, stackusage + 4) elif insn.startswith('int'): noteCall(cur, subfuncs, insnaddr, -1, stackusage + 6) noteYield(cur, stackusage + 6) elif insn.startswith('sti'): noteYield(cur, stackusage) else: # misc instruction continue else: # Jump or call insn calladdr = int(calladdr, 16) ref = m.group('ref') if '+' in ref: # Inter-function jump. pass elif insn.startswith('j'): # Tail call noteCall(cur, subfuncs, insnaddr, calladdr, 0) elif insn.startswith('calll'): noteCall(cur, subfuncs, insnaddr, calladdr, stackusage + 4) else: print "unknown call", ref noteCall(cur, subfuncs, insnaddr, calladdr, stackusage) # Reset stack usage to preamble usage stackusage = cur[1] #print "other", repr(line) # Calculate maxstackusage for funcaddr, info in funcs.items(): if info[2] is not None: continue calcmaxstack(funcs, funcaddr) # Sort functions for output funcaddrs = orderfuncs(funcs.keys(), funcs.copy()) # Show all functions print OUTPUTDESC for funcaddr in funcaddrs: name, basicusage, maxusage, yieldusage, maxyieldusage, count, calls = \ funcs[funcaddr] if maxusage == 0 and maxyieldusage is None: continue yieldstr = "" if maxyieldusage is not None: yieldstr = ",%d" % maxyieldusage print "\n%s[%d,%d%s]:" % (name, basicusage, maxusage, yieldstr) for insnaddr, calladdr, stackusage in calls: callinfo = funcs.get(calladdr, ("<unknown>", 0, 0, 0, None)) yieldstr = "" if callinfo[4] is not None: yieldstr = ",%d" % (stackusage + callinfo[4]) print " %04s:%-40s [%d+%d,%d%s]" % ( insnaddr, callinfo[0], stackusage, callinfo[1] , stackusage+callinfo[2], yieldstr) def main(): calc() if __name__ == '__main__': main()
gpl-3.0
lodle/SoapServer
third_party/gtest-1.7.0/scripts/fuse_gtest_files.py
2577
8813
#!/usr/bin/env python # # Copyright 2009, 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. """fuse_gtest_files.py v0.2.0 Fuses Google Test source code into a .h file and a .cc file. SYNOPSIS fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR Scans GTEST_ROOT_DIR for Google Test source code, and generates two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc. Then you can build your tests by adding OUTPUT_DIR to the include search path and linking with OUTPUT_DIR/gtest/gtest-all.cc. These two files contain everything you need to use Google Test. Hence you can "install" Google Test by copying them to wherever you want. GTEST_ROOT_DIR can be omitted and defaults to the parent directory of the directory holding this script. EXAMPLES ./fuse_gtest_files.py fused_gtest ./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest This tool is experimental. In particular, it assumes that there is no conditional inclusion of Google Test headers. Please report any problems to googletestframework@googlegroups.com. You can read http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide for more information. """ __author__ = 'wan@google.com (Zhanyong Wan)' import os import re import sets import sys # We assume that this file is in the scripts/ directory in the Google # Test root directory. DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..') # Regex for matching '#include "gtest/..."'. INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gtest/.+)"') # Regex for matching '#include "src/..."'. INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"') # Where to find the source seed files. GTEST_H_SEED = 'include/gtest/gtest.h' GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h' GTEST_ALL_CC_SEED = 'src/gtest-all.cc' # Where to put the generated files. GTEST_H_OUTPUT = 'gtest/gtest.h' GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc' def VerifyFileExists(directory, relative_path): """Verifies that the given file exists; aborts on failure. relative_path is the file path relative to the given directory. """ if not os.path.isfile(os.path.join(directory, relative_path)): print 'ERROR: Cannot find %s in directory %s.' % (relative_path, directory) print ('Please either specify a valid project root directory ' 'or omit it on the command line.') sys.exit(1) def ValidateGTestRootDir(gtest_root): """Makes sure gtest_root points to a valid gtest root directory. The function aborts the program on failure. """ VerifyFileExists(gtest_root, GTEST_H_SEED) VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED) def VerifyOutputFile(output_dir, relative_path): """Verifies that the given output file path is valid. relative_path is relative to the output_dir directory. """ # Makes sure the output file either doesn't exist or can be overwritten. output_file = os.path.join(output_dir, relative_path) if os.path.exists(output_file): # TODO(wan@google.com): The following user-interaction doesn't # work with automated processes. We should provide a way for the # Makefile to force overwriting the files. print ('%s already exists in directory %s - overwrite it? (y/N) ' % (relative_path, output_dir)) answer = sys.stdin.readline().strip() if answer not in ['y', 'Y']: print 'ABORTED.' sys.exit(1) # Makes sure the directory holding the output file exists; creates # it and all its ancestors if necessary. parent_directory = os.path.dirname(output_file) if not os.path.isdir(parent_directory): os.makedirs(parent_directory) def ValidateOutputDir(output_dir): """Makes sure output_dir points to a valid output directory. The function aborts the program on failure. """ VerifyOutputFile(output_dir, GTEST_H_OUTPUT) VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT) def FuseGTestH(gtest_root, output_dir): """Scans folder gtest_root to generate gtest/gtest.h in output_dir.""" output_file = file(os.path.join(output_dir, GTEST_H_OUTPUT), 'w') processed_files = sets.Set() # Holds all gtest headers we've processed. def ProcessFile(gtest_header_path): """Processes the given gtest header file.""" # We don't process the same header twice. if gtest_header_path in processed_files: return processed_files.add(gtest_header_path) # Reads each line in the given gtest header. for line in file(os.path.join(gtest_root, gtest_header_path), 'r'): m = INCLUDE_GTEST_FILE_REGEX.match(line) if m: # It's '#include "gtest/..."' - let's process it recursively. ProcessFile('include/' + m.group(1)) else: # Otherwise we copy the line unchanged to the output file. output_file.write(line) ProcessFile(GTEST_H_SEED) output_file.close() def FuseGTestAllCcToFile(gtest_root, output_file): """Scans folder gtest_root to generate gtest/gtest-all.cc in output_file.""" processed_files = sets.Set() def ProcessFile(gtest_source_file): """Processes the given gtest source file.""" # We don't process the same #included file twice. if gtest_source_file in processed_files: return processed_files.add(gtest_source_file) # Reads each line in the given gtest source file. for line in file(os.path.join(gtest_root, gtest_source_file), 'r'): m = INCLUDE_GTEST_FILE_REGEX.match(line) if m: if 'include/' + m.group(1) == GTEST_SPI_H_SEED: # It's '#include "gtest/gtest-spi.h"'. This file is not # #included by "gtest/gtest.h", so we need to process it. ProcessFile(GTEST_SPI_H_SEED) else: # It's '#include "gtest/foo.h"' where foo is not gtest-spi. # We treat it as '#include "gtest/gtest.h"', as all other # gtest headers are being fused into gtest.h and cannot be # #included directly. # There is no need to #include "gtest/gtest.h" more than once. if not GTEST_H_SEED in processed_files: processed_files.add(GTEST_H_SEED) output_file.write('#include "%s"\n' % (GTEST_H_OUTPUT,)) else: m = INCLUDE_SRC_FILE_REGEX.match(line) if m: # It's '#include "src/foo"' - let's process it recursively. ProcessFile(m.group(1)) else: output_file.write(line) ProcessFile(GTEST_ALL_CC_SEED) def FuseGTestAllCc(gtest_root, output_dir): """Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir.""" output_file = file(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w') FuseGTestAllCcToFile(gtest_root, output_file) output_file.close() def FuseGTest(gtest_root, output_dir): """Fuses gtest.h and gtest-all.cc.""" ValidateGTestRootDir(gtest_root) ValidateOutputDir(output_dir) FuseGTestH(gtest_root, output_dir) FuseGTestAllCc(gtest_root, output_dir) def main(): argc = len(sys.argv) if argc == 2: # fuse_gtest_files.py OUTPUT_DIR FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1]) elif argc == 3: # fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR FuseGTest(sys.argv[1], sys.argv[2]) else: print __doc__ sys.exit(1) if __name__ == '__main__': main()
lgpl-2.1
digiholic/universalSmashSystem
engine/subactions/control/conditional.py
2
4500
from engine.subaction import * class If(SubAction): subact_group = 'Control' fields = [NodeMap('variable','string','if>variable',''), NodeMap('source','string','if>variable|source','action'), NodeMap('function','string','if|function','=='), NodeMap('value','dynamic','if>value',True), NodeMap('if_actions','string','if>pass',''), NodeMap('else_actions','string','if>fail','') ] def __init__(self,_variable='',_source='action',_function='==',_value='True',_ifActions='',_elseActions=''): SubAction.__init__(self) self.variable = _variable self.source = _source self.function = _function self.value = _value self.if_actions = _ifActions self.else_actions = _elseActions def execute(self, _action, _actor): SubAction.execute(self, _action, _actor) if self.variable == '': return if self.source == 'fighter' or self.source == 'actor': if hasattr(_actor, 'owner'): _actor = _actor.owner if hasattr(_actor, 'stats') and _actor.stats.has_key(self.variable): variable = _actor.stats[self.variable] elif _actor.variables.has_key(self.variable): variable = _actor.variables[self.variable] else: variable = getattr(_actor, self.variable) elif self.source == 'article' and hasattr(_actor, 'owner'): variable = _actor.variables[self.variable] elif self.source == 'object': variable = _actor.variables[self.variable] else: variable = getattr(_action, self.variable) if self.function == '==': function = lambda var,val: var == val elif self.function == '!=': function = lambda var,val: not var == val elif self.function == '>=': function = lambda var,val: var >= val elif self.function == '<=': function = lambda var,val: var <= val elif self.function == '>': function = lambda var,val: var > val elif self.function == '<': function = lambda var,val: var < val elif self.function == 'is': function = lambda var,val: var is val elif self.function == 'is not': function = lambda var,val: var is not val elif self.function == 'true': function = lambda var,val: bool(var) elif self.function == 'false': function = lambda var,val: not bool(var) cond = function(variable,self.value) print(self.source,self.variable,self.value) print('COND',cond) print('EVENTS',_action.events) print(self.if_actions,self.else_actions) if cond: if self.if_actions and _action.events.has_key(self.if_actions): for act in _action.events[self.if_actions]: act.execute(_action,_actor) else: if self.else_actions and _action.events.has_key(self.else_actions): for act in _action.events[self.else_actions]: act.execute(_action,_actor) def getPropertiesPanel(self, _root): return subactionSelector.IfProperties(_root,self) def getDisplayName(self): return 'If '+self.source+' '+self.variable+' '+str(self.function)+' '+str(self.value)+': '+self.if_actions def getXmlElement(self): elem = ElementTree.Element('If') elem.attrib['function'] = self.function variable_elem = ElementTree.Element('variable') variable_elem.attrib['source'] = self.source variable_elem.text = str(self.variable) elem.append(variable_elem) value_elem = ElementTree.Element('value') value_elem.attrib['type'] = type(self.value).__name__ value_elem.text = str(self.value) elem.append(value_elem) if self.if_actions: pass_elem = ElementTree.Element('pass') pass_elem.text = self.if_actions elem.append(pass_elem) if self.else_actions: fail_elem = ElementTree.Element('fail') fail_elem.text = self.else_actions elem.append(fail_elem) return elem
gpl-3.0
ragupta-git/ImcSdk
imcsdk/mometa/huu/HuuFirmwareCatalogComponent.py
1
4134
"""This module contains the general information for HuuFirmwareCatalogComponent ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class HuuFirmwareCatalogComponentConsts: pass class HuuFirmwareCatalogComponent(ManagedObject): """This is HuuFirmwareCatalogComponent class.""" consts = HuuFirmwareCatalogComponentConsts() naming_props = set([u'id']) mo_meta = { "classic": MoMeta("HuuFirmwareCatalogComponent", "huuFirmwareCatalogComponent", "id-[id]", VersionMeta.Version151f, "OutputOnly", 0xf, [], ["admin", "read-only", "user"], [u'huuFirmwareCatalog'], [], ["Get"]), "modular": MoMeta("HuuFirmwareCatalogComponent", "huuFirmwareCatalogComponent", "id-[id]", VersionMeta.Version2013e, "OutputOnly", 0xf, [], ["admin", "read-only", "user"], [u'huuFirmwareCatalog'], [], ["Get"]) } prop_meta = { "classic": { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version151f, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "component_name": MoPropertyMeta("component_name", "componentName", "string", VersionMeta.Version151f, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "description": MoPropertyMeta("description", "description", "string", VersionMeta.Version151f, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version151f, MoPropertyMeta.READ_ONLY, 0x2, 0, 255, None, [], []), "id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version151f, MoPropertyMeta.NAMING, None, None, None, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version151f, MoPropertyMeta.READ_ONLY, 0x4, 0, 255, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version151f, MoPropertyMeta.READ_ONLY, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []), }, "modular": { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version2013e, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "component_name": MoPropertyMeta("component_name", "componentName", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "description": MoPropertyMeta("description", "description", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, 0x2, 0, 255, None, [], []), "id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version2013e, MoPropertyMeta.NAMING, None, None, None, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, 0x4, 0, 255, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []), }, } prop_map = { "classic": { "childAction": "child_action", "componentName": "component_name", "description": "description", "dn": "dn", "id": "id", "rn": "rn", "status": "status", }, "modular": { "childAction": "child_action", "componentName": "component_name", "description": "description", "dn": "dn", "id": "id", "rn": "rn", "status": "status", }, } def __init__(self, parent_mo_or_dn, id, **kwargs): self._dirty_mask = 0 self.id = id self.child_action = None self.component_name = None self.description = None self.status = None ManagedObject.__init__(self, "HuuFirmwareCatalogComponent", parent_mo_or_dn, **kwargs)
apache-2.0
cyril51/Sick-Beard
lib/guessit/transfo/guess_weak_episodes_rexps.py
56
2126
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2012 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GuessIt 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 # Lesser GNU General Public License for more details. # # You should have received a copy of the Lesser GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import unicode_literals from guessit import Guess from guessit.transfo import SingleNodeGuesser from guessit.patterns import weak_episode_rexps import re import logging log = logging.getLogger(__name__) def guess_weak_episodes_rexps(string, node): if 'episodeNumber' in node.root.info: return None, None for rexp, span_adjust in weak_episode_rexps: match = re.search(rexp, string, re.IGNORECASE) if match: metadata = match.groupdict() span = (match.start() + span_adjust[0], match.end() + span_adjust[1]) epnum = int(metadata['episodeNumber']) if epnum > 100: season, epnum = epnum // 100, epnum % 100 # episodes which have a season > 25 are most likely errors # (Simpsons is at 23!) if season > 25: continue return Guess({ 'season': season, 'episodeNumber': epnum }, confidence=0.6), span else: return Guess(metadata, confidence=0.3), span return None, None guess_weak_episodes_rexps.use_node = True def process(mtree): SingleNodeGuesser(guess_weak_episodes_rexps, 0.6, log).process(mtree)
gpl-3.0
xinjiguaike/edx-platform
common/djangoapps/util/db.py
109
2095
""" Utility functions related to databases. """ from functools import wraps import random from django.db import connection, transaction MYSQL_MAX_INT = (2 ** 31) - 1 def commit_on_success_with_read_committed(func): # pylint: disable=invalid-name """ Decorator which executes the decorated function inside a transaction with isolation level set to READ COMMITTED. If the function returns a response the transaction is committed and if the function raises an exception the transaction is rolled back. Raises TransactionManagementError if there are already more than 1 level of transactions open. Note: This only works on MySQL. """ @wraps(func) def wrapper(*args, **kwargs): # pylint: disable=missing-docstring if connection.vendor == 'mysql': # The isolation level cannot be changed while a transaction is in progress. So we close any existing one. if connection.transaction_state: if len(connection.transaction_state) == 1: connection.commit() # We can commit all open transactions. But it does not seem like a good idea. elif len(connection.transaction_state) > 1: raise transaction.TransactionManagementError('Cannot change isolation level. ' 'More than 1 level of nested transactions.') # This will set the transaction isolation level to READ COMMITTED for the next transaction. cursor = connection.cursor() cursor.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED") with transaction.commit_on_success(): return func(*args, **kwargs) return wrapper def generate_int_id(minimum=0, maximum=MYSQL_MAX_INT, used_ids=None): """ Return a unique integer in the range [minimum, maximum], inclusive. """ if used_ids is None: used_ids = [] cid = random.randint(minimum, maximum) while cid in used_ids: cid = random.randint(minimum, maximum) return cid
agpl-3.0
chrisjaquet/FreeCAD
src/Mod/Start/StartPage/ArchDesign.py
32
1805
#*************************************************************************** #* * #* Copyright (c) 2012 * #* Yorik van Havre <yorik@uncreated.net> * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* * #* This program is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warranty of * #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * #* GNU Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library General Public * #* License along with this program; if not, write to the Free Software * #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * #* USA * #* * #*************************************************************************** import FreeCADGui FreeCADGui.activateWorkbench("ArchWorkbench") App.newDocument()
lgpl-2.1