repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
EvaSDK/sqlalchemy
refs/heads/master
test/orm/test_manytomany.py
32
from sqlalchemy.testing import assert_raises, \ assert_raises_message, eq_ import sqlalchemy as sa from sqlalchemy import testing from sqlalchemy import Integer, String, ForeignKey from sqlalchemy.testing.schema import Table from sqlalchemy.testing.schema import Column from sqlalchemy.orm import mapper, relationship, Session, \ exc as orm_exc, sessionmaker, backref from sqlalchemy.testing import fixtures class M2MTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table('place', metadata, Column('place_id', Integer, test_needs_autoincrement=True, primary_key=True), Column('name', String(30), nullable=False), test_needs_acid=True, ) Table('transition', metadata, Column('transition_id', Integer, test_needs_autoincrement=True, primary_key=True), Column('name', String(30), nullable=False), test_needs_acid=True, ) Table('place_thingy', metadata, Column('thingy_id', Integer, test_needs_autoincrement=True, primary_key=True), Column('place_id', Integer, ForeignKey('place.place_id'), nullable=False), Column('name', String(30), nullable=False), test_needs_acid=True, ) # association table #1 Table('place_input', metadata, Column('place_id', Integer, ForeignKey('place.place_id')), Column('transition_id', Integer, ForeignKey('transition.transition_id')), test_needs_acid=True, ) # association table #2 Table('place_output', metadata, Column('place_id', Integer, ForeignKey('place.place_id')), Column('transition_id', Integer, ForeignKey('transition.transition_id')), test_needs_acid=True, ) Table('place_place', metadata, Column('pl1_id', Integer, ForeignKey('place.place_id')), Column('pl2_id', Integer, ForeignKey('place.place_id')), test_needs_acid=True, ) @classmethod def setup_classes(cls): class Place(cls.Basic): def __init__(self, name): self.name = name class PlaceThingy(cls.Basic): def __init__(self, name): self.name = name class Transition(cls.Basic): def __init__(self, name): self.name = name def test_overlapping_attribute_error(self): place, Transition, place_input, Place, transition = (self.tables.place, self.classes.Transition, self.tables.place_input, self.classes.Place, self.tables.transition) mapper(Place, place, properties={ 'transitions': relationship(Transition, secondary=place_input, backref='places') }) mapper(Transition, transition, properties={ 'places': relationship(Place, secondary=place_input, backref='transitions') }) assert_raises_message(sa.exc.ArgumentError, "property of that name exists", sa.orm.configure_mappers) def test_self_referential_roundtrip(self): place, Place, place_place = (self.tables.place, self.classes.Place, self.tables.place_place) mapper(Place, place, properties={ 'places': relationship( Place, secondary=place_place, primaryjoin=place.c.place_id == place_place.c.pl1_id, secondaryjoin=place.c.place_id == place_place.c.pl2_id, order_by=place_place.c.pl2_id ) }) sess = Session() p1 = Place('place1') p2 = Place('place2') p3 = Place('place3') p4 = Place('place4') p5 = Place('place5') p6 = Place('place6') p7 = Place('place7') sess.add_all((p1, p2, p3, p4, p5, p6, p7)) p1.places.append(p2) p1.places.append(p3) p5.places.append(p6) p6.places.append(p1) p7.places.append(p1) p1.places.append(p5) p4.places.append(p3) p3.places.append(p4) sess.commit() eq_(p1.places, [p2, p3, p5]) eq_(p5.places, [p6]) eq_(p7.places, [p1]) eq_(p6.places, [p1]) eq_(p4.places, [p3]) eq_(p3.places, [p4]) eq_(p2.places, []) def test_self_referential_bidirectional_mutation(self): place, Place, place_place = (self.tables.place, self.classes.Place, self.tables.place_place) mapper(Place, place, properties={ 'child_places': relationship( Place, secondary=place_place, primaryjoin=place.c.place_id == place_place.c.pl1_id, secondaryjoin=place.c.place_id == place_place.c.pl2_id, order_by=place_place.c.pl2_id, backref='parent_places' ) }) sess = Session() p1 = Place('place1') p2 = Place('place2') p2.parent_places = [p1] sess.add_all([p1, p2]) p1.parent_places.append(p2) sess.commit() assert p1 in p2.parent_places assert p2 in p1.parent_places def test_joinedload_on_double(self): """test that a mapper can have two eager relationships to the same table, via two different association tables. aliases are required.""" place_input, transition, Transition, PlaceThingy, \ place, place_thingy, Place, \ place_output = (self.tables.place_input, self.tables.transition, self.classes.Transition, self.classes.PlaceThingy, self.tables.place, self.tables.place_thingy, self.classes.Place, self.tables.place_output) mapper(PlaceThingy, place_thingy) mapper(Place, place, properties={ 'thingies': relationship(PlaceThingy, lazy='joined') }) mapper(Transition, transition, properties=dict( inputs=relationship(Place, place_output, lazy='joined'), outputs=relationship(Place, place_input, lazy='joined'), ) ) tran = Transition('transition1') tran.inputs.append(Place('place1')) tran.outputs.append(Place('place2')) tran.outputs.append(Place('place3')) sess = Session() sess.add(tran) sess.commit() r = sess.query(Transition).all() self.assert_unordered_result(r, Transition, {'name': 'transition1', 'inputs': (Place, [{'name': 'place1'}]), 'outputs': (Place, [{'name': 'place2'}, {'name': 'place3'}]) }) def test_bidirectional(self): place_input, transition, Transition, Place, place, place_output = ( self.tables.place_input, self.tables.transition, self.classes.Transition, self.classes.Place, self.tables.place, self.tables.place_output) mapper(Place, place) mapper(Transition, transition, properties=dict( inputs=relationship(Place, place_output, backref=backref('inputs', order_by=transition.c.transition_id), order_by=Place.place_id), outputs=relationship(Place, place_input, backref=backref('outputs', order_by=transition.c.transition_id), order_by=Place.place_id), ) ) t1 = Transition('transition1') t2 = Transition('transition2') t3 = Transition('transition3') p1 = Place('place1') p2 = Place('place2') p3 = Place('place3') sess = Session() sess.add_all([p3, p1, t1, t2, p2, t3]) t1.inputs.append(p1) t1.inputs.append(p2) t1.outputs.append(p3) t2.inputs.append(p1) p2.inputs.append(t2) p3.inputs.append(t2) p1.outputs.append(t1) sess.commit() self.assert_result([t1], Transition, {'outputs': (Place, [{'name': 'place3'}, {'name': 'place1'}])}) self.assert_result([p2], Place, {'inputs': (Transition, [{'name': 'transition1'}, {'name': 'transition2'}])}) @testing.requires.sane_multi_rowcount def test_stale_conditions(self): Place, Transition, place_input, place, transition = ( self.classes.Place, self.classes.Transition, self.tables.place_input, self.tables.place, self.tables.transition) mapper(Place, place, properties={ 'transitions': relationship(Transition, secondary=place_input, passive_updates=False) }) mapper(Transition, transition) p1 = Place('place1') t1 = Transition('t1') p1.transitions.append(t1) sess = sessionmaker()() sess.add_all([p1, t1]) sess.commit() p1.place_id p1.transitions sess.execute("delete from place_input", mapper=Place) p1.place_id = 7 assert_raises_message( orm_exc.StaleDataError, r"UPDATE statement on table 'place_input' expected to " r"update 1 row\(s\); Only 0 were matched.", sess.commit ) sess.rollback() p1.place_id p1.transitions sess.execute("delete from place_input", mapper=Place) p1.transitions.remove(t1) assert_raises_message( orm_exc.StaleDataError, r"DELETE statement on table 'place_input' expected to " r"delete 1 row\(s\); Only 0 were matched.", sess.commit ) class AssortedPersistenceTests(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table("left", metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('data', String(30)) ) Table("right", metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('data', String(30)), ) Table('secondary', metadata, Column('left_id', Integer, ForeignKey('left.id'), primary_key=True), Column('right_id', Integer, ForeignKey('right.id'), primary_key=True), ) @classmethod def setup_classes(cls): class A(cls.Comparable): pass class B(cls.Comparable): pass def _standard_bidirectional_fixture(self): left, secondary, right = self.tables.left, \ self.tables.secondary, self.tables.right A, B = self.classes.A, self.classes.B mapper(A, left, properties={ 'bs': relationship(B, secondary=secondary, backref='as', order_by=right.c.id) }) mapper(B, right) def _bidirectional_onescalar_fixture(self): left, secondary, right = self.tables.left, \ self.tables.secondary, self.tables.right A, B = self.classes.A, self.classes.B mapper(A, left, properties={ 'bs': relationship(B, secondary=secondary, backref=backref('a', uselist=False), order_by=right.c.id) }) mapper(B, right) def test_session_delete(self): self._standard_bidirectional_fixture() A, B = self.classes.A, self.classes.B secondary = self.tables.secondary sess = Session() sess.add_all([ A(data='a1', bs=[B(data='b1')]), A(data='a2', bs=[B(data='b2')]) ]) sess.commit() a1 = sess.query(A).filter_by(data='a1').one() sess.delete(a1) sess.flush() eq_(sess.query(secondary).count(), 1) a2 = sess.query(A).filter_by(data='a2').one() sess.delete(a2) sess.flush() eq_(sess.query(secondary).count(), 0) def test_remove_scalar(self): # test setting a uselist=False to None self._bidirectional_onescalar_fixture() A, B = self.classes.A, self.classes.B secondary = self.tables.secondary sess = Session() sess.add_all([ A(data='a1', bs=[B(data='b1'), B(data='b2')]), ]) sess.commit() a1 = sess.query(A).filter_by(data='a1').one() b2 = sess.query(B).filter_by(data='b2').one() assert b2.a is a1 b2.a = None sess.commit() eq_(a1.bs, [B(data='b1')]) eq_(b2.a, None) eq_(sess.query(secondary).count(), 1)
upshot-nutrition/upshot-nutrition.github.io
refs/heads/master
node_modules/node-gyp/gyp/pylib/gyp/generator/make.py
896
# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Notes: # # This is all roughly based on the Makefile system used by the Linux # kernel, but is a non-recursive make -- we put the entire dependency # graph in front of make and let it figure it out. # # The code below generates a separate .mk file for each target, but # all are sourced by the top-level Makefile. This means that all # variables in .mk-files clobber one another. Be careful to use := # where appropriate for immediate evaluation, and similarly to watch # that you're not relying on a variable value to last beween different # .mk files. # # TODOs: # # Global settings and utility functions are currently stuffed in the # toplevel Makefile. It may make sense to generate some .mk files on # the side to keep the the files readable. import os import re import sys import subprocess import gyp import gyp.common import gyp.xcode_emulation from gyp.common import GetEnvironFallback from gyp.common import GypError generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'SHARED_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'INTERMEDIATE_DIR': '$(obj).$(TOOLSET)/$(TARGET)/geni', 'SHARED_INTERMEDIATE_DIR': '$(obj)/gen', 'PRODUCT_DIR': '$(builddir)', 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python. 'RULE_INPUT_DIRNAME': '%(INPUT_DIRNAME)s', # This gets expanded by Python. 'RULE_INPUT_PATH': '$(abspath $<)', 'RULE_INPUT_EXT': '$(suffix $<)', 'RULE_INPUT_NAME': '$(notdir $<)', 'CONFIGURATION_NAME': '$(BUILDTYPE)', } # Make supports multiple toolsets generator_supports_multiple_toolsets = True # Request sorted dependencies in the order from dependents to dependencies. generator_wants_sorted_dependencies = False # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Make generator. import gyp.generator.xcode as xcode_generator global generator_additional_non_configuration_keys generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) global generator_additional_path_sections generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) COMPILABLE_EXTENSIONS.update({'.m': 'objc', '.mm' : 'objcxx'}) else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR','$(builddir)/lib.$(TOOLSET)') default_variables.setdefault('LIB_DIR', '$(obj).$(TOOLSET)') def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) android_ndk_version = generator_flags.get('android_ndk_version', None) # Android NDK requires a strict link order. if android_ndk_version: global generator_wants_sorted_dependencies generator_wants_sorted_dependencies = True output_dir = params['options'].generator_output or \ params['options'].toplevel_dir builddir_name = generator_flags.get('output_dir', 'out') qualified_out_dir = os.path.normpath(os.path.join( output_dir, builddir_name, 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': params['options'].toplevel_dir, 'qualified_out_dir': qualified_out_dir, } # The .d checking code below uses these functions: # wildcard, sort, foreach, shell, wordlist # wildcard can handle spaces, the rest can't. # Since I could find no way to make foreach work with spaces in filenames # correctly, the .d files have spaces replaced with another character. The .d # file for # Chromium\ Framework.framework/foo # is for example # out/Release/.deps/out/Release/Chromium?Framework.framework/foo # This is the replacement character. SPACE_REPLACEMENT = '?' LINK_COMMANDS_LINUX = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) # Due to circular dependencies between libraries :(, we wrap the # special "figure out circular dependencies" flags around the entire # input list during linking. quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) # We support two kinds of shared objects (.so): # 1) shared_library, which is just bundling together many dependent libraries # into a link line. # 2) loadable_module, which is generating a module intended for dlopen(). # # They differ only slightly: # In the former case, we want to package all dependent code into the .so. # In the latter case, we want to package just the API exposed by the # outermost module. # This means shared_library uses --whole-archive, while loadable_module doesn't. # (Note that --whole-archive is incompatible with the --start-group used in # normal linking.) # Other shared-object link notes: # - Set SONAME to the library filename so our binaries don't reference # the local, absolute paths used on the link command-line. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) """ LINK_COMMANDS_MAC = """\ quiet_cmd_alink = LIBTOOL-STATIC $@ cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ LINK_COMMANDS_ANDROID = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) # Due to circular dependencies between libraries :(, we wrap the # special "figure out circular dependencies" flags around the entire # input list during linking. quiet_cmd_link = LINK($(TOOLSET)) $@ quiet_cmd_link_host = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) cmd_link_host = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) # Other shared-object link notes: # - Set SONAME to the library filename so our binaries don't reference # the local, absolute paths used on the link command-line. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) quiet_cmd_solink_module_host = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module_host = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ LINK_COMMANDS_AIX = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # Header of toplevel Makefile. # This should go into the build tree, but it's easier to keep it here for now. SHARED_HEADER = ("""\ # We borrow heavily from the kernel build setup, though we are simpler since # we don't have Kconfig tweaking settings on us. # The implicit make rules have it looking for RCS files, among other things. # We instead explicitly write all the rules we care about. # It's even quicker (saves ~200ms) to pass -r on the command line. MAKEFLAGS=-r # The source directory tree. srcdir := %(srcdir)s abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= %(builddir)s # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= %(default_configuration)s # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := %(make_global_settings)s CC.target ?= %(CC.target)s CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS) CXX.target ?= %(CXX.target)s CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS) LINK.target ?= %(LINK.target)s LDFLAGS.target ?= $(LDFLAGS) AR.target ?= $(AR) # C++ apps need to be linked with g++. LINK ?= $(CXX.target) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= %(CC.host)s CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host) CXX.host ?= %(CXX.host)s CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host) LINK.host ?= %(LINK.host)s LDFLAGS.host ?= AR.host ?= %(AR.host)s # Define a dir function that can handle spaces. # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces replace_spaces = $(subst $(space),""" + SPACE_REPLACEMENT + """,$1) unreplace_spaces = $(subst """ + SPACE_REPLACEMENT + """,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = -MMD -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \\ # DEP3 # to # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters.""" r""" define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1). sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines. sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef """ """ # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< %(extra_commands)s quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = rm -rf "$@" && cp %(copy_archive_args)s "$<" "$@" %(link_commands)s """ r""" # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%%s\n' '$(call escape_quotes,$(1))' """ """ # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \\ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain """ + SPACE_REPLACEMENT + \ """ instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds until one fails. define do_postbuilds @E=0;\\ for p in $(POSTBUILDS); do\\ eval $$p;\\ E=$$?;\\ if [ $$E -ne 0 ]; then\\ break;\\ fi;\\ done;\\ if [ $$E -ne 0 ]; then\\ rm -rf "$@";\\ exit $$E;\\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains """ + \ SPACE_REPLACEMENT + """ for # spaces already and dirx strips the """ + SPACE_REPLACEMENT + \ """ characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word %(flock_index)d,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "%(default_target)s" target first so it is the default, # even though we don't have the deps yet. .PHONY: %(default_target)s %(default_target)s: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %%.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: """) SHARED_HEADER_MAC_COMMANDS = """ quiet_cmd_objc = CXX($(TOOLSET)) $@ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_objcxx = CXX($(TOOLSET)) $@ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # Commands for precompiled header files. quiet_cmd_pch_c = CXX($(TOOLSET)) $@ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_m = CXX($(TOOLSET)) $@ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # gyp-mac-tool is written next to the root Makefile by gyp. # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd # already. quiet_cmd_mac_tool = MACTOOL $(4) $< cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) quiet_cmd_infoplist = INFOPLIST $@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" """ def WriteRootHeaderSuffixRules(writer): extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower) writer.write('# Suffix rules, putting all outputs into $(obj).\n') for ext in extensions: writer.write('$(obj).$(TOOLSET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD\n' % ext) writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext]) writer.write('\n# Try building from generated source, too.\n') for ext in extensions: writer.write( '$(obj).$(TOOLSET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD\n' % ext) writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext]) writer.write('\n') for ext in extensions: writer.write('$(obj).$(TOOLSET)/%%.o: $(obj)/%%%s FORCE_DO_CMD\n' % ext) writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext]) writer.write('\n') SHARED_HEADER_SUFFIX_RULES_COMMENT1 = ("""\ # Suffix rules, putting all outputs into $(obj). """) SHARED_HEADER_SUFFIX_RULES_COMMENT2 = ("""\ # Try building from generated source, too. """) SHARED_FOOTER = """\ # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif """ header = """\ # This file is generated by gyp; do not edit. """ # Maps every compilable file extension to the do_cmd that compiles it. COMPILABLE_EXTENSIONS = { '.c': 'cc', '.cc': 'cxx', '.cpp': 'cxx', '.cxx': 'cxx', '.s': 'cc', '.S': 'cc', } def Compilable(filename): """Return true if the file is compilable (should be in OBJS).""" for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS): if res: return True return False def Linkable(filename): """Return true if the file is linkable (should be on the link line).""" return filename.endswith('.o') def Target(filename): """Translate a compilable filename to its .o target.""" return os.path.splitext(filename)[0] + '.o' def EscapeShellArgument(s): """Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python """ return "'" + s.replace("'", "'\\''") + "'" def EscapeMakeVariableExpansion(s): """Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.""" return s.replace('$', '$$') def EscapeCppDefine(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = EscapeShellArgument(s) s = EscapeMakeVariableExpansion(s) # '#' characters must be escaped even embedded in a string, else Make will # treat it as the start of a comment. return s.replace('#', r'\#') def QuoteIfNecessary(string): """TODO: Should this ideally be replaced with one or more of the above functions?""" if '"' in string: string = '"' + string.replace('"', '\\"') + '"' return string def StringToMakefileVariable(string): """Convert a string to a value that is acceptable as a make variable name.""" return re.sub('[^a-zA-Z0-9_]', '_', string) srcdir_prefix = '' def Sourceify(path): """Convert a path to its source directory form.""" if '$(' in path: return path if os.path.isabs(path): return path return srcdir_prefix + path def QuoteSpaces(s, quote=r'\ '): return s.replace(' ', quote) # TODO: Avoid code duplication with _ValidateSourcesForMSVSProject in msvs.py. def _ValidateSourcesForOSX(spec, all_sources): """Makes sure if duplicate basenames are not specified in the source list. Arguments: spec: The target dictionary containing the properties of the target. """ if spec.get('type', None) != 'static_library': return basenames = {} for source in all_sources: name, ext = os.path.splitext(source) is_compiled_file = ext in [ '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S'] if not is_compiled_file: continue basename = os.path.basename(name) # Don't include extension. basenames.setdefault(basename, []).append(source) error = '' for basename, files in basenames.iteritems(): if len(files) > 1: error += ' %s: %s\n' % (basename, ' '.join(files)) if error: print('static library %s has several files with the same basename:\n' % spec['target_name'] + error + 'libtool on OS X will generate' + ' warnings for them.') raise GypError('Duplicate basenames in sources section, see list above') # Map from qualified target to path to output. target_outputs = {} # Map from qualified target to any linkable output. A subset # of target_outputs. E.g. when mybinary depends on liba, we want to # include liba in the linker line; when otherbinary depends on # mybinary, we just want to build mybinary first. target_link_deps = {} class MakefileWriter(object): """MakefileWriter packages up the writing of one target-specific foobar.mk. Its only real entry point is Write(), and is mostly used for namespacing. """ def __init__(self, generator_flags, flavor): self.generator_flags = generator_flags self.flavor = flavor self.suffix_rules_srcdir = {} self.suffix_rules_objdir1 = {} self.suffix_rules_objdir2 = {} # Generate suffix rules for all compilable extensions. for ext in COMPILABLE_EXTENSIONS.keys(): # Suffix rules for source folder. self.suffix_rules_srcdir.update({ext: ("""\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD @$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]))}) # Suffix rules for generated source files. self.suffix_rules_objdir1.update({ext: ("""\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD @$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]))}) self.suffix_rules_objdir2.update({ext: ("""\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD @$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]))}) def Write(self, qualified_target, base_path, output_filename, spec, configs, part_of_all): """The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all' """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, 'w') self.fp.write(header) self.qualified_target = qualified_target self.path = base_path self.target = spec['target_name'] self.type = spec['type'] self.toolset = spec['toolset'] self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) if self.flavor == 'mac': self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) else: self.xcode_settings = None deps, link_deps = self.ComputeDeps(spec) # Some of the generation below can add extra output, sources, or # link dependencies. All of the out params of the functions that # follow use names like extra_foo. extra_outputs = [] extra_sources = [] extra_link_deps = [] extra_mac_bundle_resources = [] mac_bundle_deps = [] if self.is_mac_bundle: self.output = self.ComputeMacBundleOutput(spec) self.output_binary = self.ComputeMacBundleBinaryOutput(spec) else: self.output = self.output_binary = self.ComputeOutput(spec) self.is_standalone_static_library = bool( spec.get('standalone_static_library', 0)) self._INSTALLABLE_TARGETS = ('executable', 'loadable_module', 'shared_library') if (self.is_standalone_static_library or self.type in self._INSTALLABLE_TARGETS): self.alias = os.path.basename(self.output) install_path = self._InstallableTargetInstallPath() else: self.alias = self.output install_path = self.output self.WriteLn("TOOLSET := " + self.toolset) self.WriteLn("TARGET := " + self.target) # Actions must come first, since they can generate more OBJs for use below. if 'actions' in spec: self.WriteActions(spec['actions'], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all) # Rules must be early like actions. if 'rules' in spec: self.WriteRules(spec['rules'], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all) if 'copies' in spec: self.WriteCopies(spec['copies'], extra_outputs, part_of_all) # Bundle resources. if self.is_mac_bundle: all_mac_bundle_resources = ( spec.get('mac_bundle_resources', []) + extra_mac_bundle_resources) self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps) self.WriteMacInfoPlist(mac_bundle_deps) # Sources. all_sources = spec.get('sources', []) + extra_sources if all_sources: if self.flavor == 'mac': # libtool on OS X generates warnings for duplicate basenames in the same # target. _ValidateSourcesForOSX(spec, all_sources) self.WriteSources( configs, deps, all_sources, extra_outputs, extra_link_deps, part_of_all, gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)), self.Pchify)) sources = filter(Compilable, all_sources) if sources: self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1) extensions = set([os.path.splitext(s)[1] for s in sources]) for ext in extensions: if ext in self.suffix_rules_srcdir: self.WriteLn(self.suffix_rules_srcdir[ext]) self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2) for ext in extensions: if ext in self.suffix_rules_objdir1: self.WriteLn(self.suffix_rules_objdir1[ext]) for ext in extensions: if ext in self.suffix_rules_objdir2: self.WriteLn(self.suffix_rules_objdir2[ext]) self.WriteLn('# End of this set of suffix rules') # Add dependency from bundle to bundle binary. if self.is_mac_bundle: mac_bundle_deps.append(self.output_binary) self.WriteTarget(spec, configs, deps, extra_link_deps + link_deps, mac_bundle_deps, extra_outputs, part_of_all) # Update global list of target outputs, used in dependency tracking. target_outputs[qualified_target] = install_path # Update global list of link dependencies. if self.type in ('static_library', 'shared_library'): target_link_deps[qualified_target] = self.output_binary # Currently any versions have the same effect, but in future the behavior # could be different. if self.generator_flags.get('android_ndk_version', None): self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps) self.fp.close() def WriteSubMake(self, output_filename, makefile_path, targets, build_dir): """Write a "sub-project" Makefile. This is a small, wrapper Makefile that calls the top-level Makefile to build the targets from a single gyp file (i.e. a sub-project). Arguments: output_filename: sub-project Makefile name to write makefile_path: path to the top-level Makefile targets: list of "all" targets for this sub-project build_dir: build output directory, relative to the sub-project """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, 'w') self.fp.write(header) # For consistency with other builders, put sub-project build output in the # sub-project dir (see test/subdirectory/gyptest-subdir-all.py). self.WriteLn('export builddir_name ?= %s' % os.path.join(os.path.dirname(output_filename), build_dir)) self.WriteLn('.PHONY: all') self.WriteLn('all:') if makefile_path: makefile_path = ' -C ' + makefile_path self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets))) self.fp.close() def WriteActions(self, actions, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for action in actions: name = StringToMakefileVariable('%s_%s' % (self.qualified_target, action['action_name'])) self.WriteLn('### Rules for action "%s":' % action['action_name']) inputs = action['inputs'] outputs = action['outputs'] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get('process_outputs_as_sources', False)): extra_sources += outputs if int(action.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs # Write the actual command. action_commands = action['action'] if self.flavor == 'mac': action_commands = [gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action_commands] command = gyp.common.EncodePOSIXShellList(action_commands) if 'message' in action: self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, action['message'])) else: self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, name)) if len(dirs) > 0: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command cd_action = 'cd %s; ' % Sourceify(self.path or '.') # command and cd_action get written to a toplevel variable called # cmd_foo. Toplevel variables can't handle things that change per # makefile like $(TARGET), so hardcode the target. command = command.replace('$(TARGET)', self.target) cd_action = cd_action.replace('$(TARGET)', self.target) # Set LD_LIBRARY_PATH in case the action runs an executable from this # build which links to shared libs from this build. # actions run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn('cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:' '$(builddir)/lib.target:$$LD_LIBRARY_PATH; ' 'export LD_LIBRARY_PATH; ' '%s%s' % (name, cd_action, command)) self.WriteLn() outputs = map(self.Absolutify, outputs) # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the obj # variable for the action rule with an absolute version so that the output # goes in the right place. # Only write the 'obj' and 'builddir' rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. # Same for environment. self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0])) self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0])) self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv()) for input in inputs: assert ' ' not in input, ( "Spaces in action input filenames not supported (%s)" % input) for output in outputs: assert ' ' not in output, ( "Spaces in action output filenames not supported (%s)" % output) # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] self.WriteDoCmd(outputs, map(Sourceify, map(self.Absolutify, inputs)), part_of_all=part_of_all, command=name) # Stuff the outputs in a variable so we can refer to them later. outputs_variable = 'action_%s_outputs' % name self.WriteLn('%s := %s' % (outputs_variable, ' '.join(outputs))) extra_outputs.append('$(%s)' % outputs_variable) self.WriteLn() self.WriteLn() def WriteRules(self, rules, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for rule in rules: name = StringToMakefileVariable('%s_%s' % (self.qualified_target, rule['rule_name'])) count = 0 self.WriteLn('### Generated for rule %s:' % name) all_outputs = [] for rule_source in rule.get('rule_sources', []): dirs = set() (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = \ os.path.splitext(rule_source_basename) outputs = [self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule['outputs']] for out in outputs: dir = os.path.dirname(out) if dir: dirs.add(dir) if int(rule.get('process_outputs_as_sources', False)): extra_sources += outputs if int(rule.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs inputs = map(Sourceify, map(self.Absolutify, [rule_source] + rule.get('inputs', []))) actions = ['$(call do_cmd,%s_%d)' % (name, count)] if name == 'resources_grit': # HACK: This is ugly. Grit intentionally doesn't touch the # timestamp of its output file when the file doesn't change, # which is fine in hash-based dependency systems like scons # and forge, but not kosher in the make world. After some # discussion, hacking around it here seems like the least # amount of pain. actions += ['@touch --no-create $@'] # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] outputs = map(self.Absolutify, outputs) all_outputs += outputs # Only write the 'obj' and 'builddir' rules for the "primary" output # (:1); it's superfluous for the "extra outputs", and this avoids # accidentally writing duplicate dummy rules for those outputs. self.WriteLn('%s: obj := $(abs_obj)' % outputs[0]) self.WriteLn('%s: builddir := $(abs_builddir)' % outputs[0]) self.WriteMakeRule(outputs, inputs, actions, command="%s_%d" % (name, count)) # Spaces in rule filenames are not supported, but rule variables have # spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)'). # The spaces within the variables are valid, so remove the variables # before checking. variables_with_spaces = re.compile(r'\$\([^ ]* \$<\)') for output in outputs: output = re.sub(variables_with_spaces, '', output) assert ' ' not in output, ( "Spaces in rule filenames not yet supported (%s)" % output) self.WriteLn('all_deps += %s' % ' '.join(outputs)) action = [self.ExpandInputRoot(ac, rule_source_root, rule_source_dirname) for ac in rule['action']] mkdirs = '' if len(dirs) > 0: mkdirs = 'mkdir -p %s; ' % ' '.join(dirs) cd_action = 'cd %s; ' % Sourceify(self.path or '.') # action, cd_action, and mkdirs get written to a toplevel variable # called cmd_foo. Toplevel variables can't handle things that change # per makefile like $(TARGET), so hardcode the target. if self.flavor == 'mac': action = [gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action] action = gyp.common.EncodePOSIXShellList(action) action = action.replace('$(TARGET)', self.target) cd_action = cd_action.replace('$(TARGET)', self.target) mkdirs = mkdirs.replace('$(TARGET)', self.target) # Set LD_LIBRARY_PATH in case the rule runs an executable from this # build which links to shared libs from this build. # rules run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn( "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH=" "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; " "export LD_LIBRARY_PATH; " "%(cd_action)s%(mkdirs)s%(action)s" % { 'action': action, 'cd_action': cd_action, 'count': count, 'mkdirs': mkdirs, 'name': name, }) self.WriteLn( 'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@' % { 'count': count, 'name': name, }) self.WriteLn() count += 1 outputs_variable = 'rule_%s_outputs' % name self.WriteList(all_outputs, outputs_variable) extra_outputs.append('$(%s)' % outputs_variable) self.WriteLn('### Finished generating for rule: %s' % name) self.WriteLn() self.WriteLn('### Finished generating for all rules') self.WriteLn('') def WriteCopies(self, copies, extra_outputs, part_of_all): """Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) part_of_all: flag indicating this target is part of 'all' """ self.WriteLn('### Generated for copy rule.') variable = StringToMakefileVariable(self.qualified_target + '_copies') outputs = [] for copy in copies: for path in copy['files']: # Absolutify() may call normpath, and will strip trailing slashes. path = Sourceify(self.Absolutify(path)) filename = os.path.split(path)[1] output = Sourceify(self.Absolutify(os.path.join(copy['destination'], filename))) # If the output path has variables in it, which happens in practice for # 'copies', writing the environment as target-local doesn't work, # because the variables are already needed for the target name. # Copying the environment variables into global make variables doesn't # work either, because then the .d files will potentially contain spaces # after variable expansion, and .d file handling cannot handle spaces. # As a workaround, manually expand variables at gyp time. Since 'copies' # can't run scripts, there's no need to write the env then. # WriteDoCmd() will escape spaces for .d files. env = self.GetSortedXcodeEnv() output = gyp.xcode_emulation.ExpandEnvVars(output, env) path = gyp.xcode_emulation.ExpandEnvVars(path, env) self.WriteDoCmd([output], [path], 'copy', part_of_all) outputs.append(output) self.WriteLn('%s = %s' % (variable, ' '.join(map(QuoteSpaces, outputs)))) extra_outputs.append('$(%s)' % variable) self.WriteLn() def WriteMacBundleResources(self, resources, bundle_deps): """Writes Makefile code for 'mac_bundle_resources'.""" self.WriteLn('### Generated for mac_bundle_resources') for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, map(Sourceify, map(self.Absolutify, resources))): _, ext = os.path.splitext(output) if ext != '.xcassets': # Make does not supports '.xcassets' emulation. self.WriteDoCmd([output], [res], 'mac_tool,,,copy-bundle-resource', part_of_all=True) bundle_deps.append(output) def WriteMacInfoPlist(self, bundle_deps): """Write Makefile code for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, lambda p: Sourceify(self.Absolutify(p))) if not info_plist: return if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = ('$(obj).$(TOOLSET)/$(TARGET)/' + os.path.basename(info_plist)) self.WriteList(defines, intermediate_plist + ': INFOPLIST_DEFINES', '-D', quoter=EscapeCppDefine) self.WriteMakeRule([intermediate_plist], [info_plist], ['$(call do_cmd,infoplist)', # "Convert" the plist so that any weird whitespace changes from the # preprocessor do not affect the XML parser in mac_tool. '@plutil -convert xml1 $@ $@']) info_plist = intermediate_plist # plists can contain envvars and substitute them into the file. self.WriteSortedXcodeEnv( out, self.GetSortedXcodeEnv(additional_settings=extra_env)) self.WriteDoCmd([out], [info_plist], 'mac_tool,,,copy-info-plist', part_of_all=True) bundle_deps.append(out) def WriteSources(self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all' """ # Write configuration-specific variables for CFLAGS, etc. for configname in sorted(configs.keys()): config = configs[configname] self.WriteList(config.get('defines'), 'DEFS_%s' % configname, prefix='-D', quoter=EscapeCppDefine) if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(configname) cflags_c = self.xcode_settings.GetCflagsC(configname) cflags_cc = self.xcode_settings.GetCflagsCC(configname) cflags_objc = self.xcode_settings.GetCflagsObjC(configname) cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname) else: cflags = config.get('cflags') cflags_c = config.get('cflags_c') cflags_cc = config.get('cflags_cc') self.WriteLn("# Flags passed to all source files."); self.WriteList(cflags, 'CFLAGS_%s' % configname) self.WriteLn("# Flags passed to only C files."); self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname) self.WriteLn("# Flags passed to only C++ files."); self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname) if self.flavor == 'mac': self.WriteLn("# Flags passed to only ObjC files."); self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname) self.WriteLn("# Flags passed to only ObjC++ files."); self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname) includes = config.get('include_dirs') if includes: includes = map(Sourceify, map(self.Absolutify, includes)) self.WriteList(includes, 'INCS_%s' % configname, prefix='-I') compilable = filter(Compilable, sources) objs = map(self.Objectify, map(self.Absolutify, map(Target, compilable))) self.WriteList(objs, 'OBJS') for obj in objs: assert ' ' not in obj, ( "Spaces in object filenames not supported (%s)" % obj) self.WriteLn('# Add to the list of files we specially track ' 'dependencies for.') self.WriteLn('all_deps += $(OBJS)') self.WriteLn() # Make sure our dependencies are built first. if deps: self.WriteMakeRule(['$(OBJS)'], deps, comment = 'Make sure our dependencies are built ' 'before any of us.', order_only = True) # Make sure the actions and rules run first. # If they generate any extra headers etc., the per-.o file dep tracking # will catch the proper rebuilds, so order only is still ok here. if extra_outputs: self.WriteMakeRule(['$(OBJS)'], extra_outputs, comment = 'Make sure our actions/rules run ' 'before any of us.', order_only = True) pchdeps = precompiled_header.GetObjDependencies(compilable, objs ) if pchdeps: self.WriteLn('# Dependencies from obj files to their precompiled headers') for source, obj, gch in pchdeps: self.WriteLn('%s: %s' % (obj, gch)) self.WriteLn('# End precompiled header dependencies') if objs: extra_link_deps.append('$(OBJS)') self.WriteLn("""\ # CFLAGS et al overrides must be target-local. # See "Target-specific Variable Values" in the GNU Make manual.""") self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)") self.WriteLn("$(OBJS): GYP_CFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('c') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_CXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('cc') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE))") if self.flavor == 'mac': self.WriteLn("$(OBJS): GYP_OBJCFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('m') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE)) " "$(CFLAGS_OBJC_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_OBJCXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('mm') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE)) " "$(CFLAGS_OBJCC_$(BUILDTYPE))") self.WritePchTargets(precompiled_header.GetPchBuildCommands()) # If there are any object files in our input file list, link them into our # output. extra_link_deps += filter(Linkable, sources) self.WriteLn() def WritePchTargets(self, pch_commands): """Writes make rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: extra_flags = { 'c': '$(CFLAGS_C_$(BUILDTYPE))', 'cc': '$(CFLAGS_CC_$(BUILDTYPE))', 'm': '$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))', 'mm': '$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))', }[lang] var_name = { 'c': 'GYP_PCH_CFLAGS', 'cc': 'GYP_PCH_CXXFLAGS', 'm': 'GYP_PCH_OBJCFLAGS', 'mm': 'GYP_PCH_OBJCXXFLAGS', }[lang] self.WriteLn("%s: %s := %s " % (gch, var_name, lang_flag) + "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "$(CFLAGS_$(BUILDTYPE)) " + extra_flags) self.WriteLn('%s: %s FORCE_DO_CMD' % (gch, input)) self.WriteLn('\t@$(call do_cmd,pch_%s,1)' % lang) self.WriteLn('') assert ' ' not in gch, ( "Spaces in gch filenames not supported (%s)" % gch) self.WriteLn('all_deps += %s' % gch) self.WriteLn('') def ComputeOutputBasename(self, spec): """Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so' """ assert not self.is_mac_bundle if self.flavor == 'mac' and self.type in ( 'static_library', 'executable', 'shared_library', 'loadable_module'): return self.xcode_settings.GetExecutablePath() target = spec['target_name'] target_prefix = '' target_ext = '' if self.type == 'static_library': if target[:3] == 'lib': target = target[3:] target_prefix = 'lib' target_ext = '.a' elif self.type in ('loadable_module', 'shared_library'): if target[:3] == 'lib': target = target[3:] target_prefix = 'lib' target_ext = '.so' elif self.type == 'none': target = '%s.stamp' % target elif self.type != 'executable': print ("ERROR: What output file should be generated?", "type", self.type, "target", target) target_prefix = spec.get('product_prefix', target_prefix) target = spec.get('product_name', target) product_ext = spec.get('product_extension') if product_ext: target_ext = '.' + product_ext return target_prefix + target + target_ext def _InstallImmediately(self): return self.toolset == 'target' and self.flavor == 'mac' and self.type in ( 'static_library', 'executable', 'shared_library', 'loadable_module') def ComputeOutput(self, spec): """Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so' """ assert not self.is_mac_bundle path = os.path.join('$(obj).' + self.toolset, self.path) if self.type == 'executable' or self._InstallImmediately(): path = '$(builddir)' path = spec.get('product_dir', path) return os.path.join(path, self.ComputeOutputBasename(spec)) def ComputeMacBundleOutput(self, spec): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables['PRODUCT_DIR'] return os.path.join(path, self.xcode_settings.GetWrapperName()) def ComputeMacBundleBinaryOutput(self, spec): """Return the 'output' (full output path) to the binary in a bundle.""" path = generator_default_variables['PRODUCT_DIR'] return os.path.join(path, self.xcode_settings.GetExecutablePath()) def ComputeDeps(self, spec): """Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps). """ deps = [] link_deps = [] if 'dependencies' in spec: deps.extend([target_outputs[dep] for dep in spec['dependencies'] if target_outputs[dep]]) for dep in spec['dependencies']: if dep in target_link_deps: link_deps.append(target_link_deps[dep]) deps.extend(link_deps) # TODO: It seems we need to transitively link in libraries (e.g. -lfoo)? # This hack makes it work: # link_deps.extend(spec.get('libraries', [])) return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps)) def WriteDependencyOnExtraOutputs(self, target, extra_outputs): self.WriteMakeRule([self.output_binary], extra_outputs, comment = 'Build our special outputs first.', order_only = True) def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all' """ self.WriteLn('### Rules for final target.') if extra_outputs: self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs) self.WriteMakeRule(extra_outputs, deps, comment=('Preserve order dependency of ' 'special output on deps.'), order_only = True) target_postbuilds = {} if self.type != 'none': for configname in sorted(configs.keys()): config = configs[configname] if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(configname, generator_default_variables['PRODUCT_DIR'], lambda p: Sourceify(self.Absolutify(p))) # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on. gyp_to_build = gyp.common.InvertRelativePath(self.path) target_postbuild = self.xcode_settings.AddImplicitPostbuilds( configname, QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output))), QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output_binary)))) if target_postbuild: target_postbuilds[configname] = target_postbuild else: ldflags = config.get('ldflags', []) # Compute an rpath for this output if needed. if any(dep.endswith('.so') or '.so.' in dep for dep in deps): # We want to get the literal string "$ORIGIN" into the link command, # so we need lots of escaping. ldflags.append(r'-Wl,-rpath=\$$ORIGIN/lib.%s/' % self.toolset) ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' % self.toolset) library_dirs = config.get('library_dirs', []) ldflags += [('-L%s' % library_dir) for library_dir in library_dirs] self.WriteList(ldflags, 'LDFLAGS_%s' % configname) if self.flavor == 'mac': self.WriteList(self.xcode_settings.GetLibtoolflags(configname), 'LIBTOOLFLAGS_%s' % configname) libraries = spec.get('libraries') if libraries: # Remove duplicate entries libraries = gyp.common.uniquer(libraries) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries) self.WriteList(libraries, 'LIBS') self.WriteLn('%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary)) if self.flavor == 'mac': self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) # Postbuild actions. Like actions, but implicitly depend on the target's # output. postbuilds = [] if self.flavor == 'mac': if target_postbuilds: postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))') postbuilds.extend( gyp.xcode_emulation.GetSpecPostbuildCommands(spec)) if postbuilds: # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE), # so we must output its definition first, since we declare variables # using ":=". self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) for configname in target_postbuilds: self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' % (QuoteSpaces(self.output), configname, gyp.common.EncodePOSIXShellList(target_postbuilds[configname]))) # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path])) for i in xrange(len(postbuilds)): if not postbuilds[i].startswith('$'): postbuilds[i] = EscapeShellArgument(postbuilds[i]) self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output)) self.WriteLn('%s: POSTBUILDS := %s' % ( QuoteSpaces(self.output), ' '.join(postbuilds))) # A bundle directory depends on its dependencies such as bundle resources # and bundle binary. When all dependencies have been built, the bundle # needs to be packaged. if self.is_mac_bundle: # If the framework doesn't contain a binary, then nothing depends # on the actions -- make the framework depend on them directly too. self.WriteDependencyOnExtraOutputs(self.output, extra_outputs) # Bundle dependencies. Note that the code below adds actions to this # target, so if you move these two lines, move the lines below as well. self.WriteList(map(QuoteSpaces, bundle_deps), 'BUNDLE_DEPS') self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output)) # After the framework is built, package it. Needs to happen before # postbuilds, since postbuilds depend on this. if self.type in ('shared_library', 'loadable_module'): self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' % self.xcode_settings.GetFrameworkVersion()) # Bundle postbuilds can depend on the whole bundle, so run them after # the bundle is packaged, not already after the bundle binary is done. if postbuilds: self.WriteLn('\t@$(call do_postbuilds)') postbuilds = [] # Don't write postbuilds for target's output. # Needed by test/mac/gyptest-rebuild.py. self.WriteLn('\t@true # No-op, used by tests') # Since this target depends on binary and resources which are in # nested subfolders, the framework directory will be older than # its dependencies usually. To prevent this rule from executing # on every build (expensive, especially with postbuilds), expliclity # update the time on the framework directory. self.WriteLn('\t@touch -c %s' % QuoteSpaces(self.output)) if postbuilds: assert not self.is_mac_bundle, ('Postbuilds for bundles should be done ' 'on the bundle, not the binary (target \'%s\')' % self.target) assert 'product_dir' not in spec, ('Postbuilds do not work with ' 'custom product_dir') if self.type == 'executable': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'link_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all, postbuilds=postbuilds) elif self.type == 'static_library': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in alink input filenames not supported (%s)" % link_dep) if (self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not self.is_standalone_static_library): self.WriteDoCmd([self.output_binary], link_deps, 'alink_thin', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all, postbuilds=postbuilds) elif self.type == 'shared_library': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all, postbuilds=postbuilds) elif self.type == 'loadable_module': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in module input filenames not supported (%s)" % link_dep) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'solink_module_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd( [self.output_binary], link_deps, 'solink_module', part_of_all, postbuilds=postbuilds) elif self.type == 'none': # Write a stamp line. self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all, postbuilds=postbuilds) else: print "WARNING: no output for", self.type, target # Add an alias for each target (if there are any outputs). # Installable target aliases are created below. if ((self.output and self.output != self.target) and (self.type not in self._INSTALLABLE_TARGETS)): self.WriteMakeRule([self.target], [self.output], comment='Add target alias', phony = True) if part_of_all: self.WriteMakeRule(['all'], [self.target], comment = 'Add target alias to "all" target.', phony = True) # Add special-case rules for our installable targets. # 1) They need to install to the build dir or "product" dir. # 2) They get shortcuts for building (e.g. "make chrome"). # 3) They are part of "make all". if (self.type in self._INSTALLABLE_TARGETS or self.is_standalone_static_library): if self.type == 'shared_library': file_desc = 'shared library' elif self.type == 'static_library': file_desc = 'static library' else: file_desc = 'executable' install_path = self._InstallableTargetInstallPath() installable_deps = [self.output] if (self.flavor == 'mac' and not 'product_dir' in spec and self.toolset == 'target'): # On mac, products are created in install_path immediately. assert install_path == self.output, '%s != %s' % ( install_path, self.output) # Point the target alias to the final binary output. self.WriteMakeRule([self.target], [install_path], comment='Add target alias', phony = True) if install_path != self.output: assert not self.is_mac_bundle # See comment a few lines above. self.WriteDoCmd([install_path], [self.output], 'copy', comment = 'Copy this to the %s output path.' % file_desc, part_of_all=part_of_all) installable_deps.append(install_path) if self.output != self.alias and self.alias != self.target: self.WriteMakeRule([self.alias], installable_deps, comment = 'Short alias for building this %s.' % file_desc, phony = True) if part_of_all: self.WriteMakeRule(['all'], [install_path], comment = 'Add %s to "all" target.' % file_desc, phony = True) def WriteList(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = '' if value_list: value_list = [quoter(prefix + l) for l in value_list] values = ' \\\n\t' + ' \\\n\t'.join(value_list) self.fp.write('%s :=%s\n\n' % (variable, values)) def WriteDoCmd(self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False): """Write a Makefile rule that uses do_cmd. This makes the outputs dependent on the command line that was run, as well as support the V= make command line flag. """ suffix = '' if postbuilds: assert ',' not in command suffix = ',,1' # Tell do_cmd to honor $POSTBUILDS self.WriteMakeRule(outputs, inputs, actions = ['$(call do_cmd,%s%s)' % (command, suffix)], comment = comment, command = command, force = True) # Add our outputs to the list of targets we read depfiles from. # all_deps is only used for deps file reading, and for deps files we replace # spaces with ? because escaping doesn't work with make's $(sort) and # other functions. outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs] self.WriteLn('all_deps += %s' % ' '.join(outputs)) def WriteMakeRule(self, outputs, inputs, actions=None, comment=None, order_only=False, force=False, phony=False, command=None): """Write a Makefile rule, with some extra tricks. outputs: a list of outputs for the rule (note: this is not directly supported by make; see comments below) inputs: a list of inputs for the rule actions: a list of shell commands to run for the rule comment: a comment to put in the Makefile above the rule (also useful for making this Python script's code self-documenting) order_only: if true, makes the dependency order-only force: if true, include FORCE_DO_CMD as an order-only dep phony: if true, the rule does not actually generate the named output, the output is just a name to run the rule command: (optional) command name to generate unambiguous labels """ outputs = map(QuoteSpaces, outputs) inputs = map(QuoteSpaces, inputs) if comment: self.WriteLn('# ' + comment) if phony: self.WriteLn('.PHONY: ' + ' '.join(outputs)) if actions: self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0]) force_append = ' FORCE_DO_CMD' if force else '' if order_only: # Order only rule: Just write a simple rule. # TODO(evanm): just make order_only a list of deps instead of this hack. self.WriteLn('%s: | %s%s' % (' '.join(outputs), ' '.join(inputs), force_append)) elif len(outputs) == 1: # Regular rule, one output: Just write a simple rule. self.WriteLn('%s: %s%s' % (outputs[0], ' '.join(inputs), force_append)) else: # Regular rule, more than one output: Multiple outputs are tricky in # make. We will write three rules: # - All outputs depend on an intermediate file. # - Make .INTERMEDIATE depend on the intermediate. # - The intermediate file depends on the inputs and executes the # actual command. # - The intermediate recipe will 'touch' the intermediate file. # - The multi-output rule will have an do-nothing recipe. intermediate = "%s.intermediate" % (command if command else self.target) self.WriteLn('%s: %s' % (' '.join(outputs), intermediate)) self.WriteLn('\t%s' % '@:'); self.WriteLn('%s: %s' % ('.INTERMEDIATE', intermediate)) self.WriteLn('%s: %s%s' % (intermediate, ' '.join(inputs), force_append)) actions.insert(0, '$(call do_cmd,touch)') if actions: for action in actions: self.WriteLn('\t%s' % action) self.WriteLn() def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps): """Write a set of LOCAL_XXX definitions for Android NDK. These variable definitions will be used by Android NDK but do nothing for non-Android applications. Arguments: module_name: Android NDK module name, which must be unique among all module names. all_sources: A list of source files (will be filtered by Compilable). link_deps: A list of link dependencies, which must be sorted in the order from dependencies to dependents. """ if self.type not in ('executable', 'shared_library', 'static_library'): return self.WriteLn('# Variable definitions for Android applications') self.WriteLn('include $(CLEAR_VARS)') self.WriteLn('LOCAL_MODULE := ' + module_name) self.WriteLn('LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) ' '$(DEFS_$(BUILDTYPE)) ' # LOCAL_CFLAGS is applied to both of C and C++. There is # no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C # sources. '$(CFLAGS_C_$(BUILDTYPE)) ' # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while # LOCAL_C_INCLUDES does not expect it. So put it in # LOCAL_CFLAGS. '$(INCS_$(BUILDTYPE))') # LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred. self.WriteLn('LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))') self.WriteLn('LOCAL_C_INCLUDES :=') self.WriteLn('LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)') # Detect the C++ extension. cpp_ext = {'.cc': 0, '.cpp': 0, '.cxx': 0} default_cpp_ext = '.cpp' for filename in all_sources: ext = os.path.splitext(filename)[1] if ext in cpp_ext: cpp_ext[ext] += 1 if cpp_ext[ext] > cpp_ext[default_cpp_ext]: default_cpp_ext = ext self.WriteLn('LOCAL_CPP_EXTENSION := ' + default_cpp_ext) self.WriteList(map(self.Absolutify, filter(Compilable, all_sources)), 'LOCAL_SRC_FILES') # Filter out those which do not match prefix and suffix and produce # the resulting list without prefix and suffix. def DepsToModules(deps, prefix, suffix): modules = [] for filepath in deps: filename = os.path.basename(filepath) if filename.startswith(prefix) and filename.endswith(suffix): modules.append(filename[len(prefix):-len(suffix)]) return modules # Retrieve the default value of 'SHARED_LIB_SUFFIX' params = {'flavor': 'linux'} default_variables = {} CalculateVariables(default_variables, params) self.WriteList( DepsToModules(link_deps, generator_default_variables['SHARED_LIB_PREFIX'], default_variables['SHARED_LIB_SUFFIX']), 'LOCAL_SHARED_LIBRARIES') self.WriteList( DepsToModules(link_deps, generator_default_variables['STATIC_LIB_PREFIX'], generator_default_variables['STATIC_LIB_SUFFIX']), 'LOCAL_STATIC_LIBRARIES') if self.type == 'executable': self.WriteLn('include $(BUILD_EXECUTABLE)') elif self.type == 'shared_library': self.WriteLn('include $(BUILD_SHARED_LIBRARY)') elif self.type == 'static_library': self.WriteLn('include $(BUILD_STATIC_LIBRARY)') self.WriteLn() def WriteLn(self, text=''): self.fp.write(text + '\n') def GetSortedXcodeEnv(self, additional_settings=None): return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, "$(abs_builddir)", os.path.join("$(abs_srcdir)", self.path), "$(BUILDTYPE)", additional_settings) def GetSortedXcodePostbuildEnv(self): # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( 'CHROMIUM_STRIP_SAVE_FILE', '') # Even if strip_save_file is empty, explicitly write it. Else a postbuild # might pick up an export from an earlier target. return self.GetSortedXcodeEnv( additional_settings={'CHROMIUM_STRIP_SAVE_FILE': strip_save_file}) def WriteSortedXcodeEnv(self, target, env): for k, v in env: # For # foo := a\ b # the escaped space does the right thing. For # export foo := a\ b # it does not -- the backslash is written to the env as literal character. # So don't escape spaces in |env[k]|. self.WriteLn('%s: export %s := %s' % (QuoteSpaces(target), k, v)) def Objectify(self, path): """Convert a path to its output directory form.""" if '$(' in path: path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/' % self.toolset) if not '$(obj)' in path: path = '$(obj).%s/$(TARGET)/%s' % (self.toolset, path) return path def Pchify(self, path, lang): """Convert a prefix header path to its output directory form.""" path = self.Absolutify(path) if '$(' in path: path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' % (self.toolset, lang)) return path return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path) def Absolutify(self, path): """Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.""" if '$(' in path: # Don't call normpath in this case, as it might collapse the # path too aggressively if it features '..'. However it's still # important to strip trailing slashes. return path.rstrip('/') return os.path.normpath(os.path.join(self.path, path)) def ExpandInputRoot(self, template, expansion, dirname): if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template: return template path = template % { 'INPUT_ROOT': expansion, 'INPUT_DIRNAME': dirname, } return path def _InstallableTargetInstallPath(self): """Returns the location of the final output for an installable target.""" # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files # rely on this. Emulate this behavior for mac. # XXX(TooTallNate): disabling this code since we don't want this behavior... #if (self.type == 'shared_library' and # (self.flavor != 'mac' or self.toolset != 'target')): # # Install all shared libs into a common directory (per toolset) for # # convenient access with LD_LIBRARY_PATH. # return '$(builddir)/lib.%s/%s' % (self.toolset, self.alias) return '$(builddir)/' + self.alias def WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files): """Write the target to regenerate the Makefile.""" options = params['options'] build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir) for filename in params['build_files_arg']] gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'], options.toplevel_dir) if not gyp_binary.startswith(os.sep): gyp_binary = os.path.join('.', gyp_binary) root_makefile.write( "quiet_cmd_regen_makefile = ACTION Regenerating $@\n" "cmd_regen_makefile = cd $(srcdir); %(cmd)s\n" "%(makefile_name)s: %(deps)s\n" "\t$(call do_cmd,regen_makefile)\n\n" % { 'makefile_name': makefile_name, 'deps': ' '.join(map(Sourceify, build_files)), 'cmd': gyp.common.EncodePOSIXShellList( [gyp_binary, '-fmake'] + gyp.RegenerateFlags(options) + build_files_args)}) def PerformBuild(data, configurations, params): options = params['options'] for config in configurations: arguments = ['make'] if options.toplevel_dir and options.toplevel_dir != '.': arguments += '-C', options.toplevel_dir arguments.append('BUILDTYPE=' + config) print 'Building [%s]: %s' % (config, arguments) subprocess.check_call(arguments) def GenerateOutput(target_list, target_dicts, data, params): options = params['options'] flavor = gyp.common.GetFlavor(params) generator_flags = params.get('generator_flags', {}) builddir_name = generator_flags.get('output_dir', 'out') android_ndk_version = generator_flags.get('android_ndk_version', None) default_target = generator_flags.get('default_target', 'all') def CalculateMakefilePath(build_file, base_name): """Determine where to write a Makefile for a given gyp file.""" # Paths in gyp files are relative to the .gyp file, but we want # paths relative to the source root for the master makefile. Grab # the path of the .gyp file as the base to relativize against. # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp". base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.depth) # We write the file in the base_path directory. output_file = os.path.join(options.depth, base_path, base_name) if options.generator_output: output_file = os.path.join( options.depth, options.generator_output, base_path, base_name) base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.toplevel_dir) return base_path, output_file # TODO: search for the first non-'Default' target. This can go # away when we add verification that all targets have the # necessary configurations. default_configuration = None toolsets = set([target_dicts[target]['toolset'] for target in target_list]) for target in target_list: spec = target_dicts[target] if spec['default_configuration'] != 'Default': default_configuration = spec['default_configuration'] break if not default_configuration: default_configuration = 'Default' srcdir = '.' makefile_name = 'Makefile' + options.suffix makefile_path = os.path.join(options.toplevel_dir, makefile_name) if options.generator_output: global srcdir_prefix makefile_path = os.path.join( options.toplevel_dir, options.generator_output, makefile_name) srcdir = gyp.common.RelativePath(srcdir, options.generator_output) srcdir_prefix = '$(srcdir)/' flock_command= 'flock' copy_archive_arguments = '-af' header_params = { 'default_target': default_target, 'builddir': builddir_name, 'default_configuration': default_configuration, 'flock': flock_command, 'flock_index': 1, 'link_commands': LINK_COMMANDS_LINUX, 'extra_commands': '', 'srcdir': srcdir, 'copy_archive_args': copy_archive_arguments, } if flavor == 'mac': flock_command = './gyp-mac-tool flock' header_params.update({ 'flock': flock_command, 'flock_index': 2, 'link_commands': LINK_COMMANDS_MAC, 'extra_commands': SHARED_HEADER_MAC_COMMANDS, }) elif flavor == 'android': header_params.update({ 'link_commands': LINK_COMMANDS_ANDROID, }) elif flavor == 'solaris': header_params.update({ 'flock': './gyp-flock-tool flock', 'flock_index': 2, }) elif flavor == 'freebsd': # Note: OpenBSD has sysutils/flock. lockf seems to be FreeBSD specific. header_params.update({ 'flock': 'lockf', }) elif flavor == 'openbsd': copy_archive_arguments = '-pPRf' header_params.update({ 'copy_archive_args': copy_archive_arguments, }) elif flavor == 'aix': copy_archive_arguments = '-pPRf' header_params.update({ 'copy_archive_args': copy_archive_arguments, 'link_commands': LINK_COMMANDS_AIX, 'flock': './gyp-flock-tool flock', 'flock_index': 2, }) header_params.update({ 'CC.target': GetEnvironFallback(('CC_target', 'CC'), '$(CC)'), 'AR.target': GetEnvironFallback(('AR_target', 'AR'), '$(AR)'), 'CXX.target': GetEnvironFallback(('CXX_target', 'CXX'), '$(CXX)'), 'LINK.target': GetEnvironFallback(('LINK_target', 'LINK'), '$(LINK)'), 'CC.host': GetEnvironFallback(('CC_host', 'CC'), 'gcc'), 'AR.host': GetEnvironFallback(('AR_host', 'AR'), 'ar'), 'CXX.host': GetEnvironFallback(('CXX_host', 'CXX'), 'g++'), 'LINK.host': GetEnvironFallback(('LINK_host', 'LINK'), '$(CXX.host)'), }) build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings_array = data[build_file].get('make_global_settings', []) wrappers = {} for key, value in make_global_settings_array: if key.endswith('_wrapper'): wrappers[key[:-len('_wrapper')]] = '$(abspath %s)' % value make_global_settings = '' for key, value in make_global_settings_array: if re.match('.*_wrapper', key): continue if value[0] != '$': value = '$(abspath %s)' % value wrapper = wrappers.get(key) if wrapper: value = '%s %s' % (wrapper, value) del wrappers[key] if key in ('CC', 'CC.host', 'CXX', 'CXX.host'): make_global_settings += ( 'ifneq (,$(filter $(origin %s), undefined default))\n' % key) # Let gyp-time envvars win over global settings. env_key = key.replace('.', '_') # CC.host -> CC_host if env_key in os.environ: value = os.environ[env_key] make_global_settings += ' %s = %s\n' % (key, value) make_global_settings += 'endif\n' else: make_global_settings += '%s ?= %s\n' % (key, value) # TODO(ukai): define cmd when only wrapper is specified in # make_global_settings. header_params['make_global_settings'] = make_global_settings gyp.common.EnsureDirExists(makefile_path) root_makefile = open(makefile_path, 'w') root_makefile.write(SHARED_HEADER % header_params) # Currently any versions have the same effect, but in future the behavior # could be different. if android_ndk_version: root_makefile.write( '# Define LOCAL_PATH for build of Android applications.\n' 'LOCAL_PATH := $(call my-dir)\n' '\n') for toolset in toolsets: root_makefile.write('TOOLSET := %s\n' % toolset) WriteRootHeaderSuffixRules(root_makefile) # Put build-time support tools next to the root Makefile. dest_path = os.path.dirname(makefile_path) gyp.common.CopyTool(flavor, dest_path) # Find the list of targets that derive from the gyp file(s) being built. needed_targets = set() for build_file in params['build_files']: for target in gyp.common.AllTargets(target_list, target_dicts, build_file): needed_targets.add(target) build_files = set() include_list = set() for qualified_target in target_list: build_file, target, toolset = gyp.common.ParseQualifiedTarget( qualified_target) this_make_global_settings = data[build_file].get('make_global_settings', []) assert make_global_settings_array == this_make_global_settings, ( "make_global_settings needs to be the same for all targets. %s vs. %s" % (this_make_global_settings, make_global_settings)) build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir)) included_files = data[build_file]['included_files'] for included_file in included_files: # The included_files entries are relative to the dir of the build file # that included them, so we have to undo that and then make them relative # to the root dir. relative_include_file = gyp.common.RelativePath( gyp.common.UnrelativePath(included_file, build_file), options.toplevel_dir) abs_include_file = os.path.abspath(relative_include_file) # If the include file is from the ~/.gyp dir, we should use absolute path # so that relocating the src dir doesn't break the path. if (params['home_dot_gyp'] and abs_include_file.startswith(params['home_dot_gyp'])): build_files.add(abs_include_file) else: build_files.add(relative_include_file) base_path, output_file = CalculateMakefilePath(build_file, target + '.' + toolset + options.suffix + '.mk') spec = target_dicts[qualified_target] configs = spec['configurations'] if flavor == 'mac': gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) writer = MakefileWriter(generator_flags, flavor) writer.Write(qualified_target, base_path, output_file, spec, configs, part_of_all=qualified_target in needed_targets) # Our root_makefile lives at the source root. Compute the relative path # from there to the output_file for including. mkfile_rel_path = gyp.common.RelativePath(output_file, os.path.dirname(makefile_path)) include_list.add(mkfile_rel_path) # Write out per-gyp (sub-project) Makefiles. depth_rel_path = gyp.common.RelativePath(options.depth, os.getcwd()) for build_file in build_files: # The paths in build_files were relativized above, so undo that before # testing against the non-relativized items in target_list and before # calculating the Makefile path. build_file = os.path.join(depth_rel_path, build_file) gyp_targets = [target_dicts[target]['target_name'] for target in target_list if target.startswith(build_file) and target in needed_targets] # Only generate Makefiles for gyp files with targets. if not gyp_targets: continue base_path, output_file = CalculateMakefilePath(build_file, os.path.splitext(os.path.basename(build_file))[0] + '.Makefile') makefile_rel_path = gyp.common.RelativePath(os.path.dirname(makefile_path), os.path.dirname(output_file)) writer.WriteSubMake(output_file, makefile_rel_path, gyp_targets, builddir_name) # Write out the sorted list of includes. root_makefile.write('\n') for include_file in sorted(include_list): # We wrap each .mk include in an if statement so users can tell make to # not load a file by setting NO_LOAD. The below make code says, only # load the .mk file if the .mk filename doesn't start with a token in # NO_LOAD. root_makefile.write( "ifeq ($(strip $(foreach prefix,$(NO_LOAD),\\\n" " $(findstring $(join ^,$(prefix)),\\\n" " $(join ^," + include_file + ")))),)\n") root_makefile.write(" include " + include_file + "\n") root_makefile.write("endif\n") root_makefile.write('\n') if (not generator_flags.get('standalone') and generator_flags.get('auto_regeneration', True)): WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files) root_makefile.write(SHARED_FOOTER) root_makefile.close()
endlessm/chromium-browser
refs/heads/master
components/module_installer/android/module_desc_java.py
1
#!/usr/bin/env python # # Copyright 2019 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. """Writes Java module descriptor to srcjar file.""" import argparse import os import sys import zipfile sys.path.append( os.path.join( os.path.dirname(__file__), "..", "..", "..", "build", "android", "gyp")) from util import build_utils _TEMPLATE = """\ // This file is autogenerated by // components/module_installer/android/module_desc_java.py // Please do not change its content. package org.chromium.components.module_installer.builder; import org.chromium.base.annotations.UsedByReflection; @UsedByReflection("Module.java") public class ModuleDescriptor_{MODULE} implements ModuleDescriptor {{ private static final String[] LIBRARIES = {{{LIBRARIES}}}; private static final String[] PAKS = {{{PAKS}}}; @Override public String[] getLibraries() {{ return LIBRARIES; }} @Override public String[] getPaks() {{ return PAKS; }} @Override public boolean getLoadNativeOnGetImpl() {{ return {LOAD_NATIVE_ON_GET_IMPL}; }} }} """ def main(): parser = argparse.ArgumentParser() parser.add_argument('--module', required=True, help='The module name.') parser.add_argument( '--libraries', required=True, help='GN list of native library paths.') parser.add_argument('--paks', help='GN list of PAK file paths') parser.add_argument( '--output', required=True, help='Path to the generated srcjar file.') parser.add_argument('--load-native-on-get-impl', action='store_true', default=False, help='Load module automatically on calling Module.getImpl().') options = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:])) options.libraries = build_utils.ParseGnList(options.libraries) options.paks = build_utils.ParseGnList(options.paks) libraries = [] for path in options.libraries: path = path.strip() filename = os.path.split(path)[1] assert filename.startswith('lib') assert filename.endswith('.so') # Remove lib prefix and .so suffix. libraries += [filename[3:-3]] paks = options.paks if options.paks else [] format_dict = { 'MODULE': options.module, 'LIBRARIES': ','.join(['"%s"' % l for l in libraries]), 'PAKS': ','.join(['"%s"' % os.path.basename(p) for p in paks]), 'LOAD_NATIVE_ON_GET_IMPL': ( 'true' if options.load_native_on_get_impl else 'false'), } with build_utils.AtomicOutput(options.output) as f: with zipfile.ZipFile(f.name, 'w') as srcjar_file: build_utils.AddToZipHermetic( srcjar_file, 'org/chromium/components/module_installer/builder/' 'ModuleDescriptor_%s.java' % options.module, data=_TEMPLATE.format(**format_dict)) if __name__ == '__main__': sys.exit(main())
fake-name/ReadableWebProxy
refs/heads/master
WebMirror/management/rss_parser_funcs/feed_parse_extractRosietranslatesHomeBlog.py
1
def extractRosietranslatesHomeBlog(item): ''' Parser for 'rosietranslates.home.blog' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('Secret Organization', 'Secret Organization', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
huzq/scikit-learn
refs/heads/master
examples/miscellaneous/plot_kernel_ridge_regression.py
17
""" ============================================= Comparison of kernel ridge regression and SVR ============================================= Both kernel ridge regression (KRR) and SVR learn a non-linear function by employing the kernel trick, i.e., they learn a linear function in the space induced by the respective kernel which corresponds to a non-linear function in the original space. They differ in the loss functions (ridge versus epsilon-insensitive loss). In contrast to SVR, fitting a KRR can be done in closed-form and is typically faster for medium-sized datasets. On the other hand, the learned model is non-sparse and thus slower than SVR at prediction-time. This example illustrates both methods on an artificial dataset, which consists of a sinusoidal target function and strong noise added to every fifth datapoint. The first figure compares the learned model of KRR and SVR when both complexity/regularization and bandwidth of the RBF kernel are optimized using grid-search. The learned functions are very similar; however, fitting KRR is approx. seven times faster than fitting SVR (both with grid-search). However, prediction of 100000 target values is more than tree times faster with SVR since it has learned a sparse model using only approx. 1/3 of the 100 training datapoints as support vectors. The next figure compares the time for fitting and prediction of KRR and SVR for different sizes of the training set. Fitting KRR is faster than SVR for medium- sized training sets (less than 1000 samples); however, for larger training sets SVR scales better. With regard to prediction time, SVR is faster than KRR for all sizes of the training set because of the learned sparse solution. Note that the degree of sparsity and thus the prediction time depends on the parameters epsilon and C of the SVR. """ # Authors: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # License: BSD 3 clause import time import numpy as np from sklearn.svm import SVR from sklearn.model_selection import GridSearchCV from sklearn.model_selection import learning_curve from sklearn.kernel_ridge import KernelRidge import matplotlib.pyplot as plt rng = np.random.RandomState(0) # ############################################################################# # Generate sample data X = 5 * rng.rand(10000, 1) y = np.sin(X).ravel() # Add noise to targets y[::5] += 3 * (0.5 - rng.rand(X.shape[0] // 5)) X_plot = np.linspace(0, 5, 100000)[:, None] # ############################################################################# # Fit regression model train_size = 100 svr = GridSearchCV(SVR(kernel='rbf', gamma=0.1), param_grid={"C": [1e0, 1e1, 1e2, 1e3], "gamma": np.logspace(-2, 2, 5)}) kr = GridSearchCV(KernelRidge(kernel='rbf', gamma=0.1), param_grid={"alpha": [1e0, 0.1, 1e-2, 1e-3], "gamma": np.logspace(-2, 2, 5)}) t0 = time.time() svr.fit(X[:train_size], y[:train_size]) svr_fit = time.time() - t0 print("SVR complexity and bandwidth selected and model fitted in %.3f s" % svr_fit) t0 = time.time() kr.fit(X[:train_size], y[:train_size]) kr_fit = time.time() - t0 print("KRR complexity and bandwidth selected and model fitted in %.3f s" % kr_fit) sv_ratio = svr.best_estimator_.support_.shape[0] / train_size print("Support vector ratio: %.3f" % sv_ratio) t0 = time.time() y_svr = svr.predict(X_plot) svr_predict = time.time() - t0 print("SVR prediction for %d inputs in %.3f s" % (X_plot.shape[0], svr_predict)) t0 = time.time() y_kr = kr.predict(X_plot) kr_predict = time.time() - t0 print("KRR prediction for %d inputs in %.3f s" % (X_plot.shape[0], kr_predict)) # ############################################################################# # Look at the results sv_ind = svr.best_estimator_.support_ plt.scatter(X[sv_ind], y[sv_ind], c='r', s=50, label='SVR support vectors', zorder=2, edgecolors=(0, 0, 0)) plt.scatter(X[:100], y[:100], c='k', label='data', zorder=1, edgecolors=(0, 0, 0)) plt.plot(X_plot, y_svr, c='r', label='SVR (fit: %.3fs, predict: %.3fs)' % (svr_fit, svr_predict)) plt.plot(X_plot, y_kr, c='g', label='KRR (fit: %.3fs, predict: %.3fs)' % (kr_fit, kr_predict)) plt.xlabel('data') plt.ylabel('target') plt.title('SVR versus Kernel Ridge') plt.legend() # Visualize training and prediction time plt.figure() # Generate sample data X = 5 * rng.rand(10000, 1) y = np.sin(X).ravel() y[::5] += 3 * (0.5 - rng.rand(X.shape[0] // 5)) sizes = np.logspace(1, 4, 7).astype(int) for name, estimator in {"KRR": KernelRidge(kernel='rbf', alpha=0.1, gamma=10), "SVR": SVR(kernel='rbf', C=1e1, gamma=10)}.items(): train_time = [] test_time = [] for train_test_size in sizes: t0 = time.time() estimator.fit(X[:train_test_size], y[:train_test_size]) train_time.append(time.time() - t0) t0 = time.time() estimator.predict(X_plot[:1000]) test_time.append(time.time() - t0) plt.plot(sizes, train_time, 'o-', color="r" if name == "SVR" else "g", label="%s (train)" % name) plt.plot(sizes, test_time, 'o--', color="r" if name == "SVR" else "g", label="%s (test)" % name) plt.xscale("log") plt.yscale("log") plt.xlabel("Train size") plt.ylabel("Time (seconds)") plt.title('Execution Time') plt.legend(loc="best") # Visualize learning curves plt.figure() svr = SVR(kernel='rbf', C=1e1, gamma=0.1) kr = KernelRidge(kernel='rbf', alpha=0.1, gamma=0.1) train_sizes, train_scores_svr, test_scores_svr = \ learning_curve(svr, X[:100], y[:100], train_sizes=np.linspace(0.1, 1, 10), scoring="neg_mean_squared_error", cv=10) train_sizes_abs, train_scores_kr, test_scores_kr = \ learning_curve(kr, X[:100], y[:100], train_sizes=np.linspace(0.1, 1, 10), scoring="neg_mean_squared_error", cv=10) plt.plot(train_sizes, -test_scores_svr.mean(1), 'o-', color="r", label="SVR") plt.plot(train_sizes, -test_scores_kr.mean(1), 'o-', color="g", label="KRR") plt.xlabel("Train size") plt.ylabel("Mean Squared Error") plt.title('Learning curves') plt.legend(loc="best") plt.show()
nsgundy/ACE3
refs/heads/master
tools/search_privates.py
5
#!/usr/bin/env python3 import fnmatch import os import re import ntpath import sys import argparse def get_private_declare(content): priv_declared = [] srch = re.compile('private.*') priv_srch_declared = srch.findall(content) priv_srch_declared = sorted(set(priv_srch_declared)) priv_dec_str = ''.join(priv_srch_declared) srch = re.compile('(?<![_a-zA-Z0-9])(_[a-zA-Z]*?)[ ,\}\]\)";]') priv_split = srch.findall(priv_dec_str) priv_split = sorted(set(priv_split)) priv_declared += priv_split; srch = re.compile('params \[.*\]|PARAMS_[0-9].*|EXPLODE_[0-9]_PVT.*|DEFAULT_PARAM.*|KEY_PARAM.*|IGNORE_PRIVATE_WARNING.*') priv_srch_declared = srch.findall(content) priv_srch_declared = sorted(set(priv_srch_declared)) priv_dec_str = ''.join(priv_srch_declared) srch = re.compile('(?<![_a-zA-Z0-9])(_[a-zA-Z]*?)[ ,\}\]\)";]') priv_split = srch.findall(priv_dec_str) priv_split = sorted(set(priv_split)) priv_declared += priv_split; return priv_declared def check_privates(filepath): bad_count_file = 0 def pushClosing(t): closingStack.append(closing.expr) closing << Literal( closingFor[t[0]] ) def popClosing(): closing << closingStack.pop() with open(filepath, 'r') as file: content = file.read() priv_use = [] priv_use = [] # Regex search privates srch = re.compile('(?<![_a-zA-Z0-9])(_[a-zA-Z]*?)[ ,\^\-\+\/\*\%\}\]\)";]') priv_use = srch.findall(content) priv_use = sorted(set(priv_use)) # Private declaration search priv_declared = get_private_declare(content) if '_this' in priv_declared: priv_declared.remove('_this') if '_this' in priv_use: priv_use.remove('_this') if '_x' in priv_declared: priv_declared.remove('_x') if '_x' in priv_use: priv_use.remove('_x') if '_forEachIndex' in priv_declared: priv_declared.remove('_forEachIndex') if '_forEachIndex' in priv_use: priv_use.remove('_forEachIndex') if '_foreachIndex' in priv_declared: priv_declared.remove('_foreachIndex') if '_foreachIndex' in priv_use: priv_use.remove('_foreachIndex') if '_foreachindex' in priv_declared: priv_declared.remove('_foreachindex') if '_foreachindex' in priv_use: priv_use.remove('_foreachindex') missing = [] for s in priv_use: if s.lower() not in map(str.lower,priv_declared): if s.lower() not in map(str.lower,missing): missing.append(s) if len(missing) > 0: print (filepath) private_output = 'private['; first = True for bad_priv in missing: if first: first = False private_output = private_output + '"' + bad_priv else: private_output = private_output + '", "' + bad_priv private_output = private_output + '"];'; print (private_output) for bad_priv in missing: print ('\t' + bad_priv) bad_count_file = bad_count_file + 1 return bad_count_file def main(): print("#########################") print("# Search your Privates #") print("#########################") sqf_list = [] bad_count = 0 parser = argparse.ArgumentParser() parser.add_argument('-m','--module', help='only search specified module addon folder', required=False, default=".") args = parser.parse_args() for root, dirnames, filenames in os.walk('../addons' + '/' + args.module): for filename in fnmatch.filter(filenames, '*.sqf'): sqf_list.append(os.path.join(root, filename)) for filename in sqf_list: bad_count = bad_count + check_privates(filename) print ("Bad Count {0}".format(bad_count)) if __name__ == "__main__": main()
cbeloni/pychronesapp
refs/heads/master
backend/appengine/convention.py
34
import sys import os # Put lib on path, once Google App Engine does not allow doing it directly sys.path.append(os.path.join(os.path.dirname(__file__), "lib")) sys.path.append(os.path.join(os.path.dirname(__file__), "apps")) import settings from tekton.gae import middleware import webapp2 from webapp2_extras import i18n i18n.default_config['default_locale'] = settings.DEFAULT_LOCALE i18n.default_config['default_timezone'] = settings.DEFAULT_TIMEZONE class BaseHandler(webapp2.RequestHandler): def get(self): self.make_convention() def post(self): self.make_convention() def make_convention(self): middleware.execute(settings.MIDDLEWARE_LIST, self) app = webapp2.WSGIApplication([("/.*", BaseHandler)], debug=False)
manashmndl/scikit-learn
refs/heads/master
sklearn/utils/arpack.py
265
""" This contains a copy of the future version of scipy.sparse.linalg.eigen.arpack.eigsh It's an upgraded wrapper of the ARPACK library which allows the use of shift-invert mode for symmetric matrices. Find a few eigenvectors and eigenvalues of a matrix. Uses ARPACK: http://www.caam.rice.edu/software/ARPACK/ """ # Wrapper implementation notes # # ARPACK Entry Points # ------------------- # The entry points to ARPACK are # - (s,d)seupd : single and double precision symmetric matrix # - (s,d,c,z)neupd: single,double,complex,double complex general matrix # This wrapper puts the *neupd (general matrix) interfaces in eigs() # and the *seupd (symmetric matrix) in eigsh(). # There is no Hermetian complex/double complex interface. # To find eigenvalues of a Hermetian matrix you # must use eigs() and not eigsh() # It might be desirable to handle the Hermetian case differently # and, for example, return real eigenvalues. # Number of eigenvalues returned and complex eigenvalues # ------------------------------------------------------ # The ARPACK nonsymmetric real and double interface (s,d)naupd return # eigenvalues and eigenvectors in real (float,double) arrays. # Since the eigenvalues and eigenvectors are, in general, complex # ARPACK puts the real and imaginary parts in consecutive entries # in real-valued arrays. This wrapper puts the real entries # into complex data types and attempts to return the requested eigenvalues # and eigenvectors. # Solver modes # ------------ # ARPACK and handle shifted and shift-inverse computations # for eigenvalues by providing a shift (sigma) and a solver. __docformat__ = "restructuredtext en" __all__ = ['eigs', 'eigsh', 'svds', 'ArpackError', 'ArpackNoConvergence'] import warnings from scipy.sparse.linalg.eigen.arpack import _arpack import numpy as np from scipy.sparse.linalg.interface import aslinearoperator, LinearOperator from scipy.sparse import identity, isspmatrix, isspmatrix_csr from scipy.linalg import lu_factor, lu_solve from scipy.sparse.sputils import isdense from scipy.sparse.linalg import gmres, splu import scipy from distutils.version import LooseVersion _type_conv = {'f': 's', 'd': 'd', 'F': 'c', 'D': 'z'} _ndigits = {'f': 5, 'd': 12, 'F': 5, 'D': 12} DNAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found. IPARAM(5) " "returns the number of wanted converged Ritz values.", 2: "No longer an informational error. Deprecated starting " "with release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the " "Implicitly restarted Arnoldi iteration. One possibility " "is to increase the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: " WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation;", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible.", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated." } SNAUPD_ERRORS = DNAUPD_ERRORS ZNAUPD_ERRORS = DNAUPD_ERRORS.copy() ZNAUPD_ERRORS[-10] = "IPARAM(7) must be 1,2,3." CNAUPD_ERRORS = ZNAUPD_ERRORS DSAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found.", 2: "No longer an informational error. Deprecated starting with " "release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the Implicitly " "restarted Arnoldi iteration. One possibility is to increase " "the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from trid. eigenvalue calculation; " "Informational error from LAPACK routine dsteqr .", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible. ", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated.", } SSAUPD_ERRORS = DSAUPD_ERRORS DNEUPD_ERRORS = { 0: "Normal exit.", 1: "The Schur form computed by LAPACK routine dlahqr " "could not be reordered by LAPACK routine dtrsen. " "Re-enter subroutine dneupd with IPARAM(5)NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least NCV " "columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from calculation of a real Schur form. " "Informational error from LAPACK routine dlahqr .", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine dtrevc.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "DNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "DNEUPD got a different count of the number of converged " "Ritz values than DNAUPD got. This indicates the user " "probably made an error in passing data from DNAUPD to " "DNEUPD or that the data was modified before entering " "DNEUPD", } SNEUPD_ERRORS = DNEUPD_ERRORS.copy() SNEUPD_ERRORS[1] = ("The Schur form computed by LAPACK routine slahqr " "could not be reordered by LAPACK routine strsen . " "Re-enter subroutine dneupd with IPARAM(5)=NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.") SNEUPD_ERRORS[-14] = ("SNAUPD did not find any eigenvalues to sufficient " "accuracy.") SNEUPD_ERRORS[-15] = ("SNEUPD got a different count of the number of " "converged Ritz values than SNAUPD got. This indicates " "the user probably made an error in passing data from " "SNAUPD to SNEUPD or that the data was modified before " "entering SNEUPD") ZNEUPD_ERRORS = {0: "Normal exit.", 1: "The Schur form computed by LAPACK routine csheqr " "could not be reordered by LAPACK routine ztrsen. " "Re-enter subroutine zneupd with IPARAM(5)=NCV and " "increase the size of the array D to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 1 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation. " "This should never happened.", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine ztrevc.", -10: "IPARAM(7) must be 1,2,3", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "ZNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "ZNEUPD got a different count of the number of " "converged Ritz values than ZNAUPD got. This " "indicates the user probably made an error in passing " "data from ZNAUPD to ZNEUPD or that the data was " "modified before entering ZNEUPD"} CNEUPD_ERRORS = ZNEUPD_ERRORS.copy() CNEUPD_ERRORS[-14] = ("CNAUPD did not find any eigenvalues to sufficient " "accuracy.") CNEUPD_ERRORS[-15] = ("CNEUPD got a different count of the number of " "converged Ritz values than CNAUPD got. This indicates " "the user probably made an error in passing data from " "CNAUPD to CNEUPD or that the data was modified before " "entering CNEUPD") DSEUPD_ERRORS = { 0: "Normal exit.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: ("Error return from trid. eigenvalue calculation; " "Information error from LAPACK routine dsteqr."), -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "NEV and WHICH = 'BE' are incompatible.", -14: "DSAUPD did not find any eigenvalues to sufficient accuracy.", -15: "HOWMNY must be one of 'A' or 'S' if RVEC = .true.", -16: "HOWMNY = 'S' not yet implemented", -17: ("DSEUPD got a different count of the number of converged " "Ritz values than DSAUPD got. This indicates the user " "probably made an error in passing data from DSAUPD to " "DSEUPD or that the data was modified before entering " "DSEUPD.") } SSEUPD_ERRORS = DSEUPD_ERRORS.copy() SSEUPD_ERRORS[-14] = ("SSAUPD did not find any eigenvalues " "to sufficient accuracy.") SSEUPD_ERRORS[-17] = ("SSEUPD got a different count of the number of " "converged " "Ritz values than SSAUPD got. This indicates the user " "probably made an error in passing data from SSAUPD to " "SSEUPD or that the data was modified before entering " "SSEUPD.") _SAUPD_ERRORS = {'d': DSAUPD_ERRORS, 's': SSAUPD_ERRORS} _NAUPD_ERRORS = {'d': DNAUPD_ERRORS, 's': SNAUPD_ERRORS, 'z': ZNAUPD_ERRORS, 'c': CNAUPD_ERRORS} _SEUPD_ERRORS = {'d': DSEUPD_ERRORS, 's': SSEUPD_ERRORS} _NEUPD_ERRORS = {'d': DNEUPD_ERRORS, 's': SNEUPD_ERRORS, 'z': ZNEUPD_ERRORS, 'c': CNEUPD_ERRORS} # accepted values of parameter WHICH in _SEUPD _SEUPD_WHICH = ['LM', 'SM', 'LA', 'SA', 'BE'] # accepted values of parameter WHICH in _NAUPD _NEUPD_WHICH = ['LM', 'SM', 'LR', 'SR', 'LI', 'SI'] class ArpackError(RuntimeError): """ ARPACK error """ def __init__(self, info, infodict=_NAUPD_ERRORS): msg = infodict.get(info, "Unknown error") RuntimeError.__init__(self, "ARPACK error %d: %s" % (info, msg)) class ArpackNoConvergence(ArpackError): """ ARPACK iteration did not converge Attributes ---------- eigenvalues : ndarray Partial result. Converged eigenvalues. eigenvectors : ndarray Partial result. Converged eigenvectors. """ def __init__(self, msg, eigenvalues, eigenvectors): ArpackError.__init__(self, -1, {-1: msg}) self.eigenvalues = eigenvalues self.eigenvectors = eigenvectors class _ArpackParams(object): def __init__(self, n, k, tp, mode=1, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): if k <= 0: raise ValueError("k must be positive, k=%d" % k) if maxiter is None: maxiter = n * 10 if maxiter <= 0: raise ValueError("maxiter must be positive, maxiter=%d" % maxiter) if tp not in 'fdFD': raise ValueError("matrix type must be 'f', 'd', 'F', or 'D'") if v0 is not None: # ARPACK overwrites its initial resid, make a copy self.resid = np.array(v0, copy=True) info = 1 else: self.resid = np.zeros(n, tp) info = 0 if sigma is None: #sigma not used self.sigma = 0 else: self.sigma = sigma if ncv is None: ncv = 2 * k + 1 ncv = min(ncv, n) self.v = np.zeros((n, ncv), tp) # holds Ritz vectors self.iparam = np.zeros(11, "int") # set solver mode and parameters ishfts = 1 self.mode = mode self.iparam[0] = ishfts self.iparam[2] = maxiter self.iparam[3] = 1 self.iparam[6] = mode self.n = n self.tol = tol self.k = k self.maxiter = maxiter self.ncv = ncv self.which = which self.tp = tp self.info = info self.converged = False self.ido = 0 def _raise_no_convergence(self): msg = "No convergence (%d iterations, %d/%d eigenvectors converged)" k_ok = self.iparam[4] num_iter = self.iparam[2] try: ev, vec = self.extract(True) except ArpackError as err: msg = "%s [%s]" % (msg, err) ev = np.zeros((0,)) vec = np.zeros((self.n, 0)) k_ok = 0 raise ArpackNoConvergence(msg % (num_iter, k_ok, self.k), ev, vec) class _SymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x : # A - symmetric # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the general eigenvalue problem: # A*x = lambda*M*x # A - symmetric # M - symmetric positive definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # # mode = 4: # Solve the general eigenvalue problem in Buckling mode: # A*x = lambda*AG*x # A - symmetric positive semi-definite # AG - symmetric indefinite # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = left multiplication by [A-sigma*AG]^-1 # # mode = 5: # Solve the general eigenvalue problem in Cayley-transformed mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode == 3: if matvec is not None: raise ValueError("matvec must not be specified for mode=3") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=3") if M_matvec is None: self.OP = Minv_matvec self.OPa = Minv_matvec self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(M_matvec(x)) self.OPa = Minv_matvec self.B = M_matvec self.bmat = 'G' elif mode == 4: if matvec is None: raise ValueError("matvec must be specified for mode=4") if M_matvec is not None: raise ValueError("M_matvec must not be specified for mode=4") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=4") self.OPa = Minv_matvec self.OP = lambda x: self.OPa(matvec(x)) self.B = matvec self.bmat = 'G' elif mode == 5: if matvec is None: raise ValueError("matvec must be specified for mode=5") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=5") self.OPa = Minv_matvec self.A_matvec = matvec if M_matvec is None: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * x) self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * M_matvec(x)) self.B = M_matvec self.bmat = 'G' else: raise ValueError("mode=%i not implemented" % mode) if which not in _SEUPD_WHICH: raise ValueError("which must be one of %s" % ' '.join(_SEUPD_WHICH)) if k >= n: raise ValueError("k must be less than rank(A), k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k: raise ValueError("ncv must be k<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(self.ncv * (self.ncv + 8), self.tp) ltr = _type_conv[self.tp] if ltr not in ["s", "d"]: raise ValueError("Input matrix is not real-valued.") self._arpack_solver = _arpack.__dict__[ltr + 'saupd'] self._arpack_extract = _arpack.__dict__[ltr + 'seupd'] self.iterate_infodict = _SAUPD_ERRORS[ltr] self.extract_infodict = _SEUPD_ERRORS[ltr] self.ipntr = np.zeros(11, "int") def iterate(self): self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info = \ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode == 1: self.workd[yslice] = self.OP(self.workd[xslice]) elif self.mode == 2: self.workd[xslice] = self.OPb(self.workd[xslice]) self.workd[yslice] = self.OPa(self.workd[xslice]) elif self.mode == 5: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) Ax = self.A_matvec(self.workd[xslice]) self.workd[yslice] = self.OPa(Ax + (self.sigma * self.workd[Bxslice])) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): rvec = return_eigenvectors ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused d, z, ierr = self._arpack_extract(rvec, howmny, sselect, self.sigma, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam[0:7], self.ipntr, self.workd[0:2 * self.n], self.workl, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d class _UnsymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x # A - square matrix # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the generalized eigenvalue problem: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3,4: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # if A is real and mode==3, use the real part of Minv_matvec # if A is real and mode==4, use the imag part of Minv_matvec # if A is complex and mode==3, # use real and imag parts of Minv_matvec if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode in (3, 4): if matvec is None: raise ValueError("matvec must be specified " "for mode in (3,4)") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified " "for mode in (3,4)") self.matvec = matvec if tp in 'DF': # complex type if mode == 3: self.OPa = Minv_matvec else: raise ValueError("mode=4 invalid for complex A") else: # real type if mode == 3: self.OPa = lambda x: np.real(Minv_matvec(x)) else: self.OPa = lambda x: np.imag(Minv_matvec(x)) if M_matvec is None: self.B = lambda x: x self.bmat = 'I' self.OP = self.OPa else: self.B = M_matvec self.bmat = 'G' self.OP = lambda x: self.OPa(M_matvec(x)) else: raise ValueError("mode=%i not implemented" % mode) if which not in _NEUPD_WHICH: raise ValueError("Parameter which must be one of %s" % ' '.join(_NEUPD_WHICH)) if k >= n - 1: raise ValueError("k must be less than rank(A)-1, k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k + 1: raise ValueError("ncv must be k+1<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(3 * self.ncv * (self.ncv + 2), self.tp) ltr = _type_conv[self.tp] self._arpack_solver = _arpack.__dict__[ltr + 'naupd'] self._arpack_extract = _arpack.__dict__[ltr + 'neupd'] self.iterate_infodict = _NAUPD_ERRORS[ltr] self.extract_infodict = _NEUPD_ERRORS[ltr] self.ipntr = np.zeros(14, "int") if self.tp in 'FD': self.rwork = np.zeros(self.ncv, self.tp.lower()) else: self.rwork = None def iterate(self): if self.tp in 'fd': self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) else: self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode in (1, 2): self.workd[yslice] = self.OP(self.workd[xslice]) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): k, n = self.k, self.n ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused sigmar = np.real(self.sigma) sigmai = np.imag(self.sigma) workev = np.zeros(3 * self.ncv, self.tp) if self.tp in 'fd': dr = np.zeros(k + 1, self.tp) di = np.zeros(k + 1, self.tp) zr = np.zeros((n, k + 1), self.tp) dr, di, zr, ierr = \ self._arpack_extract( return_eigenvectors, howmny, sselect, sigmar, sigmai, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) nreturned = self.iparam[4] # number of good eigenvalues returned # Build complex eigenvalues from real and imaginary parts d = dr + 1.0j * di # Arrange the eigenvectors: complex eigenvectors are stored as # real,imaginary in consecutive columns z = zr.astype(self.tp.upper()) # The ARPACK nonsymmetric real and double interface (s,d)naupd # return eigenvalues and eigenvectors in real (float,double) # arrays. # Efficiency: this should check that return_eigenvectors == True # before going through this construction. if sigmai == 0: i = 0 while i <= k: # check if complex if abs(d[i].imag) != 0: # this is a complex conjugate pair with eigenvalues # in consecutive columns if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 else: # real matrix, mode 3 or 4, imag(sigma) is nonzero: # see remark 3 in <s,d>neupd.f # Build complex eigenvalues from real and imaginary parts i = 0 while i <= k: if abs(d[i].imag) == 0: d[i] = np.dot(zr[:, i], self.matvec(zr[:, i])) else: if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() d[i] = ((np.dot(zr[:, i], self.matvec(zr[:, i])) + np.dot(zr[:, i + 1], self.matvec(zr[:, i + 1]))) + 1j * (np.dot(zr[:, i], self.matvec(zr[:, i + 1])) - np.dot(zr[:, i + 1], self.matvec(zr[:, i])))) d[i + 1] = d[i].conj() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 # Now we have k+1 possible eigenvalues and eigenvectors # Return the ones specified by the keyword "which" if nreturned <= k: # we got less or equal as many eigenvalues we wanted d = d[:nreturned] z = z[:, :nreturned] else: # we got one extra eigenvalue (likely a cc pair, but which?) # cut at approx precision for sorting rd = np.round(d, decimals=_ndigits[self.tp]) if self.which in ['LR', 'SR']: ind = np.argsort(rd.real) elif self.which in ['LI', 'SI']: # for LI,SI ARPACK returns largest,smallest # abs(imaginary) why? ind = np.argsort(abs(rd.imag)) else: ind = np.argsort(abs(rd)) if self.which in ['LR', 'LM', 'LI']: d = d[ind[-k:]] z = z[:, ind[-k:]] if self.which in ['SR', 'SM', 'SI']: d = d[ind[:k]] z = z[:, ind[:k]] else: # complex is so much simpler... d, z, ierr =\ self._arpack_extract( return_eigenvectors, howmny, sselect, self.sigma, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d def _aslinearoperator_with_dtype(m): m = aslinearoperator(m) if not hasattr(m, 'dtype'): x = np.zeros(m.shape[1]) m.dtype = (m * x).dtype return m class SpLuInv(LinearOperator): """ SpLuInv: helper class to repeatedly solve M*x=b using a sparse LU-decopposition of M """ def __init__(self, M): self.M_lu = splu(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) self.isreal = not np.issubdtype(self.dtype, np.complexfloating) def _matvec(self, x): # careful here: splu.solve will throw away imaginary # part of x if M is real if self.isreal and np.issubdtype(x.dtype, np.complexfloating): return (self.M_lu.solve(np.real(x)) + 1j * self.M_lu.solve(np.imag(x))) else: return self.M_lu.solve(x) class LuInv(LinearOperator): """ LuInv: helper class to repeatedly solve M*x=b using an LU-decomposition of M """ def __init__(self, M): self.M_lu = lu_factor(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) def _matvec(self, x): return lu_solve(self.M_lu, x) class IterInv(LinearOperator): """ IterInv: helper class to repeatedly solve M*x=b using an iterative method. """ def __init__(self, M, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(M.dtype).eps self.M = M self.ifunc = ifunc self.tol = tol if hasattr(M, 'dtype'): dtype = M.dtype else: x = np.zeros(M.shape[1]) dtype = (M * x).dtype LinearOperator.__init__(self, M.shape, self._matvec, dtype=dtype) def _matvec(self, x): b, info = self.ifunc(self.M, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting M: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b class IterOpInv(LinearOperator): """ IterOpInv: helper class to repeatedly solve [A-sigma*M]*x = b using an iterative method """ def __init__(self, A, M, sigma, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(A.dtype).eps self.A = A self.M = M self.sigma = sigma self.ifunc = ifunc self.tol = tol x = np.zeros(A.shape[1]) if M is None: dtype = self.mult_func_M_None(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func_M_None, dtype=dtype) else: dtype = self.mult_func(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func, dtype=dtype) LinearOperator.__init__(self, A.shape, self._matvec, dtype=dtype) def mult_func(self, x): return self.A.matvec(x) - self.sigma * self.M.matvec(x) def mult_func_M_None(self, x): return self.A.matvec(x) - self.sigma * x def _matvec(self, x): b, info = self.ifunc(self.OP, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting [A-sigma*M]: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b def get_inv_matvec(M, symmetric=False, tol=0): if isdense(M): return LuInv(M).matvec elif isspmatrix(M): if isspmatrix_csr(M) and symmetric: M = M.T return SpLuInv(M).matvec else: return IterInv(M, tol=tol).matvec def get_OPinv_matvec(A, M, sigma, symmetric=False, tol=0): if sigma == 0: return get_inv_matvec(A, symmetric=symmetric, tol=tol) if M is None: #M is the identity matrix if isdense(A): if (np.issubdtype(A.dtype, np.complexfloating) or np.imag(sigma) == 0): A = np.copy(A) else: A = A + 0j A.flat[::A.shape[1] + 1] -= sigma return LuInv(A).matvec elif isspmatrix(A): A = A - sigma * identity(A.shape[0]) if symmetric and isspmatrix_csr(A): A = A.T return SpLuInv(A.tocsc()).matvec else: return IterOpInv(_aslinearoperator_with_dtype(A), M, sigma, tol=tol).matvec else: if ((not isdense(A) and not isspmatrix(A)) or (not isdense(M) and not isspmatrix(M))): return IterOpInv(_aslinearoperator_with_dtype(A), _aslinearoperator_with_dtype(M), sigma, tol=tol).matvec elif isdense(A) or isdense(M): return LuInv(A - sigma * M).matvec else: OP = A - sigma * M if symmetric and isspmatrix_csr(OP): OP = OP.T return SpLuInv(OP.tocsc()).matvec def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, OPpart=None): """ Find k eigenvalues and eigenvectors of the square matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing \ the operation A * x, where A is a real or complex square matrix. k : int, default 6 The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. return_eigenvectors : boolean, default True Whether to return the eigenvectors along with the eigenvalues. M : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation M*x for the generalized eigenvalue problem ``A * x = w * M * x`` M must represent a real symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma==None, M is positive definite * If sigma is specified, M is positive semi-definite If sigma==None, eigs requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real or complex Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] * x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. For a real matrix A, shift-invert can either be done in imaginary mode or real mode, specified by the parameter OPpart ('r' or 'i'). Note that when sigma is specified, the keyword 'which' (below) refers to the shifted eigenvalues w'[i] where: * If A is real and OPpart == 'r' (default), w'[i] = 1/2 * [ 1/(w[i]-sigma) + 1/(w[i]-conj(sigma)) ] * If A is real and OPpart == 'i', w'[i] = 1/2i * [ 1/(w[i]-sigma) - 1/(w[i]-conj(sigma)) ] * If A is complex, w'[i] = 1/(w[i]-sigma) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated `ncv` must be greater than `k`; it is recommended that ``ncv > 2*k``. which : string ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'] Which `k` eigenvectors and eigenvalues to find: - 'LM' : largest magnitude - 'SM' : smallest magnitude - 'LR' : largest real part - 'SR' : smallest real part - 'LI' : largest imaginary part - 'SI' : smallest imaginary part When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion) The default value of 0 implies machine precision. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues Minv : N x N matrix, array, sparse matrix, or linear operator See notes in M, above. OPinv : N x N matrix, array, sparse matrix, or linear operator See notes in sigma, above. OPpart : 'r' or 'i'. See notes in sigma, above Returns ------- w : array Array of k eigenvalues. v : array An array of `k` eigenvectors. ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i]. Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigsh : eigenvalues and eigenvectors for symmetric matrix A svds : singular value decomposition for a matrix A Examples -------- Find 6 eigenvectors of the identity matrix: >>> from sklearn.utils.arpack import eigs >>> id = np.identity(13) >>> vals, vecs = eigs(id, k=6) >>> vals array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> vecs.shape (13, 6) Notes ----- This function is a wrapper to the ARPACK [1]_ SNEUPD, DNEUPD, CNEUPD, ZNEUPD, functions which use the Implicitly Restarted Arnoldi Method to find the eigenvalues and eigenvectors [2]_. References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if OPpart is not None: raise ValueError("OPpart should not be specified with " "sigma = None or complex A") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: #sigma is not None: shift-invert mode if np.issubdtype(A.dtype, np.complexfloating): if OPpart is not None: raise ValueError("OPpart should not be specified " "with sigma=None or complex A") mode = 3 elif OPpart is None or OPpart.lower() == 'r': mode = 3 elif OPpart.lower() == 'i': if np.imag(sigma) == 0: raise ValueError("OPpart cannot be 'i' if sigma is real") mode = 4 else: raise ValueError("OPpart must be one of ('r','i')") matvec = _aslinearoperator_with_dtype(A).matvec if Minv is not None: raise ValueError("Minv should not be specified when sigma is") if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=False, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec params = _UnsymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, mode='normal'): """ Find k eigenvalues and eigenvectors of the real symmetric square matrix or complex hermitian matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation A * x, where A is a real symmetric matrix For buckling mode (see below) A must additionally be positive-definite k : integer The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. M : An N x N matrix, array, sparse matrix, or linear operator representing the operation M * x for the generalized eigenvalue problem ``A * x = w * M * x``. M must represent a real, symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma == None, M is symmetric positive definite * If sigma is specified, M is symmetric positive semi-definite * In buckling mode, M is symmetric indefinite. If sigma == None, eigsh requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. Note that when sigma is specified, the keyword 'which' refers to the shifted eigenvalues w'[i] where: - if mode == 'normal', w'[i] = 1 / (w[i] - sigma) - if mode == 'cayley', w'[i] = (w[i] + sigma) / (w[i] - sigma) - if mode == 'buckling', w'[i] = w[i] / (w[i] - sigma) (see further discussion in 'mode' below) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated ncv must be greater than k and smaller than n; it is recommended that ncv > 2*k which : string ['LM' | 'SM' | 'LA' | 'SA' | 'BE'] If A is a complex hermitian matrix, 'BE' is invalid. Which `k` eigenvectors and eigenvalues to find - 'LM' : Largest (in magnitude) eigenvalues - 'SM' : Smallest (in magnitude) eigenvalues - 'LA' : Largest (algebraic) eigenvalues - 'SA' : Smallest (algebraic) eigenvalues - 'BE' : Half (k/2) from each end of the spectrum When k is odd, return one more (k/2+1) from the high end When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion). The default value of 0 implies machine precision. Minv : N x N matrix, array, sparse matrix, or LinearOperator See notes in M, above OPinv : N x N matrix, array, sparse matrix, or LinearOperator See notes in sigma, above. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues mode : string ['normal' | 'buckling' | 'cayley'] Specify strategy to use for shift-invert mode. This argument applies only for real-valued A and sigma != None. For shift-invert mode, ARPACK internally solves the eigenvalue problem ``OP * x'[i] = w'[i] * B * x'[i]`` and transforms the resulting Ritz vectors x'[i] and Ritz values w'[i] into the desired eigenvectors and eigenvalues of the problem ``A * x[i] = w[i] * M * x[i]``. The modes are as follows: - 'normal' : OP = [A - sigma * M]^-1 * M B = M w'[i] = 1 / (w[i] - sigma) - 'buckling' : OP = [A - sigma * M]^-1 * A B = A w'[i] = w[i] / (w[i] - sigma) - 'cayley' : OP = [A - sigma * M]^-1 * [A + sigma * M] B = M w'[i] = (w[i] + sigma) / (w[i] - sigma) The choice of mode will affect which eigenvalues are selected by the keyword 'which', and can also impact the stability of convergence (see [2] for a discussion) Returns ------- w : array Array of k eigenvalues v : array An array of k eigenvectors The v[i] is the eigenvector corresponding to the eigenvector w[i] Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigs : eigenvalues and eigenvectors for a general (nonsymmetric) matrix A svds : singular value decomposition for a matrix A Notes ----- This function is a wrapper to the ARPACK [1]_ SSEUPD and DSEUPD functions which use the Implicitly Restarted Lanczos Method to find the eigenvalues and eigenvectors [2]_. Examples -------- >>> from sklearn.utils.arpack import eigsh >>> id = np.identity(13) >>> vals, vecs = eigsh(id, k=6) >>> vals # doctest: +SKIP array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> print(vecs.shape) (13, 6) References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ # complex hermitian matrices should be solved with eigs if np.issubdtype(A.dtype, np.complexfloating): if mode != 'normal': raise ValueError("mode=%s cannot be used with " "complex matrix A" % mode) if which == 'BE': raise ValueError("which='BE' cannot be used with complex matrix A") elif which == 'LA': which = 'LR' elif which == 'SA': which = 'SR' ret = eigs(A, k, M=M, sigma=sigma, which=which, v0=v0, ncv=ncv, maxiter=maxiter, tol=tol, return_eigenvectors=return_eigenvectors, Minv=Minv, OPinv=OPinv) if return_eigenvectors: return ret[0].real, ret[1] else: return ret.real if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: A = _aslinearoperator_with_dtype(A) matvec = A.matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: # sigma is not None: shift-invert mode if Minv is not None: raise ValueError("Minv should not be specified when sigma is") # normal mode if mode == 'normal': mode = 3 matvec = None if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M = _aslinearoperator_with_dtype(M) M_matvec = M.matvec # buckling mode elif mode == 'buckling': mode = 4 if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec matvec = _aslinearoperator_with_dtype(A).matvec M_matvec = None # cayley-transform mode elif mode == 'cayley': mode = 5 matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec # unrecognized mode else: raise ValueError("unrecognized mode '%s'" % mode) params = _SymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _svds(A, k=6, ncv=None, tol=0): """Compute k singular values/vectors for a sparse matrix using ARPACK. Parameters ---------- A : sparse matrix Array to compute the SVD on k : int, optional Number of singular values and vectors to compute. ncv : integer The number of Lanczos vectors generated ncv must be greater than k+1 and smaller than n; it is recommended that ncv > 2*k tol : float, optional Tolerance for singular values. Zero (default) means machine precision. Notes ----- This is a naive implementation using an eigensolver on A.H * A or A * A.H, depending on which one is more efficient. """ if not (isinstance(A, np.ndarray) or isspmatrix(A)): A = np.asarray(A) n, m = A.shape if np.issubdtype(A.dtype, np.complexfloating): herm = lambda x: x.T.conjugate() eigensolver = eigs else: herm = lambda x: x.T eigensolver = eigsh if n > m: X = A XH = herm(A) else: XH = A X = herm(A) if hasattr(XH, 'dot'): def matvec_XH_X(x): return XH.dot(X.dot(x)) else: def matvec_XH_X(x): return np.dot(XH, np.dot(X, x)) XH_X = LinearOperator(matvec=matvec_XH_X, dtype=X.dtype, shape=(X.shape[1], X.shape[1])) # Ignore deprecation warnings here: dot on matrices is deprecated, # but this code is a backport anyhow with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) eigvals, eigvec = eigensolver(XH_X, k=k, tol=tol ** 2) s = np.sqrt(eigvals) if n > m: v = eigvec if hasattr(X, 'dot'): u = X.dot(v) / s else: u = np.dot(X, v) / s vh = herm(v) else: u = eigvec if hasattr(X, 'dot'): vh = herm(X.dot(u) / s) else: vh = herm(np.dot(X, u) / s) return u, s, vh # check if backport is actually needed: if scipy.version.version >= LooseVersion('0.10'): from scipy.sparse.linalg import eigs, eigsh, svds else: eigs, eigsh, svds = _eigs, _eigsh, _svds
mikewiebe-ansible/ansible
refs/heads/devel
lib/ansible/modules/cloud/cloudstack/cs_vpc_offering.py
13
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017, David Passante (@dpassante) # 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: cs_vpc_offering short_description: Manages vpc offerings on Apache CloudStack based clouds. description: - Create, update, enable, disable and remove CloudStack VPC offerings. version_added: '2.5' author: David Passante (@dpassante) options: name: description: - The name of the vpc offering type: str required: true state: description: - State of the vpc offering. type: str choices: [ enabled, present, disabled, absent ] default: present display_text: description: - Display text of the vpc offerings type: str service_capabilities: description: - Desired service capabilities as part of vpc offering. type: list aliases: [ service_capability ] service_offering: description: - The name or ID of the service offering for the VPC router appliance. type: str supported_services: description: - Services supported by the vpc offering type: list aliases: [ supported_service ] service_providers: description: - provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network type: list aliases: [ service_provider ] poll_async: description: - Poll async jobs until job has finished. default: yes type: bool extends_documentation_fragment: cloudstack ''' EXAMPLES = ''' - name: Create a vpc offering and enable it cs_vpc_offering: name: my_vpc_offering display_text: vpc offering description state: enabled supported_services: [ Dns, Dhcp ] service_providers: - {service: 'dns', provider: 'VpcVirtualRouter'} - {service: 'dhcp', provider: 'VpcVirtualRouter'} delegate_to: localhost - name: Create a vpc offering with redundant router cs_vpc_offering: name: my_vpc_offering display_text: vpc offering description supported_services: [ Dns, Dhcp, SourceNat ] service_providers: - {service: 'dns', provider: 'VpcVirtualRouter'} - {service: 'dhcp', provider: 'VpcVirtualRouter'} - {service: 'SourceNat', provider: 'VpcVirtualRouter'} service_capabilities: - {service: 'SourceNat', capabilitytype: 'RedundantRouter', capabilityvalue: true} delegate_to: localhost - name: Create a region level vpc offering with distributed router cs_vpc_offering: name: my_vpc_offering display_text: vpc offering description state: present supported_services: [ Dns, Dhcp, SourceNat ] service_providers: - {service: 'dns', provider: 'VpcVirtualRouter'} - {service: 'dhcp', provider: 'VpcVirtualRouter'} - {service: 'SourceNat', provider: 'VpcVirtualRouter'} service_capabilities: - {service: 'Connectivity', capabilitytype: 'DistributedRouter', capabilityvalue: true} - {service: 'Connectivity', capabilitytype: 'RegionLevelVPC', capabilityvalue: true} delegate_to: localhost - name: Remove a vpc offering cs_vpc_offering: name: my_vpc_offering state: absent delegate_to: localhost ''' RETURN = ''' --- id: description: UUID of the vpc offering. returned: success type: str sample: a6f7a5fc-43f8-11e5-a151-feff819cdc9f name: description: The name of the vpc offering returned: success type: str sample: MyCustomVPCOffering display_text: description: The display text of the vpc offering returned: success type: str sample: My vpc offering state: description: The state of the vpc offering returned: success type: str sample: Enabled service_offering_id: description: The service offering ID. returned: success type: str sample: c5f7a5fc-43f8-11e5-a151-feff819cdc9f is_default: description: Whether VPC offering is the default offering or not. returned: success type: bool sample: false region_level: description: Indicated if the offering can support region level vpc. returned: success type: bool sample: false distributed: description: Indicates if the vpc offering supports distributed router for one-hop forwarding. returned: success type: bool sample: false ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, cs_argument_spec, cs_required_together, ) class AnsibleCloudStackVPCOffering(AnsibleCloudStack): def __init__(self, module): super(AnsibleCloudStackVPCOffering, self).__init__(module) self.returns = { 'serviceofferingid': 'service_offering_id', 'isdefault': 'is_default', 'distributedvpcrouter': 'distributed', 'supportsregionLevelvpc': 'region_level', } self.vpc_offering = None def get_vpc_offering(self): if self.vpc_offering: return self.vpc_offering args = { 'name': self.module.params.get('name'), } vo = self.query_api('listVPCOfferings', **args) if vo: for vpc_offer in vo['vpcoffering']: if args['name'] == vpc_offer['name']: self.vpc_offering = vpc_offer return self.vpc_offering def get_service_offering_id(self): service_offering = self.module.params.get('service_offering') if not service_offering: return None args = { 'issystem': True } service_offerings = self.query_api('listServiceOfferings', **args) if service_offerings: for s in service_offerings['serviceoffering']: if service_offering in [s['name'], s['id']]: return s['id'] self.fail_json(msg="Service offering '%s' not found" % service_offering) def create_or_update(self): vpc_offering = self.get_vpc_offering() if not vpc_offering: vpc_offering = self.create_vpc_offering() return self.update_vpc_offering(vpc_offering) def create_vpc_offering(self): vpc_offering = None self.result['changed'] = True args = { 'name': self.module.params.get('name'), 'state': self.module.params.get('state'), 'displaytext': self.module.params.get('display_text'), 'supportedservices': self.module.params.get('supported_services'), 'serviceproviderlist': self.module.params.get('service_providers'), 'serviceofferingid': self.get_service_offering_id(), 'servicecapabilitylist': self.module.params.get('service_capabilities'), } required_params = [ 'display_text', 'supported_services', ] self.module.fail_on_missing_params(required_params=required_params) if not self.module.check_mode: res = self.query_api('createVPCOffering', **args) poll_async = self.module.params.get('poll_async') if poll_async: vpc_offering = self.poll_job(res, 'vpcoffering') return vpc_offering def delete_vpc_offering(self): vpc_offering = self.get_vpc_offering() if vpc_offering: self.result['changed'] = True args = { 'id': vpc_offering['id'], } if not self.module.check_mode: res = self.query_api('deleteVPCOffering', **args) poll_async = self.module.params.get('poll_async') if poll_async: vpc_offering = self.poll_job(res, 'vpcoffering') return vpc_offering def update_vpc_offering(self, vpc_offering): if not vpc_offering: return vpc_offering args = { 'id': vpc_offering['id'], 'state': self.module.params.get('state'), 'name': self.module.params.get('name'), 'displaytext': self.module.params.get('display_text'), } if args['state'] in ['enabled', 'disabled']: args['state'] = args['state'].title() else: del args['state'] if self.has_changed(args, vpc_offering): self.result['changed'] = True if not self.module.check_mode: res = self.query_api('updateVPCOffering', **args) poll_async = self.module.params.get('poll_async') if poll_async: vpc_offering = self.poll_job(res, 'vpcoffering') return vpc_offering def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name=dict(required=True), display_text=dict(), state=dict(choices=['enabled', 'present', 'disabled', 'absent'], default='present'), service_capabilities=dict(type='list', aliases=['service_capability']), service_offering=dict(), supported_services=dict(type='list', aliases=['supported_service']), service_providers=dict(type='list', aliases=['service_provider']), poll_async=dict(type='bool', default=True), )) module = AnsibleModule( argument_spec=argument_spec, required_together=cs_required_together(), supports_check_mode=True ) acs_vpc_offering = AnsibleCloudStackVPCOffering(module) state = module.params.get('state') if state in ['absent']: vpc_offering = acs_vpc_offering.delete_vpc_offering() else: vpc_offering = acs_vpc_offering.create_or_update() result = acs_vpc_offering.get_result(vpc_offering) module.exit_json(**result) if __name__ == '__main__': main()
lucafavatella/intellij-community
refs/heads/cli-wip
python/testData/codeInsight/smartEnter/classKeywordOnly_after.py
79
class <caret>:
mdblv2/joatu-django
refs/heads/master
application/site-packages/django/core/management/commands/startapp.py
205
from django.core.management.base import CommandError from django.core.management.templates import TemplateCommand from django.utils.importlib import import_module class Command(TemplateCommand): help = ("Creates a Django app directory structure for the given app " "name in the current directory or optionally in the given " "directory.") def handle(self, app_name=None, target=None, **options): if app_name is None: raise CommandError("you must provide an app name") # Check that the app_name cannot be imported. try: import_module(app_name) except ImportError: pass else: raise CommandError("%r conflicts with the name of an existing " "Python module and cannot be used as an app " "name. Please try another name." % app_name) super(Command, self).handle('app', app_name, target, **options)
chromium2014/src
refs/heads/master
tools/telemetry/unittest_data/test_simple_two_page_set.py
10
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page.page_set import PageSet class TestSimpleTwoPageSet(PageSet): def __init__(self): super(TestSimpleTwoPageSet, self).__init__( archive_data_file='data/test.json', credentials_path='data/credential', user_agent_type='desktop')
sgraham/nope
refs/heads/master
v8/tools/testrunner/server/work_handler.py
123
# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import SocketServer import stat import subprocess import threading from . import compression from . import constants from . import signatures from ..network import endpoint from ..objects import workpacket class WorkHandler(SocketServer.BaseRequestHandler): def handle(self): rec = compression.Receiver(self.request) while not rec.IsDone(): data = rec.Current() with self.server.job_lock: self._WorkOnWorkPacket(data) rec.Advance() def _WorkOnWorkPacket(self, data): server_root = self.server.daemon.root v8_root = os.path.join(server_root, "v8") os.chdir(v8_root) packet = workpacket.WorkPacket.Unpack(data) self.ctx = packet.context self.ctx.shell_dir = os.path.join("out", "%s.%s" % (self.ctx.arch, self.ctx.mode)) if not os.path.isdir(self.ctx.shell_dir): os.makedirs(self.ctx.shell_dir) for binary in packet.binaries: if not self._UnpackBinary(binary, packet.pubkey_fingerprint): return if not self._CheckoutRevision(packet.base_revision): return if not self._ApplyPatch(packet.patch): return tests = packet.tests endpoint.Execute(v8_root, self.ctx, tests, self.request, self.server.daemon) self._SendResponse() def _SendResponse(self, error_message=None): try: if error_message: compression.Send([[-1, error_message]], self.request) compression.Send(constants.END_OF_STREAM, self.request) return except Exception, e: pass # Peer is gone. There's nothing we can do. # Clean up. self._Call("git checkout -f") self._Call("git clean -f -d") self._Call("rm -rf %s" % self.ctx.shell_dir) def _UnpackBinary(self, binary, pubkey_fingerprint): binary_name = binary["name"] if binary_name == "libv8.so": libdir = os.path.join(self.ctx.shell_dir, "lib.target") if not os.path.exists(libdir): os.makedirs(libdir) target = os.path.join(libdir, binary_name) else: target = os.path.join(self.ctx.shell_dir, binary_name) pubkeyfile = "../trusted/%s.pem" % pubkey_fingerprint if not signatures.VerifySignature(target, binary["blob"], binary["sign"], pubkeyfile): self._SendResponse("Signature verification failed") return False os.chmod(target, stat.S_IRWXU) return True def _CheckoutRevision(self, base_svn_revision): get_hash_cmd = ( "git log -1 --format=%%H --remotes --grep='^git-svn-id:.*@%s'" % base_svn_revision) try: base_revision = subprocess.check_output(get_hash_cmd, shell=True) if not base_revision: raise ValueError except: self._Call("git fetch") try: base_revision = subprocess.check_output(get_hash_cmd, shell=True) if not base_revision: raise ValueError except: self._SendResponse("Base revision not found.") return False code = self._Call("git checkout -f %s" % base_revision) if code != 0: self._SendResponse("Error trying to check out base revision.") return False code = self._Call("git clean -f -d") if code != 0: self._SendResponse("Failed to reset checkout") return False return True def _ApplyPatch(self, patch): if not patch: return True # Just skip if the patch is empty. patchfilename = "_dtest_incoming_patch.patch" with open(patchfilename, "w") as f: f.write(patch) code = self._Call("git apply %s" % patchfilename) if code != 0: self._SendResponse("Error applying patch.") return False return True def _Call(self, cmd): return subprocess.call(cmd, shell=True) class WorkSocketServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): def __init__(self, daemon): address = (daemon.ip, constants.PEER_PORT) SocketServer.TCPServer.__init__(self, address, WorkHandler) self.job_lock = threading.Lock() self.daemon = daemon
837468220/python-for-android
refs/heads/master
python3-alpha/python3-src/Tools/scripts/reindent.py
48
#! /usr/bin/env python3 # Released to the public domain, by Tim Peters, 03 October 2000. """reindent [-d][-r][-v] [ path ... ] -d (--dryrun) Dry run. Analyze, but don't make any changes to, files. -r (--recurse) Recurse. Search for all .py files in subdirectories too. -n (--nobackup) No backup. Does not make a ".bak" file before reindenting. -v (--verbose) Verbose. Print informative msgs; else no output. -h (--help) Help. Print this usage information and exit. Change Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files. Also ensure the last line ends with a newline. If no paths are given on the command line, reindent operates as a filter, reading a single source file from standard input and writing the transformed source to standard output. In this case, the -d, -r and -v flags are ignored. You can pass one or more file and/or directory paths. When a directory path, all .py files within the directory will be examined, and, if the -r option is given, likewise recursively for subdirectories. If output is not to standard output, reindent overwrites files in place, renaming the originals with a .bak extension. If it finds nothing to change, the file is left alone. If reindent does change a file, the changed file is a fixed-point for future runs (i.e., running reindent on the resulting .py file won't change it again). The hard part of reindenting is figuring out what to do with comment lines. So long as the input files get a clean bill of health from tabnanny.py, reindent should do a good job. The backup file is a copy of the one that is being reindented. The ".bak" file is generated with shutil.copy(), but some corner cases regarding user/group and permissions could leave the backup file more readable than you'd prefer. You can always use the --nobackup option to prevent this. """ __version__ = "1" import tokenize import os import shutil import sys verbose = False recurse = False dryrun = False makebackup = True def usage(msg=None): if msg is None: msg = __doc__ print(msg, file=sys.stderr) def errprint(*args): sys.stderr.write(" ".join(str(arg) for arg in args)) sys.stderr.write("\n") def main(): import getopt global verbose, recurse, dryrun, makebackup try: opts, args = getopt.getopt(sys.argv[1:], "drnvh", ["dryrun", "recurse", "nobackup", "verbose", "help"]) except getopt.error as msg: usage(msg) return for o, a in opts: if o in ('-d', '--dryrun'): dryrun = True elif o in ('-r', '--recurse'): recurse = True elif o in ('-n', '--nobackup'): makebackup = False elif o in ('-v', '--verbose'): verbose = True elif o in ('-h', '--help'): usage() return if not args: r = Reindenter(sys.stdin) r.run() r.write(sys.stdout) return for arg in args: check(arg) def check(file): if os.path.isdir(file) and not os.path.islink(file): if verbose: print("listing directory", file) names = os.listdir(file) for name in names: fullname = os.path.join(file, name) if ((recurse and os.path.isdir(fullname) and not os.path.islink(fullname) and not os.path.split(fullname)[1].startswith(".")) or name.lower().endswith(".py")): check(fullname) return if verbose: print("checking", file, "...", end=' ') with open(file, 'rb') as f: encoding, _ = tokenize.detect_encoding(f.readline) try: with open(file, encoding=encoding) as f: r = Reindenter(f) except IOError as msg: errprint("%s: I/O Error: %s" % (file, str(msg))) return newline = r.newlines if isinstance(newline, tuple): errprint("%s: mixed newlines detected; cannot process file" % file) return if r.run(): if verbose: print("changed.") if dryrun: print("But this is a dry run, so leaving it alone.") if not dryrun: bak = file + ".bak" if makebackup: shutil.copyfile(file, bak) if verbose: print("backed up", file, "to", bak) with open(file, "w", encoding=encoding, newline=newline) as f: r.write(f) if verbose: print("wrote new", file) return True else: if verbose: print("unchanged.") return False def _rstrip(line, JUNK='\n \t'): """Return line stripped of trailing spaces, tabs, newlines. Note that line.rstrip() instead also strips sundry control characters, but at least one known Emacs user expects to keep junk like that, not mentioning Barry by name or anything <wink>. """ i = len(line) while i > 0 and line[i - 1] in JUNK: i -= 1 return line[:i] class Reindenter: def __init__(self, f): self.find_stmt = 1 # next token begins a fresh stmt? self.level = 0 # current indent level # Raw file lines. self.raw = f.readlines() # File lines, rstripped & tab-expanded. Dummy at start is so # that we can use tokenize's 1-based line numbering easily. # Note that a line is all-blank iff it's "\n". self.lines = [_rstrip(line).expandtabs() + "\n" for line in self.raw] self.lines.insert(0, None) self.index = 1 # index into self.lines of next line # List of (lineno, indentlevel) pairs, one for each stmt and # comment line. indentlevel is -1 for comment lines, as a # signal that tokenize doesn't know what to do about them; # indeed, they're our headache! self.stats = [] # Save the newlines found in the file so they can be used to # create output without mutating the newlines. self.newlines = f.newlines def run(self): tokens = tokenize.generate_tokens(self.getline) for _token in tokens: self.tokeneater(*_token) # Remove trailing empty lines. lines = self.lines while lines and lines[-1] == "\n": lines.pop() # Sentinel. stats = self.stats stats.append((len(lines), 0)) # Map count of leading spaces to # we want. have2want = {} # Program after transformation. after = self.after = [] # Copy over initial empty lines -- there's nothing to do until # we see a line with *something* on it. i = stats[0][0] after.extend(lines[1:i]) for i in range(len(stats) - 1): thisstmt, thislevel = stats[i] nextstmt = stats[i + 1][0] have = getlspace(lines[thisstmt]) want = thislevel * 4 if want < 0: # A comment line. if have: # An indented comment line. If we saw the same # indentation before, reuse what it most recently # mapped to. want = have2want.get(have, -1) if want < 0: # Then it probably belongs to the next real stmt. for j in range(i + 1, len(stats) - 1): jline, jlevel = stats[j] if jlevel >= 0: if have == getlspace(lines[jline]): want = jlevel * 4 break if want < 0: # Maybe it's a hanging # comment like this one, # in which case we should shift it like its base # line got shifted. for j in range(i - 1, -1, -1): jline, jlevel = stats[j] if jlevel >= 0: want = have + (getlspace(after[jline - 1]) - getlspace(lines[jline])) break if want < 0: # Still no luck -- leave it alone. want = have else: want = 0 assert want >= 0 have2want[have] = want diff = want - have if diff == 0 or have == 0: after.extend(lines[thisstmt:nextstmt]) else: for line in lines[thisstmt:nextstmt]: if diff > 0: if line == "\n": after.append(line) else: after.append(" " * diff + line) else: remove = min(getlspace(line), -diff) after.append(line[remove:]) return self.raw != self.after def write(self, f): f.writelines(self.after) # Line-getter for tokenize. def getline(self): if self.index >= len(self.lines): line = "" else: line = self.lines[self.index] self.index += 1 return line # Line-eater for tokenize. def tokeneater(self, type, token, slinecol, end, line, INDENT=tokenize.INDENT, DEDENT=tokenize.DEDENT, NEWLINE=tokenize.NEWLINE, COMMENT=tokenize.COMMENT, NL=tokenize.NL): if type == NEWLINE: # A program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? self.find_stmt = 1 elif type == INDENT: self.find_stmt = 1 self.level += 1 elif type == DEDENT: self.find_stmt = 1 self.level -= 1 elif type == COMMENT: if self.find_stmt: self.stats.append((slinecol[0], -1)) # but we're still looking for a new stmt, so leave # find_stmt alone elif type == NL: pass elif self.find_stmt: # This is the first "real token" following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER. self.find_stmt = 0 if line: # not endmarker self.stats.append((slinecol[0], self.level)) # Count number of leading blanks. def getlspace(line): i, n = 0, len(line) while i < n and line[i] == " ": i += 1 return i if __name__ == '__main__': main()
mhbu50/frappe
refs/heads/develop
frappe/utils/minify.py
14
# This code is original from jsmin by Douglas Crockford, it was translated to # Python by Baruch Even. The original code had the following copyright and # license. # # /* jsmin.c # 2007-05-22 # # Copyright (c) 2002 Douglas Crockford (www.crockford.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # The Software shall be used for Good, not Evil. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # */ from six import StringIO def jsmin(js): ins = StringIO(js) outs = StringIO() JavascriptMinify().minify(ins, outs) str = outs.getvalue() if len(str) > 0 and str[0] == '\n': str = str[1:] return str def isAlphanum(c): """return true if the character is a letter, digit, underscore, dollar sign, or non-ASCII character. """ return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or (c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126)); class UnterminatedComment(Exception): pass class UnterminatedStringLiteral(Exception): pass class UnterminatedRegularExpression(Exception): pass class JavascriptMinify(object): def _outA(self): self.outstream.write(self.theA) def _outB(self): self.outstream.write(self.theB) def _get(self): """return the next character from stdin. Watch out for lookahead. If the character is a control character, translate it to a space or linefeed. """ c = self.theLookahead self.theLookahead = None if c == None: c = self.instream.read(1) if c >= ' ' or c == '\n': return c if c == '': # EOF return '\000' if c == '\r': return '\n' return ' ' def _peek(self): self.theLookahead = self._get() return self.theLookahead def _next(self): """get the next character, excluding comments. peek() is used to see if an unescaped '/' is followed by a '/' or '*'. """ c = self._get() if c == '/' and self.theA != '\\': p = self._peek() if p == '/': c = self._get() while c > '\n': c = self._get() return c if p == '*': c = self._get() while 1: c = self._get() if c == '*': if self._peek() == '/': self._get() return ' ' if c == '\000': raise UnterminatedComment() return c def _action(self, action): """do something! What you do is determined by the argument: 1 Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B. (Delete A). 3 Get the next B. (Delete B). action treats a string as a single character. Wow! action recognizes a regular expression if it is preceded by ( or , or =. """ if action <= 1: self._outA() if action <= 2: self.theA = self.theB if self.theA == "'" or self.theA == '"': while 1: self._outA() self.theA = self._get() if self.theA == self.theB: break if self.theA <= '\n': raise UnterminatedStringLiteral() if self.theA == '\\': self._outA() self.theA = self._get() if action <= 3: self.theB = self._next() if self.theB == '/' and (self.theA == '(' or self.theA == ',' or self.theA == '=' or self.theA == ':' or self.theA == '[' or self.theA == '?' or self.theA == '!' or self.theA == '&' or self.theA == '|' or self.theA == ';' or self.theA == '{' or self.theA == '}' or self.theA == '\n'): self._outA() self._outB() while 1: self.theA = self._get() if self.theA == '/': break elif self.theA == '\\': self._outA() self.theA = self._get() elif self.theA <= '\n': raise UnterminatedRegularExpression() self._outA() self.theB = self._next() def _jsmin(self): """Copy the input to the output, deleting the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. """ self.theA = '\n' self._action(3) while self.theA != '\000': if self.theA == ' ': if isAlphanum(self.theB): self._action(1) else: self._action(2) elif self.theA == '\n': if self.theB in ['{', '[', '(', '+', '-']: self._action(1) elif self.theB == ' ': self._action(3) else: if isAlphanum(self.theB): self._action(1) else: self._action(2) else: if self.theB == ' ': if isAlphanum(self.theA): self._action(1) else: self._action(3) elif self.theB == '\n': if self.theA in ['}', ']', ')', '+', '-', '"', '\'']: self._action(1) else: if isAlphanum(self.theA): self._action(1) else: self._action(3) else: self._action(1) def minify(self, instream, outstream): self.instream = instream self.outstream = outstream self.theA = '\n' self.theB = None self.theLookahead = None self._jsmin() self.instream.close()
pquentin/django
refs/heads/stable/1.8.x
django/templatetags/future.py
37
import warnings from django.template import Library, defaulttags from django.utils.deprecation import ( RemovedInDjango19Warning, RemovedInDjango20Warning, ) register = Library() @register.tag def ssi(parser, token): warnings.warn( "Loading the `ssi` tag from the `future` library is deprecated and " "will be removed in Django 1.9. Use the default `ssi` tag instead.", RemovedInDjango19Warning) return defaulttags.ssi(parser, token) @register.tag def url(parser, token): warnings.warn( "Loading the `url` tag from the `future` library is deprecated and " "will be removed in Django 1.9. Use the default `url` tag instead.", RemovedInDjango19Warning) return defaulttags.url(parser, token) @register.tag def cycle(parser, token): """ This is the future version of `cycle` with auto-escaping. The deprecation is now complete and this version is no different from the non-future version so this is deprecated. By default all strings are escaped. If you want to disable auto-escaping of variables you can use:: {% autoescape off %} {% cycle var1 var2 var3 as somecycle %} {% autoescape %} Or if only some variables should be escaped, you can use:: {% cycle var1 var2|safe var3|safe as somecycle %} """ warnings.warn( "Loading the `cycle` tag from the `future` library is deprecated and " "will be removed in Django 2.0. Use the default `cycle` tag instead.", RemovedInDjango20Warning) return defaulttags.cycle(parser, token) @register.tag def firstof(parser, token): """ This is the future version of `firstof` with auto-escaping. The deprecation is now complete and this version is no different from the non-future version so this is deprecated. This is equivalent to:: {% if var1 %} {{ var1 }} {% elif var2 %} {{ var2 }} {% elif var3 %} {{ var3 }} {% endif %} If you want to disable auto-escaping of variables you can use:: {% autoescape off %} {% firstof var1 var2 var3 "<strong>fallback value</strong>" %} {% autoescape %} Or if only some variables should be escaped, you can use:: {% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %} """ warnings.warn( "Loading the `firstof` tag from the `future` library is deprecated and " "will be removed in Django 2.0. Use the default `firstof` tag instead.", RemovedInDjango20Warning) return defaulttags.firstof(parser, token)
happy5214/pywikibot-core
refs/heads/master
scripts/solve_disambiguation.py
2
#!/usr/bin/python # -*- coding: utf-8 -*- u""" Script to help a human solve disambiguations by presenting a set of options. Specify the disambiguation page on the command line. The program will pick up the page, and look for all alternative links, and show them with a number adjacent to them. It will then automatically loop over all pages referring to the disambiguation page, and show 30 characters of context on each side of the reference to help you make the decision between the alternatives. It will ask you to type the number of the appropriate replacement, and perform the change. It is possible to choose to replace only the link (just type the number) or replace both link and link-text (type 'r' followed by the number). Multiple references in one page will be scanned in order, but typing 'n' (next) on any one of them will leave the complete page unchanged. To leave only some reference unchanged, use the 's' (skip) option. Command line options: -pos:XXXX adds XXXX as an alternative disambiguation -just only use the alternatives given on the command line, do not read the page for other possibilities -dnskip Skip links already marked with a disambiguation-needed template (e.g., {{dn}}) -primary "primary topic" disambiguation (Begriffsklärung nach Modell 2). That's titles where one topic is much more important, the disambiguation page is saved somewhere else, and the important topic gets the nice name. -primary:XY like the above, but use XY as the only alternative, instead of searching for alternatives in [[Keyword (disambiguation)]]. Note: this is the same as -primary -just -pos:XY -file:XYZ reads a list of pages from a text file. XYZ is the name of the file from which the list is taken. If XYZ is not given, the user is asked for a filename. Page titles should be inside [[double brackets]]. The -pos parameter won't work if -file is used. -always:XY instead of asking the user what to do, always perform the same action. For example, XY can be "r0", "u" or "2". Be careful with this option, and check the changes made by the bot. Note that some choices for XY don't make sense and will result in a loop, e.g. "l" or "m". -main only check pages in the main namespace, not in the talk, wikipedia, user, etc. namespaces. -start:XY goes through all disambiguation pages in the category on your wiki that is defined (to the bot) as the category containing disambiguation pages, starting at XY. If only '-start' or '-start:' is given, it starts at the beginning. -min:XX (XX being a number) only work on disambiguation pages for which at least XX are to be worked on. To complete a move of a page, one can use: python pwb.py solve_disambiguation -just -pos:New_Name Old_Name """ # # (C) Rob W.W. Hooft, 2003 # (C) Daniel Herding, 2004 # (C) Andre Engels, 2003-2004 # (C) WikiWichtel, 2004 # (C) Pywikibot team, 2003-2017 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals import codecs import os import re import pywikibot from pywikibot import editor as editarticle from pywikibot.tools import first_lower, first_upper as firstcap from pywikibot import pagegenerators, config, i18n from pywikibot.bot import ( Bot, QuitKeyboardInterrupt, StandardOption, HighlightContextOption, ListOption, OutputProxyOption, ) from pywikibot.tools.formatter import SequenceOutputter # Disambiguation Needed template dn_template = { 'en': u'{{dn}}', 'fr': u'{{Lien vers un homonyme}}', } # disambiguation page name format for "primary topic" disambiguations # (Begriffsklärungen nach Modell 2) primary_topic_format = { 'ar': u'%s_(توضيح)', 'ca': u'%s_(desambiguació)', 'cs': u'%s_(rozcestník)', 'de': u'%s_(Begriffsklärung)', 'en': u'%s_(disambiguation)', 'fa': u'%s_(ابهام‌زدایی)', 'fi': u'%s_(täsmennyssivu)', 'hu': u'%s_(egyértelműsítő lap)', 'ia': u'%s_(disambiguation)', 'it': u'%s_(disambigua)', 'lt': u'%s_(reikšmės)', 'kk': u'%s_(айрық)', 'ko': u'%s_(동음이의)', 'nl': u'%s_(doorverwijspagina)', 'no': u'%s_(peker)', 'pl': u'%s_(ujednoznacznienie)', 'pt': u'%s_(desambiguação)', 'pfl': u'%s_BKL', 'he': u'%s_(פירושונים)', 'ru': u'%s_(значения)', 'sr': u'%s_(вишезначна одредница)', 'sv': u'%s_(olika betydelser)', 'uk': u'%s_(значення)', } # List pages that will be ignored if they got a link to a disambiguation # page. An example is a page listing disambiguations articles. # Special chars should be encoded with unicode (\x##) and space used # instead of _ ignore_title = { 'wikipedia': { 'ar': [ u'تصنيف:صفحات توضيح', ], 'ca': [ u'Viquipèdia:Enllaços incorrectes a pàgines de desambiguació', u'Viquipèdia:Registre de pàgines de desambiguació òrfenes', u'.*Discussió:.+', u'.*Usuari:.+', u'.+/[aA]rxiu.*', ], 'cs': [ u'Wikipedie:Chybějící interwiki/.+', u'Wikipedie:Rozcestníky', u'Wikipedie diskuse:Rozcestníky', u'Wikipedie:Seznam nejvíce odkazovaných rozcestníků', u'Wikipedie:Seznam rozcestníků/první typ', u'Wikipedie:Seznam rozcestníků/druhý typ', u'Wikipedista:Zirland/okres', ], 'da': [ u'Wikipedia:Links til sider med flertydige titler' ], 'de': [ u'.+/[aA]rchiv.*', u'.+/Baustelle.*', u'.+/Index', u'.+/Spielwiese', u'.+/[tT]est.*', u'.*Diskussion:.+', u'Benutzer:.+/[Ll]og.*', u'Benutzer:C.Löser/.+', u'Benutzer:Katharina/Begriffsklärungen', u'Benutzer:Kirschblut/.+buchstabenkürzel', u'Benutzer:Mathias Schindler/.+', u'Benutzer:Noisper/Dingliste/[A-Z]', u'Benutzer:Professor Einstein.*', u'Benutzer:Sebbot/.+', u'Benutzer:SirJective/.+', u'Benutzer:Srbauer.*', u'Benutzer:SteEis.', u'Benutzer:Steindy.*', u'Benutzer:SrbBot.*', u'Benutzer:PortalBot/.+', u'Benutzer:Xqbot/.+', u'Lehnwort', u'Liste griechischer Wortstämme in deutschen Fremdwörtern', u'Liste von Gräzismen', u'Portal:Abkürzungen/.+', u'Portal:Astronomie/Moves', u'Portal:Astronomie/Index/.+', u'Portal:Hund', u'Portal:Hund/Beobachtungsliste', u'Portal:Marxismus', u'Portal:Täuferbewegung/Seitenindex', u'Wikipedia:Administratoren/Anfragen', u'Wikipedia:Archiv/.+', u'Wikipedia:Artikelwünsche/Ding-Liste/[A-Z]', u'Wikipedia:Begriffsklärung.*', u'Wikipedia:Bots/.+', u'Wikipedia:Interwiki-Konflikte', u'Wikipedia:ISBN-Suche', u'Wikipedia:Liste mathematischer Themen/BKS', u'Wikipedia:Liste mathematischer Themen/Redirects', u'Wikipedia:Meinungsbilder/.+', u'Wikipedia:Löschkandidaten/.+', u'Wikipedia:WikiProjekt Altertumswissenschaft/.+', u'Wikipedia:WikiProjekt Verwaiste Seiten/Begriffsklärungen', u'Wikipedia:Qualitätssicherung/.+', u'Vorlage:Infobox Weltraum', u'Vorlage:Navigationsleiste Raumfahrt', ], 'en': [ u'Wikipedia:Links to disambiguating pages', u'Wikipedia:Disambiguation pages with links', u'Wikipedia:Multiple-place names \\([A-Z]\\)', u'Wikipedia:Non-unique personal name', u"User:Jerzy/Disambiguation Pages i've Editted", u'User:Gareth Owen/inprogress', u'TLAs from [A-Z][A-Z][A-Z] to [A-Z][A-Z][A-Z]', u'List of all two-letter combinations', u'User:Daniel Quinlan/redirects.+', u'User:Oliver Pereira/stuff', u'Wikipedia:French Wikipedia language links', u'Wikipedia:Polish language links', u'Wikipedia:Undisambiguated abbreviations/.+', u'List of acronyms and initialisms', u'Wikipedia:Usemod article histories', u'User:Pizza Puzzle/stuff', u'List of generic names of political parties', u'Talk:List of initialisms/marked', u'Talk:List of initialisms/sorted', u'Talk:Programming language', u'Talk:SAMPA/To do', u"Wikipedia:Outline of Roget's Thesaurus", u'User:Wik/Articles', u'User:Egil/Sandbox', u'Wikipedia talk:Make only links relevant to the context', u'Wikipedia:Common words, searching for which is not possible', ], 'fa': [ u'ویکی‌پدیا:فهرست صفحات ابهام‌زدایی', ], 'fi': [ u'Wikipedia:Luettelo täsmennyssivuista', u'Wikipedia:Luettelo (täsmennyssivuista)', u'Wikipedia:Täsmennyssivu', ], 'fr': [ u'Wikipédia:Liens aux pages d’homonymie', u'Wikipédia:Homonymie', u'Wikipédia:Homonymie/Homonymes dynastiques', 'Wikipédia:Prise de décision, noms des membres ' 'de dynasties/liste des dynastiens', u'Liste de toutes les combinaisons de deux lettres', u'Wikipédia:Log d’upload/.*', u'Sigles de trois lettres de [A-Z]AA à [A-Z]ZZ', u'Wikipédia:Pages sans interwiki,.' ], 'fy': [ u'Wikipedy:Fangnet', ], 'hu': [ # hu:Wikipédia:Kocsmafal (egyéb)#Hol nem kell egyértelműsíteni? # 2012-02-08 u'Wikipédia:(?!Sportműhely/Eddigi cikkeink).*', u'.*\\(egyértelműsítő lap\\)$', u'.*[Vv]ita:.*', u'Szerkesztő:[^/]+$', ], 'ia': [ u'Categoria:Disambiguation', u'Wikipedia:.+', u'Usator:.+', u'Discussion Usator:.+', ], 'it': [ u'Aiuto:Disambigua/Disorfanamento', u'Discussioni utente:.+', u'Utente:Civvì/disorfanamento', ], 'kk': [ u'Санат:Айрықты бет', ], 'ko': [ u'위키백과:(동음이의) 문서의 목록', u'위키백과:동음이의어 문서의 목록', ], 'lt': [ u'Wikipedia:Rodomi nukreipiamieji straipsniai', ], 'nl': [ u"Gebruiker:.*", u"Overleg gebruiker:.+[aA]rchief.*", u"Overleg gebruiker:Pven", u"Portaal:.+[aA]rchief.*", u"Wikipedia:Humor en onzin.*", u"Wikipedia:Links naar doorverwijspagina's/Winkeldochters.*", u"Wikipedia:Project aanmelding bij startpagina's", u"Wikipedia:Wikiproject Roemeense gemeenten/Doorverwijspagina's", u'Categorie:Doorverwijspagina', u'Lijst van Nederlandse namen van pausen', u'Overleg Wikipedia:Discussie spelling 2005', u'Overleg Wikipedia:Doorverwijspagina', u'Overleg Wikipedia:Logboek.*', u'Wikipedia:Logboek.*', u'Overleg gebruiker:Sybren/test.*', u'Overleg gebruiker:([0-9][0-9]?[0-9]?\\.){3}[0-9][0-9]?[0-9]?', u'Overleg:Lage Landen (staatkunde)', u'Wikipedia:.*[aA]rchief.*', u'Wikipedia:Doorverwijspagina', u'Wikipedia:Lijst van alle tweeletter-combinaties', u'Wikipedia:Onderhoudspagina', u'Wikipedia:Ongelijke redirects', u'Wikipedia:Protection log', u'Wikipedia:Te verwijderen.*', u'Wikipedia:Top 1000 van meest bekeken artikelen', u'Wikipedia:Wikipedianen met een encyclopedisch artikel', u'Wikipedia:Woorden die niet als zoekterm gebruikt kunnen worden', u'Overleg gebruiker:Taka(/.*)?', u"Wikipedia:Links naar doorverwijspagina's/Artikelen", u"Wikipedia:Wikiproject/Redirects/.*", u"Wikipedia:Wikiproject/Muziek/Overzicht/.*", u"Wikipedia:Wikiproject/Roemeense gemeenten/Doorverwijspagina's", u"Overleg Wikipedia:Wikiproject/Redirects.*", u"Wikipedia:Links naar doorverwijspagina's/Amsterdamconstructie", ], 'pl': [ u'Wikipedysta:.+', u'Dyskusja.+:.+', ], 'pt': [ u'Usuário:.+', u'Usuário Discussão:.+', u'Discussão:.+', u'Lista de combinações de duas letras', u'Wikipedia:Lista de páginas de desambiguação.+', u'Wikipedia:Páginas para eliminar/.+', ], 'ru': [ u'Категория:Disambig', u'Википедия:Страницы разрешения неоднозначностей', u'Википедия:Вики-уборка/Статьи без языковых ссылок', u'Википедия:Страницы с пометкой «(значения)»', u'Список общерусских фамилий', ], }, 'memoryalpha': { 'en': [ u'Memory Alpha:Links to disambiguating pages' ], 'de': [ u'Memory Alpha:Liste der Wortklärungsseiten' ], }, } def correctcap(link, text): """Return the link capitalized/uncapitalized according to the text. @param link: link page @type link: pywikibot.Page @param text: the wikitext that is supposed to refer to the link @type text: str @return: uncapitalized title of the link if the text links to the link with an uncapitalized title, else capitalized @rtype: str """ linkupper = link.title() linklower = first_lower(linkupper) if "[[%s]]" % linklower in text or "[[%s|" % linklower in text: return linklower else: return linkupper class ReferringPageGeneratorWithIgnore(object): """Referring Page generator, with an ignore manager.""" def __init__(self, disambPage, primary=False, minimum=0, main_only=False): """Constructor. @type disambPage: pywikibot.Page @type primary: bool @type minimum: int @type main_only: bool @rtype: None """ self.disambPage = disambPage # if run with the -primary argument, enable the ignore manager self.primaryIgnoreManager = PrimaryIgnoreManager(disambPage, enabled=primary) self.minimum = minimum self.main_only = main_only def __iter__(self): """Yield pages.""" # TODO: start yielding before all referring pages have been found refs = [ page for page in self.disambPage.getReferences( follow_redirects=False, withTemplateInclusion=False, namespaces=0 if self.main_only else None ) ] pywikibot.output(u"Found %d references." % len(refs)) # Remove ignorables if self.disambPage.site.family.name in ignore_title and \ self.disambPage.site.lang in ignore_title[ self.disambPage.site.family.name]: for ig in ignore_title[self.disambPage.site.family.name ][self.disambPage.site.lang]: for i in range(len(refs) - 1, -1, -1): if re.match(ig, refs[i].title()): pywikibot.log(u'Ignoring page %s' % refs[i].title()) del refs[i] elif self.primaryIgnoreManager.isIgnored(refs[i]): del refs[i] if len(refs) < self.minimum: pywikibot.output(u"Found only %d pages to work on; skipping." % len(refs)) return pywikibot.output(u"Will work on %d pages." % len(refs)) for ref in refs: yield ref class PrimaryIgnoreManager(object): """ Primary ignore manager. If run with the -primary argument, reads from a file which pages should not be worked on; these are the ones where the user pressed n last time. If run without the -primary argument, doesn't ignore any pages. """ def __init__(self, disambPage, enabled=False): """Constructor. @type disambPage: pywikibot.Page @type enabled: bool @rtype: None """ self.disambPage = disambPage self.enabled = enabled self.ignorelist = [] folder = config.datafilepath('disambiguations') if os.path.exists(folder): self._read_ignorelist(folder) def _read_ignorelist(self, folder): """Read pages to be ignored from file. @type folder: str @rtype: None """ filename = os.path.join( folder, self.disambPage.title(as_filename=True) + '.txt') try: # The file is stored in the disambiguation/ subdir. # Create if necessary. f = codecs.open(filename, 'r', 'utf-8') for line in f.readlines(): # remove trailing newlines and carriage returns while line[-1] in ['\n', '\r']: line = line[:-1] # skip empty lines if line != '': self.ignorelist.append(line) f.close() except IOError: pass def isIgnored(self, refPage): """Return if refPage is to be ignored. @type refPage: pywikibot.Page @rtype: bool """ return self.enabled and refPage.title(asUrl=True) in self.ignorelist def ignore(self, refPage): """Write page to ignorelist. @type refPage: pywikibot.Page @rtype: None """ if self.enabled: # Skip this occurrence next time. filename = config.datafilepath( 'disambiguations', self.disambPage.title(asUrl=True) + '.txt') try: # Open file for appending. If none exists, create a new one. f = codecs.open(filename, 'a', 'utf-8') f.write(refPage.title(asUrl=True) + '\n') f.close() except IOError: pass class AddAlternativeOption(OutputProxyOption): """Add a new alternative.""" def result(self, value): """Add the alternative and then list them.""" newAlternative = pywikibot.input(u'New alternative:') self._outputter.sequence.append(newAlternative) super(AddAlternativeOption, self).result(value) class EditOption(StandardOption): """Edit the text.""" def __init__(self, option, shortcut, text, start, title): """Constructor. @type option: str @type shortcut: str @type text: str @type start: int @type title: str @rtype: None """ super(EditOption, self).__init__(option, shortcut) self._text = text self._start = start self._title = title @property def stop(self): """Return whether if user didn't press cancel and changed it. @rtype: bool """ return self.new_text and self.new_text != self._text def result(self, value): """Open a text editor and let the user change it.""" editor = editarticle.TextEditor() self.new_text = editor.edit(self._text, jumpIndex=self._start, highlight=self._title) return super(EditOption, self).result(value) class ShowPageOption(StandardOption): """Show the page's contents in an editor.""" def __init__(self, option, shortcut, start, page): """Constructor.""" super(ShowPageOption, self).__init__(option, shortcut, False) self._start = start if page.isRedirectPage(): page = page.getRedirectTarget() self._page = page def result(self, value): """Open a text editor and show the text.""" editor = editarticle.TextEditor() editor.edit(self._page.text, jumpIndex=self._start, highlight=self._page.title()) class AliasOption(StandardOption): """An option allowing multiple aliases which also select it.""" def __init__(self, option, shortcuts, stop=True): """Constructor.""" super(AliasOption, self).__init__(option, shortcuts[0], stop) self._aliases = frozenset(s.lower() for s in shortcuts[1:]) def test(self, value): """Test aliases and combine it with the original test.""" return value.lower() in self._aliases or super(AliasOption, self).test(value) class DisambiguationRobot(Bot): """Disambiguation bot.""" ignore_contents = { 'de': (u'{{[Ii]nuse}}', u'{{[Ll]öschen}}', ), 'fi': (u'{{[Tt]yöstetään}}', ), 'kk': (u'{{[Ii]nuse}}', u'{{[Pp]rocessing}}', ), 'nl': (u'{{wiu2}}', u'{{nuweg}}', ), 'ru': (u'{{[Ii]nuse}}', u'{{[Pp]rocessing}}', ), } primary_redir_template = { # Page.templates() format, first letter uppercase 'hu': u'Egyért-redir', } def __init__(self, always, alternatives, getAlternatives, dnSkip, generator, primary, main_only, minimum=0): """Constructor.""" super(DisambiguationRobot, self).__init__() self.always = always self.alternatives = alternatives self.getAlternatives = getAlternatives self.dnSkip = dnSkip self.generator = generator self.primary = primary self.main_only = main_only self.minimum = minimum self.site = self.mysite = pywikibot.Site() self.mylang = self.mysite.lang self.comment = None self.dn_template_str = i18n.translate(self.mysite, dn_template) self.setupRegexes() def checkContents(self, text): """ Check if the text matches any of the ignore regexes. For a given text, returns False if none of the regular expressions given in the dictionary at the top of this class matches a substring of the text. Otherwise returns the substring which is matched by one of the regular expressions. """ for ig in self.ignore_contents_regexes: match = ig.search(text) if match: return match.group() return None def makeAlternativesUnique(self): """Remove duplicate items from self.alternatives. Preserve the order of alternatives. @rtype: None """ seen = set() self.alternatives = [ i for i in self.alternatives if i not in seen and not seen.add(i) ] def listAlternatives(self): """Show a list of alternatives.""" list = u'\n' for i in range(len(self.alternatives)): list += (u"%3i - %s\n" % (i, self.alternatives[i])) pywikibot.output(list) def setupRegexes(self): """Compile regular expressions.""" self.ignore_contents_regexes = [] if self.mylang in self.ignore_contents: for ig in self.ignore_contents[self.mylang]: self.ignore_contents_regexes.append(re.compile(ig)) linktrail = self.mysite.linktrail() self.trailR = re.compile(linktrail) # The regular expression which finds links. Results consist of four # groups: # group title is the target page title, that is, everything before # | or ]. # group section is the page section. It'll include the # to make life # easier for us. # group label is the alternative link title, that's everything # between | and ]. # group linktrail is the link trail, that's letters after ]] which # are part of the word. # note: the definition of 'letter' varies from language to language. self.linkR = re.compile(r''' \[\[ (?P<title> [^\[\]\|#]*) (?P<section> \#[^\]\|]*)? (\|(?P<label> [^\]]*))? \]\] (?P<linktrail>%s)''' % linktrail, flags=re.X) def treat(self, refPage, disambPage): """Treat a page. @param disambPage: the disambiguation page or redirect we don't want anything to link to @type disambPage: pywikibot.Page @param refPage: a page linking to disambPage @type refPage: pywikibot.Page @return: False if the user pressed q to completely quit the program, True otherwise @rtype: bool """ # TODO: break this function up into subroutines! self.current_page = refPage include = False unlink_counter = 0 new_targets = [] try: text = refPage.get() ignoreReason = self.checkContents(text) if ignoreReason: pywikibot.output('\n\nSkipping %s because it contains %s.\n\n' % (refPage.title(), ignoreReason)) else: include = True except pywikibot.IsRedirectPage: pywikibot.output(u'%s is a redirect to %s' % (refPage.title(), disambPage.title())) if disambPage.isRedirectPage(): target = self.alternatives[0] if pywikibot.input_yn(u'Do you want to make redirect %s point ' 'to %s?' % (refPage.title(), target), default=False, automatic_quit=False): redir_text = '#%s [[%s]]' \ % (self.mysite.redirect(), target) try: refPage.put_async(redir_text, summary=self.comment) except pywikibot.PageNotSaved as error: pywikibot.output(u'Page not saved: %s' % error.args) else: choice = pywikibot.input_choice( u'Do you want to work on pages linking to %s?' % refPage.title(), [('yes', 'y'), ('no', 'n'), ('change redirect', 'c')], 'n', automatic_quit=False) if choice == 'y': gen = ReferringPageGeneratorWithIgnore( refPage, self.primary, main_only=self.main_only ) preloadingGen = pagegenerators.PreloadingGenerator(gen) for refPage2 in preloadingGen: # run until the user selected 'quit' if not self.treat(refPage2, refPage): break elif choice == 'c': text = refPage.get(get_redirect=True) include = "redirect" except pywikibot.NoPage: pywikibot.output( u'Page [[%s]] does not seem to exist?! Skipping.' % refPage.title()) include = False if include in (True, "redirect"): # save the original text so we can show the changes later original_text = text n = 0 curpos = 0 dn = False edited = False # This loop will run until we have finished the current page while True: m = self.linkR.search(text, pos=curpos) if not m: if n == 0: pywikibot.output(u"No changes necessary in %s" % refPage.title()) return True else: # stop loop and save page break # Ensure that next time around we will not find this same hit. curpos = m.start() + 1 try: foundlink = pywikibot.Link(m.group('title'), disambPage.site) foundlink.parse() except pywikibot.Error: continue # ignore interwiki links if foundlink.site != disambPage.site: continue # Check whether the link found is to disambPage. try: if foundlink.canonical_title() != disambPage.title(): continue except pywikibot.Error: # must be a broken link pywikibot.log(u"Invalid link [[%s]] in page [[%s]]" % (m.group('title'), refPage.title())) continue n += 1 # how many bytes should be displayed around the current link context = 60 # check if there's a dn-template here already if (self.dnSkip and self.dn_template_str and self.dn_template_str[:-2] in text[ m.end():m.end() + len(self.dn_template_str) + 8]): continue edit = EditOption('edit page', 'e', text, m.start(), disambPage.title()) context_option = HighlightContextOption( 'more context', 'm', text, 60, start=m.start(), end=m.end()) context_option.before_question = True options = [ListOption(self.alternatives, ''), ListOption(self.alternatives, 'r'), StandardOption('skip link', 's'), edit, StandardOption('next page', 'n'), StandardOption('unlink', 'u')] if self.dn_template_str: # '?', '/' for old choice options += [AliasOption('tag template %s' % self.dn_template_str, ['t', '?', '/'])] options += [context_option] if not edited: options += [ShowPageOption('show disambiguation page', 'd', m.start(), disambPage)] options += [ OutputProxyOption('list', 'l', SequenceOutputter(self.alternatives)), AddAlternativeOption('add new', 'a', SequenceOutputter(self.alternatives))] if edited: options += [StandardOption('save in this form', 'x')] # TODO: Output context on each question answer = pywikibot.input_choice('Option', options, default=self.always, force=bool(self.always)) if answer == 'x': assert edited, 'invalid option before editing' break elif answer == 's': n -= 1 # TODO what's this for? continue elif answer == 'e': text = edit.new_text edited = True curpos = 0 continue elif answer == 'n': # skip this page if self.primary: # If run with the -primary argument, skip this # occurrence next time. self.primaryIgnoreManager.ignore(refPage) return True # The link looks like this: # [[page_title|link_text]]trailing_chars page_title = m.group('title') link_text = m.group('label') if not link_text: # or like this: [[page_title]]trailing_chars link_text = page_title if m.group('section') is None: section = '' else: section = m.group('section') trailing_chars = m.group('linktrail') if trailing_chars: link_text += trailing_chars if answer == 't': assert self.dn_template_str # small chunk of text to search search_text = text[m.end():m.end() + context] # figure out where the link (and sentance) ends, put note # there end_of_word_match = re.search(r'\s', search_text) if end_of_word_match: position_split = end_of_word_match.start(0) else: position_split = 0 # insert dab needed template text = (text[:m.end() + position_split] + self.dn_template_str + text[m.end() + position_split:]) dn = True continue elif answer == 'u': # unlink - we remove the section if there's any text = text[:m.start()] + link_text + text[m.end():] unlink_counter += 1 continue else: # Check that no option from above was missed assert isinstance(answer, tuple), 'only tuple answer left.' assert answer[0] in ['r', ''], 'only valid tuple answers.' if answer[0] == 'r': # we want to throw away the original link text replaceit = link_text == page_title elif include == "redirect": replaceit = True else: replaceit = False new_page_title = answer[1] repPl = pywikibot.Page(pywikibot.Link(new_page_title, disambPage.site)) if (new_page_title[0].isupper() or link_text[0].isupper()): new_page_title = repPl.title() else: new_page_title = repPl.title() new_page_title = first_lower(new_page_title) if new_page_title not in new_targets: new_targets.append(new_page_title) if replaceit and trailing_chars: newlink = "[[%s%s]]%s" % (new_page_title, section, trailing_chars) elif replaceit or (new_page_title == link_text and not section): newlink = "[[%s]]" % new_page_title # check if we can create a link with trailing characters # instead of a pipelink elif ( (len(new_page_title) <= len(link_text)) and (firstcap(link_text[:len(new_page_title)]) == firstcap(new_page_title)) and (re.sub(self.trailR, '', link_text[len(new_page_title):]) == '') and (not section) ): newlink = "[[%s]]%s" \ % (link_text[:len(new_page_title)], link_text[len(new_page_title):]) else: newlink = "[[%s%s|%s]]" \ % (new_page_title, section, link_text) text = text[:m.start()] + newlink + text[m.end():] continue pywikibot.output(text[max(0, m.start() - 30):m.end() + 30]) if text == original_text: pywikibot.output(u'\nNo changes have been made:\n') else: pywikibot.output(u'\nThe following changes have been made:\n') pywikibot.showDiff(original_text, text) pywikibot.output(u'') # save the page self.setSummaryMessage(disambPage, new_targets, unlink_counter, dn) try: refPage.put_async(text, summary=self.comment) except pywikibot.LockedPage: pywikibot.output(u'Page not saved: page is locked') except pywikibot.PageNotSaved as error: pywikibot.output(u'Page not saved: %s' % error.args) return True def findAlternatives(self, disambPage): """Extend self.alternatives using correctcap of disambPage.linkedPages. @param disambPage: the disambiguation page @type disambPage: pywikibot.Page @return: True if everything goes fine, False otherwise @rtype: bool """ if disambPage.isRedirectPage() and not self.primary: if (disambPage.site.lang in self.primary_redir_template and self.primary_redir_template[disambPage.site.lang] in disambPage.templates(get_redirect=True)): baseTerm = disambPage.title() for template in disambPage.templatesWithParams( get_redirect=True): if template[0] == self.primary_redir_template[ disambPage.site.lang] \ and len(template[1]) > 0: baseTerm = template[1][1] disambTitle = primary_topic_format[self.mylang] % baseTerm try: disambPage2 = pywikibot.Page( pywikibot.Link(disambTitle, self.mysite)) links = disambPage2.linkedPages() links = [correctcap(l, disambPage2.get()) for l in links] except pywikibot.NoPage: pywikibot.output(u"No page at %s, using redirect target." % disambTitle) links = disambPage.linkedPages()[:1] links = [correctcap(l, disambPage.get(get_redirect=True)) for l in links] self.alternatives += links else: try: target = disambPage.getRedirectTarget().title() self.alternatives.append(target) except pywikibot.NoPage: pywikibot.output(u"The specified page was not found.") user_input = pywikibot.input(u"""\ Please enter the name of the page where the redirect should have pointed at, or press enter to quit:""") if user_input == "": self.quit() else: self.alternatives.append(user_input) except pywikibot.IsNotRedirectPage: pywikibot.output( u"The specified page is not a redirect. Skipping.") return False elif self.getAlternatives: # not disambPage.isRedirectPage() or self.primary try: if self.primary: try: disambPage2 = pywikibot.Page( pywikibot.Link( primary_topic_format[self.mylang] % disambPage.title(), self.mysite)) links = disambPage2.linkedPages() links = [correctcap(l, disambPage2.get()) for l in links] except pywikibot.NoPage: pywikibot.output( 'Page does not exist; using first link in page %s.' % disambPage.title()) links = disambPage.linkedPages()[:1] links = [correctcap(l, disambPage.get()) for l in links] else: try: links = disambPage.linkedPages() links = [correctcap(l, disambPage.get()) for l in links] except pywikibot.NoPage: pywikibot.output(u"Page does not exist, skipping.") return False except pywikibot.IsRedirectPage: pywikibot.output(u"Page is a redirect, skipping.") return False self.alternatives += links return True def setSummaryMessage(self, disambPage, new_targets=[], unlink_counter=0, dn=False): """Setup i18n summary message.""" # make list of new targets comma = self.mysite.mediawiki_message(u"comma-separator") targets = comma.join(u'[[%s]]' % page_title for page_title in new_targets) if not targets: targets = i18n.twtranslate(self.mysite, 'solve_disambiguation-unknown-page') # first check whether user has customized the edit comment if (self.mysite.family.name in config.disambiguation_comment and self.mylang in config.disambiguation_comment[ self.mysite.family.name]): try: self.comment = i18n.translate( self.mysite, config.disambiguation_comment[self.mysite.family.name], fallback=True) % (disambPage.title(), targets) # Backwards compatibility, type error probably caused by too # many arguments for format string except TypeError: self.comment = i18n.translate( self.mysite, config.disambiguation_comment[self.mysite.family.name], fallback=True) % disambPage.title() elif disambPage.isRedirectPage(): # when working on redirects, there's another summary message if unlink_counter and not new_targets: self.comment = i18n.twtranslate( self.mysite, 'solve_disambiguation-redirect-removed', {'from': disambPage.title(), 'count': unlink_counter}) elif dn and not new_targets: self.comment = i18n.twtranslate( self.mysite, 'solve_disambiguation-redirect-adding-dn-template', {'from': disambPage.title()}) else: self.comment = i18n.twtranslate( self.mysite, 'solve_disambiguation-redirect-resolved', {'from': disambPage.title(), 'to': targets, 'count': len(new_targets)}) else: if unlink_counter and not new_targets: self.comment = i18n.twtranslate( self.mysite, 'solve_disambiguation-links-removed', {'from': disambPage.title(), 'count': unlink_counter}) elif dn and not new_targets: self.comment = i18n.twtranslate( self.mysite, 'solve_disambiguation-adding-dn-template', {'from': disambPage.title()}) else: self.comment = i18n.twtranslate( self.mysite, 'solve_disambiguation-links-resolved', {'from': disambPage.title(), 'to': targets, 'count': len(new_targets)}) def run(self): """Run the bot.""" for disambPage in self.generator: self.primaryIgnoreManager = PrimaryIgnoreManager( disambPage, enabled=self.primary) if not self.findAlternatives(disambPage): continue pywikibot.output('\nAlternatives for %s' % disambPage) self.makeAlternativesUnique() # sort possible choices if config.sort_ignore_case: self.alternatives.sort(key=lambda x: x.lower()) else: self.alternatives.sort() SequenceOutputter(self.alternatives).output() gen = ReferringPageGeneratorWithIgnore( disambPage, self.primary, minimum=self.minimum, main_only=self.main_only ) preloadingGen = pagegenerators.PreloadingGenerator(gen) for refPage in preloadingGen: if not self.primaryIgnoreManager.isIgnored(refPage): try: self.treat(refPage, disambPage) except QuitKeyboardInterrupt: pywikibot.output('\nUser quit %s bot run...' % self.__class__.__name__) return # clear alternatives before working on next disambiguation page self.alternatives = [] def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ # the option that's always selected when the bot wonders what to do with # a link. If it's None, the user is prompted (default behaviour). always = None alternatives = [] getAlternatives = True dnSkip = False generator = None primary = False main_only = False # For sorting the linked pages, case can be ignored minimum = 0 local_args = pywikibot.handle_args(args) generator_factory = pagegenerators.GeneratorFactory( positional_arg_name='page') for arg in local_args: if arg.startswith('-primary:'): primary = True getAlternatives = False alternatives.append(arg[9:]) elif arg == '-primary': primary = True elif arg.startswith('-always:'): always = arg[8:] elif arg.startswith('-pos:'): if arg[5] != ':': mysite = pywikibot.Site() page = pywikibot.Page(pywikibot.Link(arg[5:], mysite)) if page.exists(): alternatives.append(page.title()) else: if pywikibot.input_yn( u'Possibility %s does not actually exist. Use it ' 'anyway?' % page.title(), default=False, automatic_quit=False): alternatives.append(page.title()) else: alternatives.append(arg[5:]) elif arg == '-just': getAlternatives = False elif arg == '-dnskip': dnSkip = True elif arg == '-main': main_only = True elif arg.startswith('-min:'): minimum = int(arg[5:]) elif arg.startswith('-start'): try: generator = pagegenerators.CategorizedPageGenerator( pywikibot.Site().disambcategory(), start=arg[7:], namespaces=[0]) except pywikibot.NoPage: pywikibot.output( 'Disambiguation category for your wiki is not known.') raise else: generator_factory.handleArg(arg) site = pywikibot.Site() generator = generator_factory.getCombinedGenerator(generator) if not generator: pywikibot.bot.suggest_help(missing_generator=True) return False site.login() bot = DisambiguationRobot(always, alternatives, getAlternatives, dnSkip, generator, primary, main_only, minimum=minimum) bot.run() if __name__ == "__main__": main()
skirsdeda/django
refs/heads/master
django/contrib/sitemaps/tests/test_https.py
21
from __future__ import unicode_literals from datetime import date import warnings from django.test import override_settings from django.utils.deprecation import RemovedInDjango20Warning from .base import SitemapTestsBase @override_settings(ROOT_URLCONF='django.contrib.sitemaps.tests.urls.https') class HTTPSSitemapTests(SitemapTestsBase): protocol = 'https' def test_secure_sitemap_index(self): "A secure sitemap index can be rendered" with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) # The URL for views.sitemap in tests/urls/https.py has been updated # with a name but since reversing by Python path is tried first # before reversing by name and works since we're giving # name='django.contrib.sitemaps.views.sitemap', we need to silence # the erroneous warning until reversing by dotted path is removed. # The test will work without modification when it's removed. response = self.client.get('/secure/index.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>%s/secure/sitemap-simple.xml</loc></sitemap> </sitemapindex> """ % self.base_url self.assertXMLEqual(response.content.decode('utf-8'), expected_content) def test_secure_sitemap_section(self): "A secure sitemap section can be rendered" response = self.client.get('/secure/sitemap-simple.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url> </urlset> """ % (self.base_url, date.today()) self.assertXMLEqual(response.content.decode('utf-8'), expected_content) @override_settings(SECURE_PROXY_SSL_HEADER=False) class HTTPSDetectionSitemapTests(SitemapTestsBase): extra = {'wsgi.url_scheme': 'https'} def test_sitemap_index_with_https_request(self): "A sitemap index requested in HTTPS is rendered with HTTPS links" with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) # The URL for views.sitemap in tests/urls/https.py has been updated # with a name but since reversing by Python path is tried first # before reversing by name and works since we're giving # name='django.contrib.sitemaps.views.sitemap', we need to silence # the erroneous warning until reversing by dotted path is removed. # The test will work without modification when it's removed. response = self.client.get('/simple/index.xml', **self.extra) expected_content = """<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap> </sitemapindex> """ % self.base_url.replace('http://', 'https://') self.assertXMLEqual(response.content.decode('utf-8'), expected_content) def test_sitemap_section_with_https_request(self): "A sitemap section requested in HTTPS is rendered with HTTPS links" response = self.client.get('/simple/sitemap-simple.xml', **self.extra) expected_content = """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url> </urlset> """ % (self.base_url.replace('http://', 'https://'), date.today()) self.assertXMLEqual(response.content.decode('utf-8'), expected_content)
minjay/Stuff
refs/heads/master
Lecture_Code/Big_Data/MapReduce/example2/reducer.py
6
#!/usr/bin/env python from operator import itemgetter import sys # Hideously ugly reduce example current_sum = 0.0 current_group = None current_count = 0 verbose = False # input comes from STDIN for line in sys.stdin: # Remove trailing '\n' line = line.strip() # Extract (key,value) vs = line.split('\t') if (len(vs) != 2): print "vs not of length 2: " + str(vs) else: tmp_group = int(vs[0]) if tmp_group == current_group: current_count = current_count + 1 current_sum = current_sum + float(vs[1]) else: if (current_count != 0): current_mean = current_sum / float(current_count) else: current_mean = float("inf") if not (current_group is None): if verbose: print "group: " + str(current_group) + "; sum: " + str(current_sum) + "; count: " + str(current_count) + "; mean: " + str(current_mean) out_str = '{:03n}'.format(current_group) + "\t" + str(current_mean) print out_str current_group = int(tmp_group) current_sum = float(vs[1]) current_count = 1 # Last one: if verbose: print "group: " + str(current_group) + "; sum: " + str(current_sum) + "; count: " + str(current_count) + "; mean: " + str(current_mean) current_mean = current_sum / float(current_count) out_str = '{:03n}'.format(current_group) + "\t" + str(current_mean) print out_str
enjaz/enjaz
refs/heads/master
newhpc/migrations/0008_add_files.py
2
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('newhpc', '0007_merge'), ] operations = [ migrations.AddField( model_name='previousversion', name='speaker_file', field=models.ImageField(upload_to=b'newhpc/previous/speaker/file', null=True, verbose_name=b'\xd9\x85\xd9\x84\xd9\x81 \xd8\xa7\xd9\x84\xd9\x85\xd8\xaa\xd8\xad\xd8\xaf\xd8\xab\xd9\x8a\xd9\x86', blank=True), ), migrations.AddField( model_name='previousversion', name='winner_file', field=models.ImageField(upload_to=b'newhpc/previous/winner/file', null=True, verbose_name=b'\xd9\x85\xd9\x84\xd9\x81 \xd8\xa7\xd9\x84\xd9\x81\xd8\xa7\xd8\xa6\xd8\xb2\xd9\x8a\xd9\x86', blank=True), ), ]
bennojoy/ansible
refs/heads/devel
lib/ansible/template/__init__.py
5
# (c) 2012-2014, Michael DeHaan <michael.dehaan@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/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re from jinja2 import Environment from jinja2.exceptions import TemplateSyntaxError, UndefinedError from jinja2.utils import concat as j2_concat from jinja2.runtime import StrictUndefined from ansible import constants as C from ansible.errors import AnsibleError, AnsibleFilterError, AnsibleUndefinedVariable from ansible.plugins import filter_loader, lookup_loader from ansible.template.safe_eval import safe_eval from ansible.template.template import AnsibleJ2Template from ansible.template.vars import AnsibleJ2Vars from ansible.utils.debug import debug from numbers import Number __all__ = ['Templar'] # A regex for checking to see if a variable we're trying to # expand is just a single variable name. # Primitive Types which we don't want Jinja to convert to strings. NON_TEMPLATED_TYPES = ( bool, Number ) JINJA2_OVERRIDE = '#jinja2:' JINJA2_ALLOWED_OVERRIDES = frozenset(['trim_blocks', 'lstrip_blocks', 'newline_sequence', 'keep_trailing_newline']) class Templar: ''' The main class for templating, with the main entry-point of template(). ''' def __init__(self, loader, shared_loader_obj=None, variables=dict()): self._loader = loader self._basedir = loader.get_basedir() self._filters = None self._available_variables = variables if shared_loader_obj: self._filter_loader = getattr(shared_loader_obj, 'filter_loader') self._lookup_loader = getattr(shared_loader_obj, 'lookup_loader') else: self._filter_loader = filter_loader self._lookup_loader = lookup_loader # flags to determine whether certain failures during templating # should result in fatal errors being raised self._fail_on_lookup_errors = True self._fail_on_filter_errors = True self._fail_on_undefined_errors = C.DEFAULT_UNDEFINED_VAR_BEHAVIOR self.environment = Environment(trim_blocks=True, undefined=StrictUndefined, extensions=self._get_extensions(), finalize=self._finalize) self.environment.template_class = AnsibleJ2Template self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string)) def _count_newlines_from_end(self, in_str): ''' Counts the number of newlines at the end of a string. This is used during the jinja2 templating to ensure the count matches the input, since some newlines may be thrown away during the templating. ''' i = len(in_str) while i > 0: if in_str[i-1] != '\n': break i -= 1 return len(in_str) - i def _get_filters(self): ''' Returns filter plugins, after loading and caching them if need be ''' if self._filters is not None: return self._filters.copy() plugins = [x for x in self._filter_loader.all()] self._filters = dict() for fp in plugins: self._filters.update(fp.filters()) return self._filters.copy() def _get_extensions(self): ''' Return jinja2 extensions to load. If some extensions are set via jinja_extensions in ansible.cfg, we try to load them with the jinja environment. ''' jinja_exts = [] if C.DEFAULT_JINJA2_EXTENSIONS: # make sure the configuration directive doesn't contain spaces # and split extensions in an array jinja_exts = C.DEFAULT_JINJA2_EXTENSIONS.replace(" ", "").split(',') return jinja_exts def set_available_variables(self, variables): ''' Sets the list of template variables this Templar instance will use to template things, so we don't have to pass them around between internal methods. ''' assert isinstance(variables, dict) self._available_variables = variables.copy() def template(self, variable, convert_bare=False, preserve_trailing_newlines=False, fail_on_undefined=None, overrides=None): ''' Templates (possibly recursively) any given data as input. If convert_bare is set to True, the given data will be wrapped as a jinja2 variable ('{{foo}}') before being sent through the template engine. ''' try: if convert_bare: variable = self._convert_bare_variable(variable) if isinstance(variable, basestring): result = variable if self._contains_vars(variable): # Check to see if the string we are trying to render is just referencing a single # var. In this case we don't want to accidentally change the type of the variable # to a string by using the jinja template renderer. We just want to pass it. only_one = self.SINGLE_VAR.match(variable) if only_one: var_name = only_one.group(1) if var_name in self._available_variables: resolved_val = self._available_variables[var_name] if isinstance(resolved_val, NON_TEMPLATED_TYPES): return resolved_val result = self._do_template(variable, preserve_trailing_newlines=preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides) # if this looks like a dictionary or list, convert it to such using the safe_eval method if (result.startswith("{") and not result.startswith(self.environment.variable_start_string)) or result.startswith("["): eval_results = safe_eval(result, locals=self._available_variables, include_exceptions=True) if eval_results[1] is None: result = eval_results[0] else: # FIXME: if the safe_eval raised an error, should we do something with it? pass return result elif isinstance(variable, (list, tuple)): return [self.template(v, convert_bare=convert_bare, preserve_trailing_newlines=preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides) for v in variable] elif isinstance(variable, dict): d = {} for (k, v) in variable.iteritems(): d[k] = self.template(v, convert_bare=convert_bare, preserve_trailing_newlines=preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides) return d else: return variable except AnsibleFilterError: if self._fail_on_filter_errors: raise else: return variable def _contains_vars(self, data): ''' returns True if the data contains a variable pattern ''' return self.environment.block_start_string in data or self.environment.variable_start_string in data def _convert_bare_variable(self, variable): ''' Wraps a bare string, which may have an attribute portion (ie. foo.bar) in jinja2 variable braces so that it is evaluated properly. ''' if isinstance(variable, basestring): first_part = variable.split(".")[0].split("[")[0] if first_part in self._available_variables and self.environment.variable_start_string not in variable: return "%s%s%s" % (self.environment.variable_start_string, variable, self.environment.variable_end_string) # the variable didn't meet the conditions to be converted, # so just return it as-is return variable def _finalize(self, thing): ''' A custom finalize method for jinja2, which prevents None from being returned ''' return thing if thing is not None else '' def _lookup(self, name, *args, **kwargs): instance = self._lookup_loader.get(name.lower(), loader=self._loader) if instance is not None: # safely catch run failures per #5059 try: ran = instance.run(*args, variables=self._available_variables, **kwargs) except (AnsibleUndefinedVariable, UndefinedError): raise except Exception, e: if self._fail_on_lookup_errors: raise ran = None if ran: ran = ",".join(ran) return ran else: raise AnsibleError("lookup plugin (%s) not found" % name) def _do_template(self, data, preserve_trailing_newlines=False, fail_on_undefined=None, overrides=None): if fail_on_undefined is None: fail_on_undefined = self._fail_on_undefined_errors try: # allows template header overrides to change jinja2 options. if overrides is None: myenv = self.environment.overlay() else: overrides = JINJA2_ALLOWED_OVERRIDES.intersection(set(overrides)) myenv = self.environment.overlay(overrides) #FIXME: add tests myenv.filters.update(self._get_filters()) try: t = myenv.from_string(data) except TemplateSyntaxError, e: raise AnsibleError("template error while templating string: %s" % str(e)) except Exception, e: if 'recursion' in str(e): raise AnsibleError("recursive loop detected in template string: %s" % data) else: return data t.globals['lookup'] = self._lookup t.globals['finalize'] = self._finalize jvars = AnsibleJ2Vars(self, t.globals) new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try: res = j2_concat(rf) except TypeError, te: if 'StrictUndefined' in str(te): raise AnsibleUndefinedVariable( "Unable to look up a name or access an attribute in template string. " + \ "Make sure your variable name does not contain invalid characters like '-'." ) else: debug("failing because of a type error, template data is: %s" % data) raise AnsibleError("an unexpected type error occurred. Error was %s" % te) if preserve_trailing_newlines: # The low level calls above do not preserve the newline # characters at the end of the input data, so we use the # calculate the difference in newlines and append them # to the resulting output for parity res_newlines = self._count_newlines_from_end(res) data_newlines = self._count_newlines_from_end(data) if data_newlines > res_newlines: res += '\n' * (data_newlines - res_newlines) return res except (UndefinedError, AnsibleUndefinedVariable), e: if fail_on_undefined: raise else: #TODO: return warning about undefined var return data
neurodata/synaptome-stats
refs/heads/gh-pages
collman14v2/201710/synaptogramCubes.py
1
#!/usr/bin/env python3 ### ### ### ### Jesse Leigh Patsolic ### 2017 <jpatsol1@jhu.edu> ### S.D.G # import argparse import math from intern.remote.boss import BossRemote from intern.resource.boss.resource import * import configparser #import grequests # for async requests, conflicts with requests somehow import requests import numpy as np from numpy import genfromtxt import h5py import matplotlib.pyplot as plt import matplotlib.image as mpimg import shutil import blosc from IPython.core.debugger import set_trace import sys import os import itertools from functools import partial from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool from multiprocessing import cpu_count import csv import datetime import morton import toolbox def main(COLL_NAME, EXP_NAME, COORD_FRAME, LOCATIONS, BF = [5,5,5], CHAN_NAMES=None, num_threads = 6, CONFIG_FILE= None): L = genfromtxt(LOCATIONS, delimiter=',', skip_header = 0, dtype='int32').tolist() m = morton.Morton(dimensions=3, bits=64) Lzo = sorted([m.pack(L[i][0], L[i][1], L[i][2]) for i in range(len(L))]) loc = np.asarray([m.unpack(l) for l in Lzo]) config = configparser.ConfigParser() config.read(CONFIG_FILE) TOKEN = config['Default']['token'] boss_url = ''.join( ( config['Default']['protocol'],'://',config['Default']['host'],'/v1/' ) ) #intern rem = BossRemote(CONFIG_FILE) cfr = rem.get_project(CoordinateFrameResource(COORD_FRAME)) ext = {'x': [cfr.x_start, cfr.x_stop], 'y': [cfr.y_start, cfr.y_stop], 'z': [cfr.z_start, cfr.z_stop]} ## remove coordinates that are outside buffer area. x_bnd = [np.all([x[0]-BF[0] >= ext['x'][0] , x[0]+BF[0] < ext['x'][1]]) for x in loc] y_bnd = [np.all([y[1]-BF[1] >= ext['y'][0] , y[1]+BF[1] < ext['y'][1]]) for y in loc] z_bnd = [np.all([z[2]-BF[2] >= ext['z'][0] , z[2]+BF[2] < ext['z'][1]]) for z in loc] xyzbnd = np.asarray([np.all([x_bnd[i], y_bnd[i], z_bnd[i]]) for i in range(len(x_bnd))]) ## Select only locations that are buffered away from the edge. loc = loc[xyzbnd] ## Compute the buffered ranges x_rng = [[x[0]-BF[0], x[0]+BF[0]+1] for x in loc] y_rng = [[y[1]-BF[1], y[1]+BF[1]+1] for y in loc] z_rng = [[z[2]-BF[2], z[2]+BF[2]+1] for z in loc] ChanList = [] for ch in CHAN_NAMES: di = [{ 'rem': rem, 'ch_rsc': ChannelResource(ch,COLL_NAME,EXP_NAME,'image',datatype='uint8'), 'ch' : ch, 'res' : 0, 'loc' : loc[i], 'xrng': x_rng[i], 'yrng': y_rng[i], 'zrng': z_rng[i], 'bf' : BF } for i in range(len(loc))] with ThreadPool(num_threads) as tp: out = tp.map(toolbox.getCube, di) print(ch) ##DEBUG sys.stdout.flush() #DEBUG ChanList.append(np.asarray(out)) outArray = np.asarray(ChanList) ## outArray will be a numpy array in [channel, synapse, z, y, x] order ## this is C-ordering return(outArray, loc) ## END MAIN def driveMain(): COLL_NAME = 'collman' EXP_NAME = 'collman14v2' COORD_FRAME = 'collman_collman14v2' #LOCATIONS_FILE = 'meda_plots_tight/hmcC5synaptogramLocations.csv' #LOCATIONS_FILE = 'ZeroAnnotations.csv' LOCATIONS_FILE = 'meda_plots_gaussian/hmcC5synaptogramLocations.csv' BF = [108,108,5] OUTPUT = 'meda_plots_gaussian/collman14v2_gaussianSynaptograms.csv' CONFIG_FILE = 'config.ini' #CHAN_NAMES = ['DAPI1st', 'DAPI2nd', 'DAPI3rd', 'GABA488', # 'GAD647', 'gephyrin594', 'GS594', 'MBP488', 'NR1594', # 'PSD95_488', 'Synapsin647', 'VGluT1_647'] #CHAN_NAMES = ['synapsin', 'PSDr'] CHAN_NAMES = ['EM10K', 'bIIItubulin', 'DAPI_2nd', 'DAPI_3rd', 'GABA', 'GAD2', 'VGAT', 'gephyrin', 'NR1', 'PSDr', 'synapsin', 'VGluT1'] cubes, locs = main(COLL_NAME, EXP_NAME, COORD_FRAME, LOCATIONS_FILE, BF = BF, CHAN_NAMES=CHAN_NAMES, num_threads = 8, CONFIG_FILE= 'config.ini') #import pdb; pdb.set_trace() f0 = toolbox.F0(cubes) toolbox.mainOUT(f0, CHAN_NAMES, OUTPUT) toolbox.toh5(EXP_NAME, OUTPUT + '.h5', CHAN_NAMES, cubes, locs, F0 = f0) return(cubes, locs) ## END driveMain if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'Download synapse cubes using the BOSS') parser.add_argument('-C', help='Valid collection id', type = str, metavar='C', default='weiler14') parser.add_argument('-E', help='Valid experiment id', type = str, metavar='E', default='Ex2R18C1') parser.add_argument('-F', help='valid coordinate frame', type = str, metavar='F', default='weiler14_Ex2R18C1') parser.add_argument('-B', help='integer xyz list for buffer around center', nargs = 3, type = int, metavar='B', default= [5,5,5]) parser.add_argument('-L', help='csv file of locations ' 'in xyz order', type = str, metavar='L', required=True) parser.add_argument('-O', help='output filename', type = str, metavar='O', required=True, default = 'output') parser.add_argument('--con', help='user config file for BOSS' 'authentication', type = str, metavar='con', required=True) args = parser.parse_args() COLL_NAME = args.C EXP_NAME = args.E COORD_FRAME = args.F LOCATIONS_FILE = args.L BF = args.B OUTPUT = args.O CONFIG_FILE = args.con #rem = BossRemote(CONFIG_FILE) #CHAN_NAMES = rem.list_channels(COLL_NAME, EXP_NAME) CHAN_NAMES = ['EM10K', 'bIIItubulin', 'DAPI_2nd', 'DAPI_3rd', 'GABA', 'GAD2', 'VGAT', 'gephyrin', 'NR1', 'PSDr', 'synapsin', 'VGluT1'] cubes, locs = main(COLL_NAME, EXP_NAME, COORD_FRAME, LOCATIONS_FILE, BF = BF, CHAN_NAMES=CHAN_NAMES, num_threads = 6, CONFIG_FILE= CONFIG_FILE) f0 = toolbox.F0(cubes) toolbox.mainOUT(f0, CHAN_NAMES, OUTPUT) toolbox.toh5(EXP_NAME, OUTPUT + '.h5', CHAN_NAMES, cubes, locs, F0 = f0) print('Done!')
3dfxmadscientist/odoo_vi
refs/heads/master
addons/lunch/report/order.py
377
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 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 time from openerp.report import report_sxw from openerp.osv import osv class order(report_sxw.rml_parse): def get_lines(self, user,objects): lines=[] for obj in objects: if user.id==obj.user_id.id: lines.append(obj) return lines def get_total(self, user,objects): lines=[] for obj in objects: if user.id==obj.user_id.id: lines.append(obj) total=0.0 for line in lines: total+=line.price self.net_total+=total return total def get_nettotal(self): return self.net_total def get_users(self, objects): users=[] for obj in objects: if obj.user_id not in users: users.append(obj.user_id) return users def get_note(self,objects): notes=[] for obj in objects: notes.append(obj.note) return notes def __init__(self, cr, uid, name, context): super(order, self).__init__(cr, uid, name, context) self.net_total=0.0 self.localcontext.update({ 'time': time, 'get_lines': self.get_lines, 'get_users': self.get_users, 'get_total': self.get_total, 'get_nettotal': self.get_nettotal, 'get_note': self.get_note, }) class report_lunchorder(osv.AbstractModel): _name = 'report.lunch.report_lunchorder' _inherit = 'report.abstract_report' _template = 'lunch.report_lunchorder' _wrapped_report_class = order # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
cosmiclattes/TPBviz
refs/heads/master
torrent/lib/python2.7/site-packages/django/contrib/gis/gdal/tests/test_ds.py
109
import os from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.geometry.test_data import get_ds_file, TestDS, TEST_DATA from django.utils import unittest from django.utils.unittest import skipUnless if HAS_GDAL: from django.contrib.gis.gdal import DataSource, Envelope, OGRGeometry, OGRException, OGRIndexError, GDAL_VERSION from django.contrib.gis.gdal.field import OFTReal, OFTInteger, OFTString # List of acceptable data sources. ds_list = ( TestDS('test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile', fields={'dbl' : OFTReal, 'int' : OFTInteger, 'str' : OFTString,}, extent=(-1.35011,0.166623,-0.524093,0.824508), # Got extent from QGIS srs_wkt='GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]', field_values={'dbl' : [float(i) for i in range(1, 6)], 'int' : list(range(1, 6)), 'str' : [str(i) for i in range(1, 6)]}, fids=range(5)), TestDS('test_vrt', ext='vrt', nfeat=3, nfld=3, geom='POINT', gtype='Point25D', driver='VRT', fields={'POINT_X' : OFTString, 'POINT_Y' : OFTString, 'NUM' : OFTString}, # VRT uses CSV, which all types are OFTString. extent=(1.0, 2.0, 100.0, 523.5), # Min/Max from CSV field_values={'POINT_X' : ['1.0', '5.0', '100.0'], 'POINT_Y' : ['2.0', '23.0', '523.5'], 'NUM' : ['5', '17', '23']}, fids=range(1,4)), TestDS('test_poly', nfeat=3, nfld=3, geom='POLYGON', gtype=3, driver='ESRI Shapefile', fields={'float' : OFTReal, 'int' : OFTInteger, 'str' : OFTString,}, extent=(-1.01513,-0.558245,0.161876,0.839637), # Got extent from QGIS srs_wkt='GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]'), ) bad_ds = (TestDS('foo'),) @skipUnless(HAS_GDAL, "GDAL is required") class DataSourceTest(unittest.TestCase): def test01_valid_shp(self): "Testing valid SHP Data Source files." for source in ds_list: # Loading up the data source ds = DataSource(source.ds) # Making sure the layer count is what's expected (only 1 layer in a SHP file) self.assertEqual(1, len(ds)) # Making sure GetName works self.assertEqual(source.ds, ds.name) # Making sure the driver name matches up self.assertEqual(source.driver, str(ds.driver)) # Making sure indexing works try: ds[len(ds)] except OGRIndexError: pass else: self.fail('Expected an IndexError!') def test02_invalid_shp(self): "Testing invalid SHP files for the Data Source." for source in bad_ds: self.assertRaises(OGRException, DataSource, source.ds) def test03a_layers(self): "Testing Data Source Layers." for source in ds_list: ds = DataSource(source.ds) # Incrementing through each layer, this tests DataSource.__iter__ for layer in ds: # Making sure we get the number of features we expect self.assertEqual(len(layer), source.nfeat) # Making sure we get the number of fields we expect self.assertEqual(source.nfld, layer.num_fields) self.assertEqual(source.nfld, len(layer.fields)) # Testing the layer's extent (an Envelope), and it's properties if source.driver == 'VRT' and (GDAL_VERSION >= (1, 7, 0) and GDAL_VERSION < (1, 7, 3)): # There's a known GDAL regression with retrieving the extent # of a VRT layer in versions 1.7.0-1.7.2: # http://trac.osgeo.org/gdal/ticket/3783 pass else: self.assertEqual(True, isinstance(layer.extent, Envelope)) self.assertAlmostEqual(source.extent[0], layer.extent.min_x, 5) self.assertAlmostEqual(source.extent[1], layer.extent.min_y, 5) self.assertAlmostEqual(source.extent[2], layer.extent.max_x, 5) self.assertAlmostEqual(source.extent[3], layer.extent.max_y, 5) # Now checking the field names. flds = layer.fields for f in flds: self.assertEqual(True, f in source.fields) # Negative FIDs are not allowed. self.assertRaises(OGRIndexError, layer.__getitem__, -1) self.assertRaises(OGRIndexError, layer.__getitem__, 50000) if hasattr(source, 'field_values'): fld_names = source.field_values.keys() # Testing `Layer.get_fields` (which uses Layer.__iter__) for fld_name in fld_names: self.assertEqual(source.field_values[fld_name], layer.get_fields(fld_name)) # Testing `Layer.__getitem__`. for i, fid in enumerate(source.fids): feat = layer[fid] self.assertEqual(fid, feat.fid) # Maybe this should be in the test below, but we might as well test # the feature values here while in this loop. for fld_name in fld_names: self.assertEqual(source.field_values[fld_name][i], feat.get(fld_name)) def test03b_layer_slice(self): "Test indexing and slicing on Layers." # Using the first data-source because the same slice # can be used for both the layer and the control values. source = ds_list[0] ds = DataSource(source.ds) sl = slice(1, 3) feats = ds[0][sl] for fld_name in ds[0].fields: test_vals = [feat.get(fld_name) for feat in feats] control_vals = source.field_values[fld_name][sl] self.assertEqual(control_vals, test_vals) def test03c_layer_references(self): """ Ensure OGR objects keep references to the objects they belong to. """ source = ds_list[0] # See ticket #9448. def get_layer(): # This DataSource object is not accessible outside this # scope. However, a reference should still be kept alive # on the `Layer` returned. ds = DataSource(source.ds) return ds[0] # Making sure we can call OGR routines on the Layer returned. lyr = get_layer() self.assertEqual(source.nfeat, len(lyr)) self.assertEqual(source.gtype, lyr.geom_type.num) # Same issue for Feature/Field objects, see #18640 self.assertEqual(str(lyr[0]['str']), "1") def test04_features(self): "Testing Data Source Features." for source in ds_list: ds = DataSource(source.ds) # Incrementing through each layer for layer in ds: # Incrementing through each feature in the layer for feat in layer: # Making sure the number of fields, and the geometry type # are what's expected. self.assertEqual(source.nfld, len(list(feat))) self.assertEqual(source.gtype, feat.geom_type) # Making sure the fields match to an appropriate OFT type. for k, v in source.fields.items(): # Making sure we get the proper OGR Field instance, using # a string value index for the feature. self.assertEqual(True, isinstance(feat[k], v)) # Testing Feature.__iter__ for fld in feat: self.assertEqual(True, fld.name in source.fields.keys()) def test05_geometries(self): "Testing Geometries from Data Source Features." for source in ds_list: ds = DataSource(source.ds) # Incrementing through each layer and feature. for layer in ds: for feat in layer: g = feat.geom # Making sure we get the right Geometry name & type self.assertEqual(source.geom, g.geom_name) self.assertEqual(source.gtype, g.geom_type) # Making sure the SpatialReference is as expected. if hasattr(source, 'srs_wkt'): self.assertEqual( source.srs_wkt, # Depending on lib versions, WGS_84 might be WGS_1984 g.srs.wkt.replace('SPHEROID["WGS_84"', 'SPHEROID["WGS_1984"') ) def test06_spatial_filter(self): "Testing the Layer.spatial_filter property." ds = DataSource(get_ds_file('cities', 'shp')) lyr = ds[0] # When not set, it should be None. self.assertEqual(None, lyr.spatial_filter) # Must be set a/an OGRGeometry or 4-tuple. self.assertRaises(TypeError, lyr._set_spatial_filter, 'foo') # Setting the spatial filter with a tuple/list with the extent of # a buffer centering around Pueblo. self.assertRaises(ValueError, lyr._set_spatial_filter, list(range(5))) filter_extent = (-105.609252, 37.255001, -103.609252, 39.255001) lyr.spatial_filter = (-105.609252, 37.255001, -103.609252, 39.255001) self.assertEqual(OGRGeometry.from_bbox(filter_extent), lyr.spatial_filter) feats = [feat for feat in lyr] self.assertEqual(1, len(feats)) self.assertEqual('Pueblo', feats[0].get('Name')) # Setting the spatial filter with an OGRGeometry for buffer centering # around Houston. filter_geom = OGRGeometry('POLYGON((-96.363151 28.763374,-94.363151 28.763374,-94.363151 30.763374,-96.363151 30.763374,-96.363151 28.763374))') lyr.spatial_filter = filter_geom self.assertEqual(filter_geom, lyr.spatial_filter) feats = [feat for feat in lyr] self.assertEqual(1, len(feats)) self.assertEqual('Houston', feats[0].get('Name')) # Clearing the spatial filter by setting it to None. Now # should indicate that there are 3 features in the Layer. lyr.spatial_filter = None self.assertEqual(3, len(lyr)) def test07_integer_overflow(self): "Testing that OFTReal fields, treated as OFTInteger, do not overflow." # Using *.dbf from Census 2010 TIGER Shapefile for Texas, # which has land area ('ALAND10') stored in a Real field # with no precision. ds = DataSource(os.path.join(TEST_DATA, 'texas.dbf')) feat = ds[0][0] # Reference value obtained using `ogrinfo`. self.assertEqual(676586997978, feat.get('ALAND10'))
nan86150/ImageFusion
refs/heads/master
lib/python2.7/site-packages/nose/tools/__init__.py
94
""" Tools for testing ----------------- nose.tools provides a few convenience functions to make writing tests easier. You don't have to use them; nothing in the rest of nose depends on any of these methods. """ from nose.tools.nontrivial import * from nose.tools.nontrivial import __all__ as nontrivial_all from nose.tools.trivial import * from nose.tools.trivial import __all__ as trivial_all __all__ = trivial_all + nontrivial_all
rafaelmartins/blohg
refs/heads/master
blohg/tests/vcs_backends/hg/filectx.py
1
# -*- coding: utf-8 -*- """ blohg.tests.vcs_backends.hg.filectx ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Module with tests for blohg integration with mercurial (file context). :copyright: (c) 2010-2013 by Rafael Goncalves Martins :license: GPL-2, see LICENSE for more details. """ import codecs import os import time import unittest from mercurial import commands, hg, ui from shutil import rmtree from tempfile import mkdtemp from blohg.vcs_backends.hg.filectx import FileCtx from blohg.vcs_backends.hg.utils import u2hg class FileCtxTestCase(unittest.TestCase): def setUp(self): self.repo_path = mkdtemp() self.repo_pathb = u2hg(self.repo_path) self.ui = ui.ui() self.ui.setconfig(b'ui', b'quiet', True) commands.init(self.ui, self.repo_pathb) self.file_name = 'foo.rst' self.file_path = os.path.join(self.repo_path, self.file_name) with codecs.open(self.file_path, 'w', encoding='utf-8') as fp: fp.write('test\n') self.repo = hg.repository(self.ui, self.repo_pathb) self.changectx = self.repo[None] commands.commit(self.ui, self.repo, message=b'foo', user=b'foo <foo@bar.com>', addremove=True) def tearDown(self): try: rmtree(self.repo_path) except: pass def test_path(self): ctx = FileCtx(self.repo, self.changectx, self.file_name) self.assertEqual(ctx.path, 'foo.rst') def test_content(self): ctx = FileCtx(self.repo, self.changectx, self.file_name) self.assertEqual(ctx.content, 'test\n') with codecs.open(self.file_path, 'a', encoding='utf-8') as fp: fp.write('lol\n') # change file without hg add ctx = FileCtx(self.repo, self.changectx, self.file_name) self.assertEqual(ctx.content, 'test\nlol\n') def test_author(self): ctx = FileCtx(self.repo, self.changectx, self.file_name) self.assertEqual(ctx.author, 'foo <foo@bar.com>') def test_date_and_mdate(self): ctx = FileCtx(self.repo, self.changectx, self.file_name) time.sleep(1) self.assertTrue(ctx.date < time.time()) self.assertTrue(ctx.mdate is None) old_date = ctx.date time.sleep(1) with codecs.open(self.file_path, 'a', encoding='utf-8') as fp: fp.write('foo\n') commands.commit(self.ui, self.repo, user=b'foo', message=b'foo2') ctx = FileCtx(self.repo, self.changectx, self.file_name) self.assertEqual(ctx.date, old_date) self.assertTrue(ctx.mdate > old_date)
drrk/micropython
refs/heads/master
tests/basics/del_deref.py
118
def f(): x = 1 y = 2 def g(): nonlocal x print(y) try: print(x) except NameError: print("NameError") def h(): nonlocal x print(y) try: del x except NameError: print("NameError") print(x, y) del x g() h() f()
icede/Gridcoin-master
refs/heads/master
share/qt/extract_strings_qt.py
2945
#!/usr/bin/python ''' Extract _("...") strings for translation and convert to Qt4 stringdefs so that they can be picked up by Qt linguist. ''' from subprocess import Popen, PIPE import glob import operator OUT_CPP="src/qt/bitcoinstrings.cpp" EMPTY=['""'] def parse_po(text): """ Parse 'po' format produced by xgettext. Return a list of (msgid,msgstr) tuples. """ messages = [] msgid = [] msgstr = [] in_msgid = False in_msgstr = False for line in text.split('\n'): line = line.rstrip('\r') if line.startswith('msgid '): if in_msgstr: messages.append((msgid, msgstr)) in_msgstr = False # message start in_msgid = True msgid = [line[6:]] elif line.startswith('msgstr '): in_msgid = False in_msgstr = True msgstr = [line[7:]] elif line.startswith('"'): if in_msgid: msgid.append(line) if in_msgstr: msgstr.append(line) if in_msgstr: messages.append((msgid, msgstr)) return messages files = glob.glob('src/*.cpp') + glob.glob('src/*.h') # xgettext -n --keyword=_ $FILES child = Popen(['xgettext','--output=-','-n','--keyword=_'] + files, stdout=PIPE) (out, err) = child.communicate() messages = parse_po(out) f = open(OUT_CPP, 'w') f.write("""#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif """) f.write('static const char UNUSED *bitcoin_strings[] = {\n') messages.sort(key=operator.itemgetter(0)) for (msgid, msgstr) in messages: if msgid != EMPTY: f.write('QT_TRANSLATE_NOOP("bitcoin-core", %s),\n' % ('\n'.join(msgid))) f.write('};') f.close()
me0/LikSATSolver
refs/heads/master
lib/lp_solve_5.5/extra/Python/setup.py
1
from distutils.core import setup, Extension from os import getenv import sys import os p = sys.prefix NUMPYPATH = '.' if os.path.isdir(p + '/include/numpy'): NUMPY = 'NUMPY' elif os.path.isdir(p + '/Lib/site-packages/numpy/core/include/numpy'): NUMPY = 'NUMPY' NUMPYPATH = p + '/Lib/site-packages/numpy/core/include' else: NUMPY = 'NONUMPY' print 'numpy: ' + NUMPY windir = getenv('windir') if windir == None: WIN32 = 'NOWIN32' LPSOLVE55 = '../../lpsolve55/bin/ux32' else: WIN32 = 'WIN32' LPSOLVE55 = '../../lpsolve55/bin/win32' setup (name = "lpsolve55", version = "5.5.0.9", description = "Linear Program Solver, Interface to lpsolve", author = "Peter Notebaert", author_email = "lpsolve@peno.be", url = "http://www.peno.be/", py_modules=['lp_solve', 'lp_maker'], ext_modules = [Extension("lpsolve55", ["lpsolve.c", "hash.c", "pythonmod.c"], define_macros=[('PYTHON', '1'), (WIN32, '1'), ('NODEBUG', '1'), ('DINLINE', 'static'), (NUMPY, '1'), ('_CRT_SECURE_NO_WARNINGS', '1')], include_dirs=['../..', NUMPYPATH], library_dirs=[LPSOLVE55], libraries = ["lpsolve55"]) ] )
vveliev/selenium
refs/heads/master
py/selenium/webdriver/support/expected_conditions.py
69
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoSuchFrameException from selenium.common.exceptions import StaleElementReferenceException from selenium.common.exceptions import WebDriverException from selenium.common.exceptions import NoAlertPresentException """ * Canned "Expected Conditions" which are generally useful within webdriver * tests. """ class title_is(object): """An expectation for checking the title of a page. title is the expected title, which must be an exact match returns True if the title matches, false otherwise.""" def __init__(self, title): self.title = title def __call__(self, driver): return self.title == driver.title class title_contains(object): """ An expectation for checking that the title contains a case-sensitive substring. title is the fragment of title expected returns True when the title matches, False otherwise """ def __init__(self, title): self.title = title def __call__(self, driver): return self.title in driver.title class presence_of_element_located(object): """ An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. locator - used to find the element returns the WebElement once it is located """ def __init__(self, locator): self.locator = locator def __call__(self, driver): return _find_element(driver, self.locator) class visibility_of_element_located(object): """ An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. locator - used to find the element returns the WebElement once it is located and visible """ def __init__(self, locator): self.locator = locator def __call__(self, driver): try: return _element_if_visible(_find_element(driver, self.locator)) except StaleElementReferenceException: return False class visibility_of(object): """ An expectation for checking that an element, known to be present on the DOM of a page, is visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. element is the WebElement returns the (same) WebElement once it is visible """ def __init__(self, element): self.element = element def __call__(self, ignored): return _element_if_visible(self.element) def _element_if_visible(element, visibility=True): return element if element.is_displayed() == visibility else False class presence_of_all_elements_located(object): """ An expectation for checking that there is at least one element present on a web page. locator is used to find the element returns the list of WebElements once they are located """ def __init__(self, locator): self.locator = locator def __call__(self, driver): return _find_elements(driver, self.locator) class text_to_be_present_in_element(object): """ An expectation for checking if the given text is present in the specified element. locator, text """ def __init__(self, locator, text_): self.locator = locator self.text = text_ def __call__(self, driver): try : element_text = _find_element(driver, self.locator).text return self.text in element_text except StaleElementReferenceException: return False class text_to_be_present_in_element_value(object): """ An expectation for checking if the given text is present in the element's locator, text """ def __init__(self, locator, text_): self.locator = locator self.text = text_ def __call__(self, driver): try: element_text = _find_element(driver, self.locator).get_attribute("value") if element_text: return self.text in element_text else: return False except StaleElementReferenceException: return False class frame_to_be_available_and_switch_to_it(object): """ An expectation for checking whether the given frame is available to switch to. If the frame is available it switches the given driver to the specified frame. """ def __init__(self, locator): self.frame_locator = locator def __call__(self, driver): try: if isinstance(self.frame_locator, tuple): driver.switch_to.frame(_find_element(driver, self.frame_locator)) else: driver.switch_to.frame(self.frame_locator) return True except NoSuchFrameException: return False class invisibility_of_element_located(object): """ An Expectation for checking that an element is either invisible or not present on the DOM. locator used to find the element """ def __init__(self, locator): self.locator = locator def __call__(self, driver): try: return _element_if_visible(_find_element(driver, self.locator), False) except (NoSuchElementException, StaleElementReferenceException): # In the case of NoSuchElement, returns true because the element is # not present in DOM. The try block checks if the element is present # but is invisible. # In the case of StaleElementReference, returns true because stale # element reference implies that element is no longer visible. return True class element_to_be_clickable(object): """ An Expectation for checking an element is visible and enabled such that you can click it.""" def __init__(self, locator): self.locator = locator def __call__(self, driver): element = visibility_of_element_located(self.locator)(driver) if element and element.is_enabled(): return element else: return False class staleness_of(object): """ Wait until an element is no longer attached to the DOM. element is the element to wait for. returns False if the element is still attached to the DOM, true otherwise. """ def __init__(self, element): self.element = element def __call__(self, ignored): try: # Calling any method forces a staleness check self.element.is_enabled() return False except StaleElementReferenceException as expected: return True class element_to_be_selected(object): """ An expectation for checking the selection is selected. element is WebElement object """ def __init__(self, element): self.element = element def __call__(self, ignored): return self.element.is_selected() class element_located_to_be_selected(object): """An expectation for the element to be located is selected. locator is a tuple of (by, path)""" def __init__(self, locator): self.locator = locator def __call__(self, driver): return _find_element(driver, self.locator).is_selected() class element_selection_state_to_be(object): """ An expectation for checking if the given element is selected. element is WebElement object is_selected is a Boolean." """ def __init__(self, element, is_selected): self.element = element self.is_selected = is_selected def __call__(self, ignored): return self.element.is_selected() == self.is_selected class element_located_selection_state_to_be(object): """ An expectation to locate an element and check if the selection state specified is in that state. locator is a tuple of (by, path) is_selected is a boolean """ def __init__(self, locator, is_selected): self.locator = locator self.is_selected = is_selected def __call__(self, driver): try: element = _find_element(driver, self.locator) return element.is_selected() == self.is_selected except StaleElementReferenceException: return False class alert_is_present(object): """ Expect an alert to be present.""" def __init__(self): pass def __call__(self, driver): try: alert = driver.switch_to.alert alert.text return alert except NoAlertPresentException: return False def _find_element(driver, by): """Looks up an element. Logs and re-raises ``WebDriverException`` if thrown.""" try : return driver.find_element(*by) except NoSuchElementException as e: raise e except WebDriverException as e: raise e def _find_elements(driver, by): try : return driver.find_elements(*by) except WebDriverException as e: raise e
yusufm/mobly
refs/heads/master
tests/mobly/records_test.py
1
#!/usr/bin/env python3.4 # # Copyright 2016 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. import unittest from mobly import records from mobly import signals class RecordsTest(unittest.TestCase): """This test class tests the implementation of classes in mobly.records. """ def setUp(self): self.tn = "test_name" self.details = "Some details about the test execution." self.float_extra = 12345.56789 self.json_extra = {"ha": "whatever"} def verify_record(self, record, result, details, extras): # Verify each field. self.assertEqual(record.test_name, self.tn) self.assertEqual(record.result, result) self.assertEqual(record.details, details) self.assertEqual(record.extras, extras) self.assertTrue(record.begin_time, "begin time should not be empty.") self.assertTrue(record.end_time, "end time should not be empty.") # UID is not used at the moment, should always be None. self.assertIsNone(record.uid) # Verify to_dict. d = {} d[records.TestResultEnums.RECORD_NAME] = self.tn d[records.TestResultEnums.RECORD_RESULT] = result d[records.TestResultEnums.RECORD_DETAILS] = details d[records.TestResultEnums.RECORD_EXTRAS] = extras d[records.TestResultEnums.RECORD_BEGIN_TIME] = record.begin_time d[records.TestResultEnums.RECORD_END_TIME] = record.end_time d[records.TestResultEnums.RECORD_UID] = None d[records.TestResultEnums.RECORD_CLASS] = None d[records.TestResultEnums.RECORD_EXTRA_ERRORS] = {} actual_d = record.to_dict() self.assertDictEqual(actual_d, d) # Verify that these code paths do not cause crashes and yield non-empty # results. self.assertTrue(str(record), "str of the record should not be empty.") self.assertTrue(repr(record), "the record's repr shouldn't be empty.") self.assertTrue(record.json_str(), ("json str of the record should " "not be empty.")) """ Begin of Tests """ def test_result_record_pass_none(self): record = records.TestResultRecord(self.tn) record.test_begin() record.test_pass() self.verify_record(record=record, result=records.TestResultEnums.TEST_RESULT_PASS, details=None, extras=None) def test_result_record_pass_with_float_extra(self): record = records.TestResultRecord(self.tn) record.test_begin() s = signals.TestPass(self.details, self.float_extra) record.test_pass(s) self.verify_record(record=record, result=records.TestResultEnums.TEST_RESULT_PASS, details=self.details, extras=self.float_extra) def test_result_record_pass_with_json_extra(self): record = records.TestResultRecord(self.tn) record.test_begin() s = signals.TestPass(self.details, self.json_extra) record.test_pass(s) self.verify_record(record=record, result=records.TestResultEnums.TEST_RESULT_PASS, details=self.details, extras=self.json_extra) def test_result_record_fail_none(self): record = records.TestResultRecord(self.tn) record.test_begin() record.test_fail() self.verify_record(record=record, result=records.TestResultEnums.TEST_RESULT_FAIL, details=None, extras=None) def test_result_record_fail_with_float_extra(self): record = records.TestResultRecord(self.tn) record.test_begin() s = signals.TestFailure(self.details, self.float_extra) record.test_fail(s) self.verify_record(record=record, result=records.TestResultEnums.TEST_RESULT_FAIL, details=self.details, extras=self.float_extra) def test_result_record_fail_with_json_extra(self): record = records.TestResultRecord(self.tn) record.test_begin() s = signals.TestFailure(self.details, self.json_extra) record.test_fail(s) self.verify_record(record=record, result=records.TestResultEnums.TEST_RESULT_FAIL, details=self.details, extras=self.json_extra) def test_result_record_skip_none(self): record = records.TestResultRecord(self.tn) record.test_begin() record.test_skip() self.verify_record(record=record, result=records.TestResultEnums.TEST_RESULT_SKIP, details=None, extras=None) def test_result_record_skip_with_float_extra(self): record = records.TestResultRecord(self.tn) record.test_begin() s = signals.TestSkip(self.details, self.float_extra) record.test_skip(s) self.verify_record(record=record, result=records.TestResultEnums.TEST_RESULT_SKIP, details=self.details, extras=self.float_extra) def test_result_record_skip_with_json_extra(self): record = records.TestResultRecord(self.tn) record.test_begin() s = signals.TestSkip(self.details, self.json_extra) record.test_skip(s) self.verify_record(record=record, result=records.TestResultEnums.TEST_RESULT_SKIP, details=self.details, extras=self.json_extra) def test_result_add_operator_success(self): record1 = records.TestResultRecord(self.tn) record1.test_begin() s = signals.TestPass(self.details, self.float_extra) record1.test_pass(s) tr1 = records.TestResult() tr1.add_record(record1) tr1.add_controller_info("MockDevice", ["magicA", "magicB"]) record2 = records.TestResultRecord(self.tn) record2.test_begin() s = signals.TestPass(self.details, self.json_extra) record2.test_pass(s) tr2 = records.TestResult() tr2.add_record(record2) tr2.add_controller_info("MockDevice", ["magicC"]) tr2 += tr1 self.assertTrue(tr2.passed, [tr1, tr2]) self.assertTrue(tr2.controller_info, {"MockDevice": ["magicC"]}) def test_result_add_operator_type_mismatch(self): record1 = records.TestResultRecord(self.tn) record1.test_begin() s = signals.TestPass(self.details, self.float_extra) record1.test_pass(s) tr1 = records.TestResult() tr1.add_record(record1) expected_msg = "Operand .* of type .* is not a TestResult." with self.assertRaisesRegexp(TypeError, expected_msg): tr1 += "haha" def test_result_fail_class_with_test_signal(self): record1 = records.TestResultRecord(self.tn) record1.test_begin() s = signals.TestPass(self.details, self.float_extra) record1.test_pass(s) tr = records.TestResult() tr.add_record(record1) s = signals.TestFailure(self.details, self.float_extra) record2 = records.TestResultRecord("SomeTest", s) tr.fail_class(record2) self.assertEqual(len(tr.passed), 1) self.assertEqual(len(tr.failed), 1) self.assertEqual(len(tr.executed), 2) def test_result_fail_class_with_special_error(self): """Call TestResult.fail_class with an error class that requires more than one arg to instantiate. """ record1 = records.TestResultRecord(self.tn) record1.test_begin() s = signals.TestPass(self.details, self.float_extra) record1.test_pass(s) tr = records.TestResult() tr.add_record(record1) class SpecialError(Exception): def __init__(self, arg1, arg2): self.msg = "%s %s" % (arg1, arg2) se = SpecialError("haha", 42) record2 = records.TestResultRecord("SomeTest", se) tr.fail_class(record2) self.assertEqual(len(tr.passed), 1) self.assertEqual(len(tr.failed), 1) self.assertEqual(len(tr.executed), 2) def test_is_all_pass(self): s = signals.TestPass(self.details, self.float_extra) record1 = records.TestResultRecord(self.tn) record1.test_begin() record1.test_pass(s) s = signals.TestSkip(self.details, self.float_extra) record2 = records.TestResultRecord(self.tn) record2.test_begin() record2.test_skip(s) tr = records.TestResult() tr.add_record(record1) tr.add_record(record2) tr.add_record(record1) self.assertEqual(len(tr.passed), 2) self.assertTrue(tr.is_all_pass) def test_is_all_pass_negative(self): s = signals.TestFailure(self.details, self.float_extra) record1 = records.TestResultRecord(self.tn) record1.test_begin() record1.test_fail(s) record2 = records.TestResultRecord(self.tn) record2.test_begin() record2.test_error(s) tr = records.TestResult() tr.add_record(record1) tr.add_record(record2) self.assertFalse(tr.is_all_pass) def test_is_all_pass_with_fail_class(self): """Verifies that is_all_pass yields correct value when fail_class is used. """ record1 = records.TestResultRecord(self.tn) record1.test_begin() record1.test_fail(Exception("haha")) tr = records.TestResult() tr.fail_class(record1) self.assertFalse(tr.is_all_pass) if __name__ == "__main__": unittest.main()
xuewei4d/scikit-learn
refs/heads/master
examples/miscellaneous/plot_isotonic_regression.py
17
""" =================== Isotonic Regression =================== An illustration of the isotonic regression on generated data (non-linear monotonic trend with homoscedastic uniform noise). The isotonic regression algorithm finds a non-decreasing approximation of a function while minimizing the mean squared error on the training data. The benefit of such a non-parametric model is that it does not assume any shape for the target function besides monotonicity. For comparison a linear regression is also presented. The plot on the right-hand side shows the model prediction function that results from the linear interpolation of thresholds points. The thresholds points are a subset of the training input observations and their matching target values are computed by the isotonic non-parametric fit. """ print(__doc__) # Author: Nelle Varoquaux <nelle.varoquaux@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # License: BSD import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from sklearn.linear_model import LinearRegression from sklearn.isotonic import IsotonicRegression from sklearn.utils import check_random_state n = 100 x = np.arange(n) rs = check_random_state(0) y = rs.randint(-50, 50, size=(n,)) + 50. * np.log1p(np.arange(n)) # %% # Fit IsotonicRegression and LinearRegression models: ir = IsotonicRegression(out_of_bounds="clip") y_ = ir.fit_transform(x, y) lr = LinearRegression() lr.fit(x[:, np.newaxis], y) # x needs to be 2d for LinearRegression # %% # Plot results: segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)] lc = LineCollection(segments, zorder=0) lc.set_array(np.ones(len(y))) lc.set_linewidths(np.full(n, 0.5)) fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 6)) ax0.plot(x, y, 'C0.', markersize=12) ax0.plot(x, y_, 'C1.-', markersize=12) ax0.plot(x, lr.predict(x[:, np.newaxis]), 'C2-') ax0.add_collection(lc) ax0.legend(('Training data', 'Isotonic fit', 'Linear fit'), loc='lower right') ax0.set_title('Isotonic regression fit on noisy data (n=%d)' % n) x_test = np.linspace(-10, 110, 1000) ax1.plot(x_test, ir.predict(x_test), 'C1-') ax1.plot(ir.X_thresholds_, ir.y_thresholds_, 'C1.', markersize=12) ax1.set_title("Prediction function (%d thresholds)" % len(ir.X_thresholds_)) plt.show() # %% # Note that we explicitly passed `out_of_bounds="clip"` to the constructor of # `IsotonicRegression` to control the way the model extrapolates outside of the # range of data observed in the training set. This "clipping" extrapolation can # be seen on the plot of the decision function on the right-hand.
baryonix/collectd
refs/heads/master
contrib/collectd_unixsock.py
84
#-*- coding: ISO-8859-1 -*- # collect.py: the python collectd-unixsock module. # # Requires collectd to be configured with the unixsock plugin, like so: # # LoadPlugin unixsock # <Plugin unixsock> # SocketFile "/var/run/collectd-unixsock" # SocketPerms "0775" # </Plugin> # # Copyright (C) 2008 Clay Loveless <clay@killersoft.com> # # This software is provided 'as-is', without any express or implied # warranty. In no event will the author be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. import socket import sys class Collectd(): def __init__(self, path='/var/run/collectd-unixsock', noisy=False): self.noisy = noisy self.path = path self._sock = self._connect() def flush(self, timeout=None, plugins=[], identifiers=[]): """Send a FLUSH command. Full documentation: http://collectd.org/wiki/index.php/Plain_text_protocol#FLUSH """ # have to pass at least one plugin or identifier if not plugins and not identifiers: return None args = [] if timeout: args.append("timeout=%s" % timeout) if plugins: plugin_args = map(lambda x: "plugin=%s" % x, plugins) args.extend(plugin_args) if identifiers: identifier_args = map(lambda x: "identifier=%s" % x, identifiers) args.extend(identifier_args) return self._cmd('FLUSH %s' % ' '.join(args)) def getthreshold(self, identifier): """Send a GETTHRESHOLD command. Full documentation: http://collectd.org/wiki/index.php/Plain_text_protocol#GETTHRESHOLD """ numvalues = self._cmd('GETTHRESHOLD "%s"' % identifier) lines = [] if not numvalues or numvalues < 0: raise KeyError("Identifier '%s' not found" % identifier) lines = self._readlines(numvalues) return lines def getval(self, identifier, flush_after=True): """Send a GETVAL command. Also flushes the identifier if flush_after is True. Full documentation: http://collectd.org/wiki/index.php/Plain_text_protocol#GETVAL """ numvalues = self._cmd('GETVAL "%s"' % identifier) lines = [] if not numvalues or numvalues < 0: raise KeyError("Identifier '%s' not found" % identifier) lines = self._readlines(numvalues) if flush_after: self.flush(identifiers=[identifier]) return lines def listval(self): """Send a LISTVAL command. Full documentation: http://collectd.org/wiki/index.php/Plain_text_protocol#LISTVAL """ numvalues = self._cmd('LISTVAL') lines = [] if numvalues: lines = self._readlines(numvalues) return lines def putnotif(self, message, options={}): """Send a PUTNOTIF command. Options must be passed as a Python dictionary. Example: options={'severity': 'failure', 'host': 'example.com'} Full documentation: http://collectd.org/wiki/index.php/Plain_text_protocol#PUTNOTIF """ args = [] if options: options_args = map(lambda x: "%s=%s" % (x, options[x]), options) args.extend(options_args) args.append('message="%s"' % message) return self._cmd('PUTNOTIF %s' % ' '.join(args)) def putval(self, identifier, values, options={}): """Send a PUTVAL command. Options must be passed as a Python dictionary. Example: options={'interval': 10} Full documentation: http://collectd.org/wiki/index.php/Plain_text_protocol#PUTVAL """ args = [] args.append('"%s"' % identifier) if options: options_args = map(lambda x: "%s=%s" % (x, options[x]), options) args.extend(options_args) values = map(str, values) args.append(':'.join(values)) return self._cmd('PUTVAL %s' % ' '.join(args)) def _cmd(self, c): try: return self._cmdattempt(c) except socket.error, (errno, errstr): sys.stderr.write("[error] Sending to socket failed: [%d] %s\n" % (errno, errstr)) self._sock = self._connect() return self._cmdattempt(c) def _cmdattempt(self, c): if self.noisy: print "[send] %s" % c if not self._sock: sys.stderr.write("[error] Socket unavailable. Can not send.") return False self._sock.send(c + "\n") status_message = self._readline() if self.noisy: print "[receive] %s" % status_message if not status_message: return None code, message = status_message.split(' ', 1) if int(code): return int(code) return False def _connect(self): try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(self.path) if self.noisy: print "[socket] connected to %s" % self.path return sock except socket.error, (errno, errstr): sys.stderr.write("[error] Connecting to socket failed: [%d] %s" % (errno, errstr)) return None def _readline(self): """Read single line from socket""" if not self._sock: sys.stderr.write("[error] Socket unavailable. Can not read.") return None try: data = '' buf = [] recv = self._sock.recv while data != "\n": data = recv(1) if not data: break if data != "\n": buf.append(data) return ''.join(buf) except socket.error, (errno, errstr): sys.stderr.write("[error] Reading from socket failed: [%d] %s" % (errno, errstr)) self._sock = self._connect() return None def _readlines(self, sizehint=0): """Read multiple lines from socket""" total = 0 list = [] while True: line = self._readline() if not line: break list.append(line) total = len(list) if sizehint and total >= sizehint: break return list def __del__(self): if not self._sock: return try: self._sock.close() except socket.error, (errno, errstr): sys.stderr.write("[error] Closing socket failed: [%d] %s" % (errno, errstr)) if __name__ == '__main__': """Collect values from socket and dump to STDOUT""" c = Collectd('/var/run/collectd-unixsock', noisy=True) list = c.listval() for val in list: stamp, identifier = val.split() print "\n%s" % identifier print "\tUpdate time: %s" % stamp values = c.getval(identifier) print "\tValue list: %s" % ', '.join(values) # don't fetch thresholds by default because collectd will crash # if there is no treshold for the given identifier #thresholds = c.getthreshold(identifier) #print "\tThresholds: %s" % ', '.join(thresholds)
evanma92/routeh
refs/heads/master
flask/lib/python2.7/site-packages/sqlalchemy/dialects/oracle/base.py
21
# oracle/base.py # Copyright (C) 2005-2015 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: oracle :name: Oracle Oracle version 8 through current (11g at the time of this writing) are supported. Connect Arguments ----------------- The dialect supports several :func:`~sqlalchemy.create_engine()` arguments which affect the behavior of the dialect regardless of driver in use. * ``use_ansi`` - Use ANSI JOIN constructs (see the section on Oracle 8). Defaults to ``True``. If ``False``, Oracle-8 compatible constructs are used for joins. * ``optimize_limits`` - defaults to ``False``. see the section on LIMIT/OFFSET. * ``use_binds_for_limits`` - defaults to ``True``. see the section on LIMIT/OFFSET. Auto Increment Behavior ----------------------- SQLAlchemy Table objects which include integer primary keys are usually assumed to have "autoincrementing" behavior, meaning they can generate their own primary key values upon INSERT. Since Oracle has no "autoincrement" feature, SQLAlchemy relies upon sequences to produce these values. With the Oracle dialect, *a sequence must always be explicitly specified to enable autoincrement*. This is divergent with the majority of documentation examples which assume the usage of an autoincrement-capable database. To specify sequences, use the sqlalchemy.schema.Sequence object which is passed to a Column construct:: t = Table('mytable', metadata, Column('id', Integer, Sequence('id_seq'), primary_key=True), Column(...), ... ) This step is also required when using table reflection, i.e. autoload=True:: t = Table('mytable', metadata, Column('id', Integer, Sequence('id_seq'), primary_key=True), autoload=True ) Identifier Casing ----------------- In Oracle, the data dictionary represents all case insensitive identifier names using UPPERCASE text. SQLAlchemy on the other hand considers an all-lower case identifier name to be case insensitive. The Oracle dialect converts all case insensitive identifiers to and from those two formats during schema level communication, such as reflection of tables and indexes. Using an UPPERCASE name on the SQLAlchemy side indicates a case sensitive identifier, and SQLAlchemy will quote the name - this will cause mismatches against data dictionary data received from Oracle, so unless identifier names have been truly created as case sensitive (i.e. using quoted names), all lowercase names should be used on the SQLAlchemy side. LIMIT/OFFSET Support -------------------- Oracle has no support for the LIMIT or OFFSET keywords. SQLAlchemy uses a wrapped subquery approach in conjunction with ROWNUM. The exact methodology is taken from http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html . There are two options which affect its behavior: * the "FIRST ROWS()" optimization keyword is not used by default. To enable the usage of this optimization directive, specify ``optimize_limits=True`` to :func:`.create_engine`. * the values passed for the limit/offset are sent as bound parameters. Some users have observed that Oracle produces a poor query plan when the values are sent as binds and not rendered literally. To render the limit/offset values literally within the SQL statement, specify ``use_binds_for_limits=False`` to :func:`.create_engine`. Some users have reported better performance when the entirely different approach of a window query is used, i.e. ROW_NUMBER() OVER (ORDER BY), to provide LIMIT/OFFSET (note that the majority of users don't observe this). To suit this case the method used for LIMIT/OFFSET can be replaced entirely. See the recipe at http://www.sqlalchemy.org/trac/wiki/UsageRecipes/WindowFunctionsByDefault which installs a select compiler that overrides the generation of limit/offset with a window function. .. _oracle_returning: RETURNING Support ----------------- The Oracle database supports a limited form of RETURNING, in order to retrieve result sets of matched rows from INSERT, UPDATE and DELETE statements. Oracle's RETURNING..INTO syntax only supports one row being returned, as it relies upon OUT parameters in order to function. In addition, supported DBAPIs have further limitations (see :ref:`cx_oracle_returning`). SQLAlchemy's "implicit returning" feature, which employs RETURNING within an INSERT and sometimes an UPDATE statement in order to fetch newly generated primary key values and other SQL defaults and expressions, is normally enabled on the Oracle backend. By default, "implicit returning" typically only fetches the value of a single ``nextval(some_seq)`` expression embedded into an INSERT in order to increment a sequence within an INSERT statement and get the value back at the same time. To disable this feature across the board, specify ``implicit_returning=False`` to :func:`.create_engine`:: engine = create_engine("oracle://scott:tiger@dsn", implicit_returning=False) Implicit returning can also be disabled on a table-by-table basis as a table option:: # Core Table my_table = Table("my_table", metadata, ..., implicit_returning=False) # declarative class MyClass(Base): __tablename__ = 'my_table' __table_args__ = {"implicit_returning": False} .. seealso:: :ref:`cx_oracle_returning` - additional cx_oracle-specific restrictions on implicit returning. ON UPDATE CASCADE ----------------- Oracle doesn't have native ON UPDATE CASCADE functionality. A trigger based solution is available at http://asktom.oracle.com/tkyte/update_cascade/index.html . When using the SQLAlchemy ORM, the ORM has limited ability to manually issue cascading updates - specify ForeignKey objects using the "deferrable=True, initially='deferred'" keyword arguments, and specify "passive_updates=False" on each relationship(). Oracle 8 Compatibility ---------------------- When Oracle 8 is detected, the dialect internally configures itself to the following behaviors: * the use_ansi flag is set to False. This has the effect of converting all JOIN phrases into the WHERE clause, and in the case of LEFT OUTER JOIN makes use of Oracle's (+) operator. * the NVARCHAR2 and NCLOB datatypes are no longer generated as DDL when the :class:`~sqlalchemy.types.Unicode` is used - VARCHAR2 and CLOB are issued instead. This because these types don't seem to work correctly on Oracle 8 even though they are available. The :class:`~sqlalchemy.types.NVARCHAR` and :class:`~sqlalchemy.dialects.oracle.NCLOB` types will always generate NVARCHAR2 and NCLOB. * the "native unicode" mode is disabled when using cx_oracle, i.e. SQLAlchemy encodes all Python unicode objects to "string" before passing in as bind parameters. Synonym/DBLINK Reflection ------------------------- When using reflection with Table objects, the dialect can optionally search for tables indicated by synonyms, either in local or remote schemas or accessed over DBLINK, by passing the flag ``oracle_resolve_synonyms=True`` as a keyword argument to the :class:`.Table` construct:: some_table = Table('some_table', autoload=True, autoload_with=some_engine, oracle_resolve_synonyms=True) When this flag is set, the given name (such as ``some_table`` above) will be searched not just in the ``ALL_TABLES`` view, but also within the ``ALL_SYNONYMS`` view to see if this name is actually a synonym to another name. If the synonym is located and refers to a DBLINK, the oracle dialect knows how to locate the table's information using DBLINK syntax(e.g. ``@dblink``). ``oracle_resolve_synonyms`` is accepted wherever reflection arguments are accepted, including methods such as :meth:`.MetaData.reflect` and :meth:`.Inspector.get_columns`. If synonyms are not in use, this flag should be left disabled. DateTime Compatibility ---------------------- Oracle has no datatype known as ``DATETIME``, it instead has only ``DATE``, which can actually store a date and time value. For this reason, the Oracle dialect provides a type :class:`.oracle.DATE` which is a subclass of :class:`.DateTime`. This type has no special behavior, and is only present as a "marker" for this type; additionally, when a database column is reflected and the type is reported as ``DATE``, the time-supporting :class:`.oracle.DATE` type is used. .. versionchanged:: 0.9.4 Added :class:`.oracle.DATE` to subclass :class:`.DateTime`. This is a change as previous versions would reflect a ``DATE`` column as :class:`.types.DATE`, which subclasses :class:`.Date`. The only significance here is for schemes that are examining the type of column for use in special Python translations or for migrating schemas to other database backends. """ import re from sqlalchemy import util, sql from sqlalchemy.engine import default, base, reflection from sqlalchemy.sql import compiler, visitors, expression from sqlalchemy.sql import (operators as sql_operators, functions as sql_functions) from sqlalchemy import types as sqltypes, schema as sa_schema from sqlalchemy.types import VARCHAR, NVARCHAR, CHAR, \ BLOB, CLOB, TIMESTAMP, FLOAT RESERVED_WORDS = \ set('SHARE RAW DROP BETWEEN FROM DESC OPTION PRIOR LONG THEN ' 'DEFAULT ALTER IS INTO MINUS INTEGER NUMBER GRANT IDENTIFIED ' 'ALL TO ORDER ON FLOAT DATE HAVING CLUSTER NOWAIT RESOURCE ' 'ANY TABLE INDEX FOR UPDATE WHERE CHECK SMALLINT WITH DELETE ' 'BY ASC REVOKE LIKE SIZE RENAME NOCOMPRESS NULL GROUP VALUES ' 'AS IN VIEW EXCLUSIVE COMPRESS SYNONYM SELECT INSERT EXISTS ' 'NOT TRIGGER ELSE CREATE INTERSECT PCTFREE DISTINCT USER ' 'CONNECT SET MODE OF UNIQUE VARCHAR2 VARCHAR LOCK OR CHAR ' 'DECIMAL UNION PUBLIC AND START UID COMMENT CURRENT LEVEL'.split()) NO_ARG_FNS = set('UID CURRENT_DATE SYSDATE USER ' 'CURRENT_TIME CURRENT_TIMESTAMP'.split()) class RAW(sqltypes._Binary): __visit_name__ = 'RAW' OracleRaw = RAW class NCLOB(sqltypes.Text): __visit_name__ = 'NCLOB' class VARCHAR2(VARCHAR): __visit_name__ = 'VARCHAR2' NVARCHAR2 = NVARCHAR class NUMBER(sqltypes.Numeric, sqltypes.Integer): __visit_name__ = 'NUMBER' def __init__(self, precision=None, scale=None, asdecimal=None): if asdecimal is None: asdecimal = bool(scale and scale > 0) super(NUMBER, self).__init__( precision=precision, scale=scale, asdecimal=asdecimal) def adapt(self, impltype): ret = super(NUMBER, self).adapt(impltype) # leave a hint for the DBAPI handler ret._is_oracle_number = True return ret @property def _type_affinity(self): if bool(self.scale and self.scale > 0): return sqltypes.Numeric else: return sqltypes.Integer class DOUBLE_PRECISION(sqltypes.Numeric): __visit_name__ = 'DOUBLE_PRECISION' def __init__(self, precision=None, scale=None, asdecimal=None): if asdecimal is None: asdecimal = False super(DOUBLE_PRECISION, self).__init__( precision=precision, scale=scale, asdecimal=asdecimal) class BFILE(sqltypes.LargeBinary): __visit_name__ = 'BFILE' class LONG(sqltypes.Text): __visit_name__ = 'LONG' class DATE(sqltypes.DateTime): """Provide the oracle DATE type. This type has no special Python behavior, except that it subclasses :class:`.types.DateTime`; this is to suit the fact that the Oracle ``DATE`` type supports a time value. .. versionadded:: 0.9.4 """ __visit_name__ = 'DATE' def _compare_type_affinity(self, other): return other._type_affinity in (sqltypes.DateTime, sqltypes.Date) class INTERVAL(sqltypes.TypeEngine): __visit_name__ = 'INTERVAL' def __init__(self, day_precision=None, second_precision=None): """Construct an INTERVAL. Note that only DAY TO SECOND intervals are currently supported. This is due to a lack of support for YEAR TO MONTH intervals within available DBAPIs (cx_oracle and zxjdbc). :param day_precision: the day precision value. this is the number of digits to store for the day field. Defaults to "2" :param second_precision: the second precision value. this is the number of digits to store for the fractional seconds field. Defaults to "6". """ self.day_precision = day_precision self.second_precision = second_precision @classmethod def _adapt_from_generic_interval(cls, interval): return INTERVAL(day_precision=interval.day_precision, second_precision=interval.second_precision) @property def _type_affinity(self): return sqltypes.Interval class ROWID(sqltypes.TypeEngine): """Oracle ROWID type. When used in a cast() or similar, generates ROWID. """ __visit_name__ = 'ROWID' class _OracleBoolean(sqltypes.Boolean): def get_dbapi_type(self, dbapi): return dbapi.NUMBER colspecs = { sqltypes.Boolean: _OracleBoolean, sqltypes.Interval: INTERVAL, sqltypes.DateTime: DATE } ischema_names = { 'VARCHAR2': VARCHAR, 'NVARCHAR2': NVARCHAR, 'CHAR': CHAR, 'DATE': DATE, 'NUMBER': NUMBER, 'BLOB': BLOB, 'BFILE': BFILE, 'CLOB': CLOB, 'NCLOB': NCLOB, 'TIMESTAMP': TIMESTAMP, 'TIMESTAMP WITH TIME ZONE': TIMESTAMP, 'INTERVAL DAY TO SECOND': INTERVAL, 'RAW': RAW, 'FLOAT': FLOAT, 'DOUBLE PRECISION': DOUBLE_PRECISION, 'LONG': LONG, } class OracleTypeCompiler(compiler.GenericTypeCompiler): # Note: # Oracle DATE == DATETIME # Oracle does not allow milliseconds in DATE # Oracle does not support TIME columns def visit_datetime(self, type_): return self.visit_DATE(type_) def visit_float(self, type_): return self.visit_FLOAT(type_) def visit_unicode(self, type_): if self.dialect._supports_nchar: return self.visit_NVARCHAR2(type_) else: return self.visit_VARCHAR2(type_) def visit_INTERVAL(self, type_): return "INTERVAL DAY%s TO SECOND%s" % ( type_.day_precision is not None and "(%d)" % type_.day_precision or "", type_.second_precision is not None and "(%d)" % type_.second_precision or "", ) def visit_LONG(self, type_): return "LONG" def visit_TIMESTAMP(self, type_): if type_.timezone: return "TIMESTAMP WITH TIME ZONE" else: return "TIMESTAMP" def visit_DOUBLE_PRECISION(self, type_): return self._generate_numeric(type_, "DOUBLE PRECISION") def visit_NUMBER(self, type_, **kw): return self._generate_numeric(type_, "NUMBER", **kw) def _generate_numeric(self, type_, name, precision=None, scale=None): if precision is None: precision = type_.precision if scale is None: scale = getattr(type_, 'scale', None) if precision is None: return name elif scale is None: n = "%(name)s(%(precision)s)" return n % {'name': name, 'precision': precision} else: n = "%(name)s(%(precision)s, %(scale)s)" return n % {'name': name, 'precision': precision, 'scale': scale} def visit_string(self, type_): return self.visit_VARCHAR2(type_) def visit_VARCHAR2(self, type_): return self._visit_varchar(type_, '', '2') def visit_NVARCHAR2(self, type_): return self._visit_varchar(type_, 'N', '2') visit_NVARCHAR = visit_NVARCHAR2 def visit_VARCHAR(self, type_): return self._visit_varchar(type_, '', '') def _visit_varchar(self, type_, n, num): if not type_.length: return "%(n)sVARCHAR%(two)s" % {'two': num, 'n': n} elif not n and self.dialect._supports_char_length: varchar = "VARCHAR%(two)s(%(length)s CHAR)" return varchar % {'length': type_.length, 'two': num} else: varchar = "%(n)sVARCHAR%(two)s(%(length)s)" return varchar % {'length': type_.length, 'two': num, 'n': n} def visit_text(self, type_): return self.visit_CLOB(type_) def visit_unicode_text(self, type_): if self.dialect._supports_nchar: return self.visit_NCLOB(type_) else: return self.visit_CLOB(type_) def visit_large_binary(self, type_): return self.visit_BLOB(type_) def visit_big_integer(self, type_): return self.visit_NUMBER(type_, precision=19) def visit_boolean(self, type_): return self.visit_SMALLINT(type_) def visit_RAW(self, type_): if type_.length: return "RAW(%(length)s)" % {'length': type_.length} else: return "RAW" def visit_ROWID(self, type_): return "ROWID" class OracleCompiler(compiler.SQLCompiler): """Oracle compiler modifies the lexical structure of Select statements to work under non-ANSI configured Oracle databases, if the use_ansi flag is False. """ compound_keywords = util.update_copy( compiler.SQLCompiler.compound_keywords, { expression.CompoundSelect.EXCEPT: 'MINUS' } ) def __init__(self, *args, **kwargs): self.__wheres = {} self._quoted_bind_names = {} super(OracleCompiler, self).__init__(*args, **kwargs) def visit_mod_binary(self, binary, operator, **kw): return "mod(%s, %s)" % (self.process(binary.left, **kw), self.process(binary.right, **kw)) def visit_now_func(self, fn, **kw): return "CURRENT_TIMESTAMP" def visit_char_length_func(self, fn, **kw): return "LENGTH" + self.function_argspec(fn, **kw) def visit_match_op_binary(self, binary, operator, **kw): return "CONTAINS (%s, %s)" % (self.process(binary.left), self.process(binary.right)) def visit_true(self, expr, **kw): return '1' def visit_false(self, expr, **kw): return '0' def get_select_hint_text(self, byfroms): return " ".join( "/*+ %s */" % text for table, text in byfroms.items() ) def function_argspec(self, fn, **kw): if len(fn.clauses) > 0 or fn.name.upper() not in NO_ARG_FNS: return compiler.SQLCompiler.function_argspec(self, fn, **kw) else: return "" def default_from(self): """Called when a ``SELECT`` statement has no froms, and no ``FROM`` clause is to be appended. The Oracle compiler tacks a "FROM DUAL" to the statement. """ return " FROM DUAL" def visit_join(self, join, **kwargs): if self.dialect.use_ansi: return compiler.SQLCompiler.visit_join(self, join, **kwargs) else: kwargs['asfrom'] = True if isinstance(join.right, expression.FromGrouping): right = join.right.element else: right = join.right return self.process(join.left, **kwargs) + \ ", " + self.process(right, **kwargs) def _get_nonansi_join_whereclause(self, froms): clauses = [] def visit_join(join): if join.isouter: def visit_binary(binary): if binary.operator == sql_operators.eq: if join.right.is_derived_from(binary.left.table): binary.left = _OuterJoinColumn(binary.left) elif join.right.is_derived_from(binary.right.table): binary.right = _OuterJoinColumn(binary.right) clauses.append(visitors.cloned_traverse( join.onclause, {}, {'binary': visit_binary})) else: clauses.append(join.onclause) for j in join.left, join.right: if isinstance(j, expression.Join): visit_join(j) elif isinstance(j, expression.FromGrouping): visit_join(j.element) for f in froms: if isinstance(f, expression.Join): visit_join(f) if not clauses: return None else: return sql.and_(*clauses) def visit_outer_join_column(self, vc): return self.process(vc.column) + "(+)" def visit_sequence(self, seq): return (self.dialect.identifier_preparer.format_sequence(seq) + ".nextval") def visit_alias(self, alias, asfrom=False, ashint=False, **kwargs): """Oracle doesn't like ``FROM table AS alias``. Is the AS standard SQL?? """ if asfrom or ashint: alias_name = isinstance(alias.name, expression._truncated_label) and \ self._truncated_identifier("alias", alias.name) or alias.name if ashint: return alias_name elif asfrom: return self.process(alias.original, asfrom=asfrom, **kwargs) + \ " " + self.preparer.format_alias(alias, alias_name) else: return self.process(alias.original, **kwargs) def returning_clause(self, stmt, returning_cols): columns = [] binds = [] for i, column in enumerate( expression._select_iterables(returning_cols)): if column.type._has_column_expression: col_expr = column.type.column_expression(column) else: col_expr = column outparam = sql.outparam("ret_%d" % i, type_=column.type) self.binds[outparam.key] = outparam binds.append( self.bindparam_string(self._truncate_bindparam(outparam))) columns.append( self.process(col_expr, within_columns_clause=False)) self.result_map[outparam.key] = ( outparam.key, (column, getattr(column, 'name', None), getattr(column, 'key', None)), column.type ) return 'RETURNING ' + ', '.join(columns) + " INTO " + ", ".join(binds) def _TODO_visit_compound_select(self, select): """Need to determine how to get ``LIMIT``/``OFFSET`` into a ``UNION`` for Oracle. """ pass def visit_select(self, select, **kwargs): """Look for ``LIMIT`` and OFFSET in a select statement, and if so tries to wrap it in a subquery with ``rownum`` criterion. """ if not getattr(select, '_oracle_visit', None): if not self.dialect.use_ansi: froms = self._display_froms_for_select( select, kwargs.get('asfrom', False)) whereclause = self._get_nonansi_join_whereclause(froms) if whereclause is not None: select = select.where(whereclause) select._oracle_visit = True if select._limit is not None or select._offset is not None: # See http://www.oracle.com/technology/oramag/oracle/06-sep/\ # o56asktom.html # # Generalized form of an Oracle pagination query: # select ... from ( # select /*+ FIRST_ROWS(N) */ ...., rownum as ora_rn from # ( select distinct ... where ... order by ... # ) where ROWNUM <= :limit+:offset # ) where ora_rn > :offset # Outer select and "ROWNUM as ora_rn" can be dropped if # limit=0 # TODO: use annotations instead of clone + attr set ? select = select._generate() select._oracle_visit = True # Wrap the middle select and add the hint limitselect = sql.select([c for c in select.c]) if select._limit and self.dialect.optimize_limits: limitselect = limitselect.prefix_with( "/*+ FIRST_ROWS(%d) */" % select._limit) limitselect._oracle_visit = True limitselect._is_wrapper = True # If needed, add the limiting clause if select._limit is not None: max_row = select._limit if select._offset is not None: max_row += select._offset if not self.dialect.use_binds_for_limits: max_row = sql.literal_column("%d" % max_row) limitselect.append_whereclause( sql.literal_column("ROWNUM") <= max_row) # If needed, add the ora_rn, and wrap again with offset. if select._offset is None: limitselect._for_update_arg = select._for_update_arg select = limitselect else: limitselect = limitselect.column( sql.literal_column("ROWNUM").label("ora_rn")) limitselect._oracle_visit = True limitselect._is_wrapper = True offsetselect = sql.select( [c for c in limitselect.c if c.key != 'ora_rn']) offsetselect._oracle_visit = True offsetselect._is_wrapper = True offset_value = select._offset if not self.dialect.use_binds_for_limits: offset_value = sql.literal_column("%d" % offset_value) offsetselect.append_whereclause( sql.literal_column("ora_rn") > offset_value) offsetselect._for_update_arg = select._for_update_arg select = offsetselect kwargs['iswrapper'] = getattr(select, '_is_wrapper', False) return compiler.SQLCompiler.visit_select(self, select, **kwargs) def limit_clause(self, select): return "" def for_update_clause(self, select): if self.is_subquery(): return "" tmp = ' FOR UPDATE' if select._for_update_arg.of: tmp += ' OF ' + ', '.join( self.process(elem) for elem in select._for_update_arg.of ) if select._for_update_arg.nowait: tmp += " NOWAIT" return tmp class OracleDDLCompiler(compiler.DDLCompiler): def define_constraint_cascades(self, constraint): text = "" if constraint.ondelete is not None: text += " ON DELETE %s" % constraint.ondelete # oracle has no ON UPDATE CASCADE - # its only available via triggers # http://asktom.oracle.com/tkyte/update_cascade/index.html if constraint.onupdate is not None: util.warn( "Oracle does not contain native UPDATE CASCADE " "functionality - onupdates will not be rendered for foreign " "keys. Consider using deferrable=True, initially='deferred' " "or triggers.") return text def visit_create_index(self, create, **kw): return super(OracleDDLCompiler, self).\ visit_create_index(create, include_schema=True) class OracleIdentifierPreparer(compiler.IdentifierPreparer): reserved_words = set([x.lower() for x in RESERVED_WORDS]) illegal_initial_characters = set( (str(dig) for dig in range(0, 10))).union(["_", "$"]) def _bindparam_requires_quotes(self, value): """Return True if the given identifier requires quoting.""" lc_value = value.lower() return (lc_value in self.reserved_words or value[0] in self.illegal_initial_characters or not self.legal_characters.match(util.text_type(value)) ) def format_savepoint(self, savepoint): name = re.sub(r'^_+', '', savepoint.ident) return super( OracleIdentifierPreparer, self).format_savepoint(savepoint, name) class OracleExecutionContext(default.DefaultExecutionContext): def fire_sequence(self, seq, type_): return self._execute_scalar( "SELECT " + self.dialect.identifier_preparer.format_sequence(seq) + ".nextval FROM DUAL", type_) class OracleDialect(default.DefaultDialect): name = 'oracle' supports_alter = True supports_unicode_statements = False supports_unicode_binds = False max_identifier_length = 30 supports_sane_rowcount = True supports_sane_multi_rowcount = False supports_sequences = True sequences_optional = False postfetch_lastrowid = False default_paramstyle = 'named' colspecs = colspecs ischema_names = ischema_names requires_name_normalize = True supports_default_values = False supports_empty_insert = False statement_compiler = OracleCompiler ddl_compiler = OracleDDLCompiler type_compiler = OracleTypeCompiler preparer = OracleIdentifierPreparer execution_ctx_cls = OracleExecutionContext reflection_options = ('oracle_resolve_synonyms', ) construct_arguments = [ (sa_schema.Table, {"resolve_synonyms": False}) ] def __init__(self, use_ansi=True, optimize_limits=False, use_binds_for_limits=True, **kwargs): default.DefaultDialect.__init__(self, **kwargs) self.use_ansi = use_ansi self.optimize_limits = optimize_limits self.use_binds_for_limits = use_binds_for_limits def initialize(self, connection): super(OracleDialect, self).initialize(connection) self.implicit_returning = self.__dict__.get( 'implicit_returning', self.server_version_info > (10, ) ) if self._is_oracle_8: self.colspecs = self.colspecs.copy() self.colspecs.pop(sqltypes.Interval) self.use_ansi = False @property def _is_oracle_8(self): return self.server_version_info and \ self.server_version_info < (9, ) @property def _supports_char_length(self): return not self._is_oracle_8 @property def _supports_nchar(self): return not self._is_oracle_8 def do_release_savepoint(self, connection, name): # Oracle does not support RELEASE SAVEPOINT pass def has_table(self, connection, table_name, schema=None): if not schema: schema = self.default_schema_name cursor = connection.execute( sql.text("SELECT table_name FROM all_tables " "WHERE table_name = :name AND owner = :schema_name"), name=self.denormalize_name(table_name), schema_name=self.denormalize_name(schema)) return cursor.first() is not None def has_sequence(self, connection, sequence_name, schema=None): if not schema: schema = self.default_schema_name cursor = connection.execute( sql.text("SELECT sequence_name FROM all_sequences " "WHERE sequence_name = :name AND " "sequence_owner = :schema_name"), name=self.denormalize_name(sequence_name), schema_name=self.denormalize_name(schema)) return cursor.first() is not None def normalize_name(self, name): if name is None: return None if util.py2k: if isinstance(name, str): name = name.decode(self.encoding) if name.upper() == name and not \ self.identifier_preparer._requires_quotes(name.lower()): return name.lower() else: return name def denormalize_name(self, name): if name is None: return None elif name.lower() == name and not \ self.identifier_preparer._requires_quotes(name.lower()): name = name.upper() if util.py2k: if not self.supports_unicode_binds: name = name.encode(self.encoding) else: name = unicode(name) return name def _get_default_schema_name(self, connection): return self.normalize_name( connection.execute('SELECT USER FROM DUAL').scalar()) def _resolve_synonym(self, connection, desired_owner=None, desired_synonym=None, desired_table=None): """search for a local synonym matching the given desired owner/name. if desired_owner is None, attempts to locate a distinct owner. returns the actual name, owner, dblink name, and synonym name if found. """ q = "SELECT owner, table_owner, table_name, db_link, "\ "synonym_name FROM all_synonyms WHERE " clauses = [] params = {} if desired_synonym: clauses.append("synonym_name = :synonym_name") params['synonym_name'] = desired_synonym if desired_owner: clauses.append("owner = :desired_owner") params['desired_owner'] = desired_owner if desired_table: clauses.append("table_name = :tname") params['tname'] = desired_table q += " AND ".join(clauses) result = connection.execute(sql.text(q), **params) if desired_owner: row = result.first() if row: return (row['table_name'], row['table_owner'], row['db_link'], row['synonym_name']) else: return None, None, None, None else: rows = result.fetchall() if len(rows) > 1: raise AssertionError( "There are multiple tables visible to the schema, you " "must specify owner") elif len(rows) == 1: row = rows[0] return (row['table_name'], row['table_owner'], row['db_link'], row['synonym_name']) else: return None, None, None, None @reflection.cache def _prepare_reflection_args(self, connection, table_name, schema=None, resolve_synonyms=False, dblink='', **kw): if resolve_synonyms: actual_name, owner, dblink, synonym = self._resolve_synonym( connection, desired_owner=self.denormalize_name(schema), desired_synonym=self.denormalize_name(table_name) ) else: actual_name, owner, dblink, synonym = None, None, None, None if not actual_name: actual_name = self.denormalize_name(table_name) if dblink: # using user_db_links here since all_db_links appears # to have more restricted permissions. # http://docs.oracle.com/cd/B28359_01/server.111/b28310/ds_admin005.htm # will need to hear from more users if we are doing # the right thing here. See [ticket:2619] owner = connection.scalar( sql.text("SELECT username FROM user_db_links " "WHERE db_link=:link"), link=dblink) dblink = "@" + dblink elif not owner: owner = self.denormalize_name(schema or self.default_schema_name) return (actual_name, owner, dblink or '', synonym) @reflection.cache def get_schema_names(self, connection, **kw): s = "SELECT username FROM all_users ORDER BY username" cursor = connection.execute(s,) return [self.normalize_name(row[0]) for row in cursor] @reflection.cache def get_table_names(self, connection, schema=None, **kw): schema = self.denormalize_name(schema or self.default_schema_name) # note that table_names() isn't loading DBLINKed or synonym'ed tables if schema is None: schema = self.default_schema_name s = sql.text( "SELECT table_name FROM all_tables " "WHERE nvl(tablespace_name, 'no tablespace') NOT IN " "('SYSTEM', 'SYSAUX') " "AND OWNER = :owner " "AND IOT_NAME IS NULL") cursor = connection.execute(s, owner=schema) return [self.normalize_name(row[0]) for row in cursor] @reflection.cache def get_view_names(self, connection, schema=None, **kw): schema = self.denormalize_name(schema or self.default_schema_name) s = sql.text("SELECT view_name FROM all_views WHERE owner = :owner") cursor = connection.execute(s, owner=self.denormalize_name(schema)) return [self.normalize_name(row[0]) for row in cursor] @reflection.cache def get_columns(self, connection, table_name, schema=None, **kw): """ kw arguments can be: oracle_resolve_synonyms dblink """ resolve_synonyms = kw.get('oracle_resolve_synonyms', False) dblink = kw.get('dblink', '') info_cache = kw.get('info_cache') (table_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache) columns = [] if self._supports_char_length: char_length_col = 'char_length' else: char_length_col = 'data_length' params = {"table_name": table_name} text = "SELECT column_name, data_type, %(char_length_col)s, "\ "data_precision, data_scale, "\ "nullable, data_default FROM ALL_TAB_COLUMNS%(dblink)s "\ "WHERE table_name = :table_name" if schema is not None: params['owner'] = schema text += " AND owner = :owner " text += " ORDER BY column_id" text = text % {'dblink': dblink, 'char_length_col': char_length_col} c = connection.execute(sql.text(text), **params) for row in c: (colname, orig_colname, coltype, length, precision, scale, nullable, default) = \ (self.normalize_name(row[0]), row[0], row[1], row[ 2], row[3], row[4], row[5] == 'Y', row[6]) if coltype == 'NUMBER': coltype = NUMBER(precision, scale) elif coltype in ('VARCHAR2', 'NVARCHAR2', 'CHAR'): coltype = self.ischema_names.get(coltype)(length) elif 'WITH TIME ZONE' in coltype: coltype = TIMESTAMP(timezone=True) else: coltype = re.sub(r'\(\d+\)', '', coltype) try: coltype = self.ischema_names[coltype] except KeyError: util.warn("Did not recognize type '%s' of column '%s'" % (coltype, colname)) coltype = sqltypes.NULLTYPE cdict = { 'name': colname, 'type': coltype, 'nullable': nullable, 'default': default, 'autoincrement': default is None } if orig_colname.lower() == orig_colname: cdict['quote'] = True columns.append(cdict) return columns @reflection.cache def get_indexes(self, connection, table_name, schema=None, resolve_synonyms=False, dblink='', **kw): info_cache = kw.get('info_cache') (table_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache) indexes = [] params = {'table_name': table_name} text = \ "SELECT a.index_name, a.column_name, b.uniqueness "\ "\nFROM ALL_IND_COLUMNS%(dblink)s a, "\ "\nALL_INDEXES%(dblink)s b "\ "\nWHERE "\ "\na.index_name = b.index_name "\ "\nAND a.table_owner = b.table_owner "\ "\nAND a.table_name = b.table_name "\ "\nAND a.table_name = :table_name " if schema is not None: params['schema'] = schema text += "AND a.table_owner = :schema " text += "ORDER BY a.index_name, a.column_position" text = text % {'dblink': dblink} q = sql.text(text) rp = connection.execute(q, **params) indexes = [] last_index_name = None pk_constraint = self.get_pk_constraint( connection, table_name, schema, resolve_synonyms=resolve_synonyms, dblink=dblink, info_cache=kw.get('info_cache')) pkeys = pk_constraint['constrained_columns'] uniqueness = dict(NONUNIQUE=False, UNIQUE=True) oracle_sys_col = re.compile(r'SYS_NC\d+\$', re.IGNORECASE) def upper_name_set(names): return set([i.upper() for i in names]) pk_names = upper_name_set(pkeys) def remove_if_primary_key(index): # don't include the primary key index if index is not None and \ upper_name_set(index['column_names']) == pk_names: indexes.pop() index = None for rset in rp: if rset.index_name != last_index_name: remove_if_primary_key(index) index = dict(name=self.normalize_name(rset.index_name), column_names=[]) indexes.append(index) index['unique'] = uniqueness.get(rset.uniqueness, False) # filter out Oracle SYS_NC names. could also do an outer join # to the all_tab_columns table and check for real col names there. if not oracle_sys_col.match(rset.column_name): index['column_names'].append( self.normalize_name(rset.column_name)) last_index_name = rset.index_name remove_if_primary_key(index) return indexes @reflection.cache def _get_constraint_data(self, connection, table_name, schema=None, dblink='', **kw): params = {'table_name': table_name} text = \ "SELECT"\ "\nac.constraint_name,"\ "\nac.constraint_type,"\ "\nloc.column_name AS local_column,"\ "\nrem.table_name AS remote_table,"\ "\nrem.column_name AS remote_column,"\ "\nrem.owner AS remote_owner,"\ "\nloc.position as loc_pos,"\ "\nrem.position as rem_pos"\ "\nFROM all_constraints%(dblink)s ac,"\ "\nall_cons_columns%(dblink)s loc,"\ "\nall_cons_columns%(dblink)s rem"\ "\nWHERE ac.table_name = :table_name"\ "\nAND ac.constraint_type IN ('R','P')" if schema is not None: params['owner'] = schema text += "\nAND ac.owner = :owner" text += \ "\nAND ac.owner = loc.owner"\ "\nAND ac.constraint_name = loc.constraint_name"\ "\nAND ac.r_owner = rem.owner(+)"\ "\nAND ac.r_constraint_name = rem.constraint_name(+)"\ "\nAND (rem.position IS NULL or loc.position=rem.position)"\ "\nORDER BY ac.constraint_name, loc.position" text = text % {'dblink': dblink} rp = connection.execute(sql.text(text), **params) constraint_data = rp.fetchall() return constraint_data @reflection.cache def get_pk_constraint(self, connection, table_name, schema=None, **kw): resolve_synonyms = kw.get('oracle_resolve_synonyms', False) dblink = kw.get('dblink', '') info_cache = kw.get('info_cache') (table_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache) pkeys = [] constraint_name = None constraint_data = self._get_constraint_data( connection, table_name, schema, dblink, info_cache=kw.get('info_cache')) for row in constraint_data: (cons_name, cons_type, local_column, remote_table, remote_column, remote_owner) = \ row[0:2] + tuple([self.normalize_name(x) for x in row[2:6]]) if cons_type == 'P': if constraint_name is None: constraint_name = self.normalize_name(cons_name) pkeys.append(local_column) return {'constrained_columns': pkeys, 'name': constraint_name} @reflection.cache def get_foreign_keys(self, connection, table_name, schema=None, **kw): """ kw arguments can be: oracle_resolve_synonyms dblink """ requested_schema = schema # to check later on resolve_synonyms = kw.get('oracle_resolve_synonyms', False) dblink = kw.get('dblink', '') info_cache = kw.get('info_cache') (table_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache) constraint_data = self._get_constraint_data( connection, table_name, schema, dblink, info_cache=kw.get('info_cache')) def fkey_rec(): return { 'name': None, 'constrained_columns': [], 'referred_schema': None, 'referred_table': None, 'referred_columns': [] } fkeys = util.defaultdict(fkey_rec) for row in constraint_data: (cons_name, cons_type, local_column, remote_table, remote_column, remote_owner) = \ row[0:2] + tuple([self.normalize_name(x) for x in row[2:6]]) if cons_type == 'R': if remote_table is None: # ticket 363 util.warn( ("Got 'None' querying 'table_name' from " "all_cons_columns%(dblink)s - does the user have " "proper rights to the table?") % {'dblink': dblink}) continue rec = fkeys[cons_name] rec['name'] = cons_name local_cols, remote_cols = rec[ 'constrained_columns'], rec['referred_columns'] if not rec['referred_table']: if resolve_synonyms: ref_remote_name, ref_remote_owner, ref_dblink, ref_synonym = \ self._resolve_synonym( connection, desired_owner=self.denormalize_name( remote_owner), desired_table=self.denormalize_name( remote_table) ) if ref_synonym: remote_table = self.normalize_name(ref_synonym) remote_owner = self.normalize_name( ref_remote_owner) rec['referred_table'] = remote_table if requested_schema is not None or \ self.denormalize_name(remote_owner) != schema: rec['referred_schema'] = remote_owner local_cols.append(local_column) remote_cols.append(remote_column) return list(fkeys.values()) @reflection.cache def get_view_definition(self, connection, view_name, schema=None, resolve_synonyms=False, dblink='', **kw): info_cache = kw.get('info_cache') (view_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, view_name, schema, resolve_synonyms, dblink, info_cache=info_cache) params = {'view_name': view_name} text = "SELECT text FROM all_views WHERE view_name=:view_name" if schema is not None: text += " AND owner = :schema" params['schema'] = schema rp = connection.execute(sql.text(text), **params).scalar() if rp: if util.py2k: rp = rp.decode(self.encoding) return rp else: return None class _OuterJoinColumn(sql.ClauseElement): __visit_name__ = 'outer_join_column' def __init__(self, column): self.column = column
xfournet/intellij-community
refs/heads/master
python/testData/refactoring/changeSignature/removeKeyedParam.after.py
83
def retry(tries, delay=3, backoff=1, exceptions_to_check=Exception, retry_for_lambda=None): print "tries", tries print "log", log print "delay", delay print "backoff", backoff print "exceptions_to_check", exceptions_to_check print "retry_for_lambda", retry_for_lambda retry(3, 2, retry_for_lambda=lambda x: not x)
x111ong/django
refs/heads/master
django/core/mail/backends/dummy.py
835
""" Dummy email backend that does nothing. """ from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def send_messages(self, email_messages): return len(list(email_messages))
jaysonsantos/servo
refs/heads/master
tests/wpt/web-platform-tests/tools/pytest/testing/test_conftest.py
171
from textwrap import dedent import _pytest._code import py import pytest from _pytest.config import PytestPluginManager from _pytest.main import EXIT_NOTESTSCOLLECTED, EXIT_USAGEERROR @pytest.fixture(scope="module", params=["global", "inpackage"]) def basedir(request, tmpdir_factory): from _pytest.tmpdir import tmpdir tmpdir = tmpdir(request, tmpdir_factory) tmpdir.ensure("adir/conftest.py").write("a=1 ; Directory = 3") tmpdir.ensure("adir/b/conftest.py").write("b=2 ; a = 1.5") if request.param == "inpackage": tmpdir.ensure("adir/__init__.py") tmpdir.ensure("adir/b/__init__.py") return tmpdir def ConftestWithSetinitial(path): conftest = PytestPluginManager() conftest_setinitial(conftest, [path]) return conftest def conftest_setinitial(conftest, args, confcutdir=None): class Namespace: def __init__(self): self.file_or_dir = args self.confcutdir = str(confcutdir) self.noconftest = False conftest._set_initial_conftests(Namespace()) class TestConftestValueAccessGlobal: def test_basic_init(self, basedir): conftest = PytestPluginManager() p = basedir.join("adir") assert conftest._rget_with_confmod("a", p)[1] == 1 def test_immediate_initialiation_and_incremental_are_the_same(self, basedir): conftest = PytestPluginManager() len(conftest._path2confmods) conftest._getconftestmodules(basedir) snap1 = len(conftest._path2confmods) #assert len(conftest._path2confmods) == snap1 + 1 conftest._getconftestmodules(basedir.join('adir')) assert len(conftest._path2confmods) == snap1 + 1 conftest._getconftestmodules(basedir.join('b')) assert len(conftest._path2confmods) == snap1 + 2 def test_value_access_not_existing(self, basedir): conftest = ConftestWithSetinitial(basedir) with pytest.raises(KeyError): conftest._rget_with_confmod('a', basedir) def test_value_access_by_path(self, basedir): conftest = ConftestWithSetinitial(basedir) adir = basedir.join("adir") assert conftest._rget_with_confmod("a", adir)[1] == 1 assert conftest._rget_with_confmod("a", adir.join("b"))[1] == 1.5 def test_value_access_with_confmod(self, basedir): startdir = basedir.join("adir", "b") startdir.ensure("xx", dir=True) conftest = ConftestWithSetinitial(startdir) mod, value = conftest._rget_with_confmod("a", startdir) assert value == 1.5 path = py.path.local(mod.__file__) assert path.dirpath() == basedir.join("adir", "b") assert path.purebasename.startswith("conftest") def test_conftest_in_nonpkg_with_init(tmpdir): tmpdir.ensure("adir-1.0/conftest.py").write("a=1 ; Directory = 3") tmpdir.ensure("adir-1.0/b/conftest.py").write("b=2 ; a = 1.5") tmpdir.ensure("adir-1.0/b/__init__.py") tmpdir.ensure("adir-1.0/__init__.py") ConftestWithSetinitial(tmpdir.join("adir-1.0", "b")) def test_doubledash_considered(testdir): conf = testdir.mkdir("--option") conf.join("conftest.py").ensure() conftest = PytestPluginManager() conftest_setinitial(conftest, [conf.basename, conf.basename]) l = conftest._getconftestmodules(conf) assert len(l) == 1 def test_issue151_load_all_conftests(testdir): names = "code proj src".split() for name in names: p = testdir.mkdir(name) p.ensure("conftest.py") conftest = PytestPluginManager() conftest_setinitial(conftest, names) d = list(conftest._conftestpath2mod.values()) assert len(d) == len(names) def test_conftest_global_import(testdir): testdir.makeconftest("x=3") p = testdir.makepyfile(""" import py, pytest from _pytest.config import PytestPluginManager conf = PytestPluginManager() mod = conf._importconftest(py.path.local("conftest.py")) assert mod.x == 3 import conftest assert conftest is mod, (conftest, mod) subconf = py.path.local().ensure("sub", "conftest.py") subconf.write("y=4") mod2 = conf._importconftest(subconf) assert mod != mod2 assert mod2.y == 4 import conftest assert conftest is mod2, (conftest, mod) """) res = testdir.runpython(p) assert res.ret == 0 def test_conftestcutdir(testdir): conf = testdir.makeconftest("") p = testdir.mkdir("x") conftest = PytestPluginManager() conftest_setinitial(conftest, [testdir.tmpdir], confcutdir=p) l = conftest._getconftestmodules(p) assert len(l) == 0 l = conftest._getconftestmodules(conf.dirpath()) assert len(l) == 0 assert conf not in conftest._conftestpath2mod # but we can still import a conftest directly conftest._importconftest(conf) l = conftest._getconftestmodules(conf.dirpath()) assert l[0].__file__.startswith(str(conf)) # and all sub paths get updated properly l = conftest._getconftestmodules(p) assert len(l) == 1 assert l[0].__file__.startswith(str(conf)) def test_conftestcutdir_inplace_considered(testdir): conf = testdir.makeconftest("") conftest = PytestPluginManager() conftest_setinitial(conftest, [conf.dirpath()], confcutdir=conf.dirpath()) l = conftest._getconftestmodules(conf.dirpath()) assert len(l) == 1 assert l[0].__file__.startswith(str(conf)) @pytest.mark.parametrize("name", 'test tests whatever .dotdir'.split()) def test_setinitial_conftest_subdirs(testdir, name): sub = testdir.mkdir(name) subconftest = sub.ensure("conftest.py") conftest = PytestPluginManager() conftest_setinitial(conftest, [sub.dirpath()], confcutdir=testdir.tmpdir) if name not in ('whatever', '.dotdir'): assert subconftest in conftest._conftestpath2mod assert len(conftest._conftestpath2mod) == 1 else: assert subconftest not in conftest._conftestpath2mod assert len(conftest._conftestpath2mod) == 0 def test_conftest_confcutdir(testdir): testdir.makeconftest("assert 0") x = testdir.mkdir("x") x.join("conftest.py").write(_pytest._code.Source(""" def pytest_addoption(parser): parser.addoption("--xyz", action="store_true") """)) result = testdir.runpytest("-h", "--confcutdir=%s" % x, x) result.stdout.fnmatch_lines(["*--xyz*"]) assert 'warning: could not load initial' not in result.stdout.str() def test_no_conftest(testdir): testdir.makeconftest("assert 0") result = testdir.runpytest("--noconftest") assert result.ret == EXIT_NOTESTSCOLLECTED result = testdir.runpytest() assert result.ret == EXIT_USAGEERROR def test_conftest_existing_resultlog(testdir): x = testdir.mkdir("tests") x.join("conftest.py").write(_pytest._code.Source(""" def pytest_addoption(parser): parser.addoption("--xyz", action="store_true") """)) testdir.makefile(ext=".log", result="") # Writes result.log result = testdir.runpytest("-h", "--resultlog", "result.log") result.stdout.fnmatch_lines(["*--xyz*"]) def test_conftest_existing_junitxml(testdir): x = testdir.mkdir("tests") x.join("conftest.py").write(_pytest._code.Source(""" def pytest_addoption(parser): parser.addoption("--xyz", action="store_true") """)) testdir.makefile(ext=".xml", junit="") # Writes junit.xml result = testdir.runpytest("-h", "--junitxml", "junit.xml") result.stdout.fnmatch_lines(["*--xyz*"]) def test_conftest_import_order(testdir, monkeypatch): ct1 = testdir.makeconftest("") sub = testdir.mkdir("sub") ct2 = sub.join("conftest.py") ct2.write("") def impct(p): return p conftest = PytestPluginManager() monkeypatch.setattr(conftest, '_importconftest', impct) assert conftest._getconftestmodules(sub) == [ct1, ct2] def test_fixture_dependency(testdir, monkeypatch): ct1 = testdir.makeconftest("") ct1 = testdir.makepyfile("__init__.py") ct1.write("") sub = testdir.mkdir("sub") sub.join("__init__.py").write("") sub.join("conftest.py").write(py.std.textwrap.dedent(""" import pytest @pytest.fixture def not_needed(): assert False, "Should not be called!" @pytest.fixture def foo(): assert False, "Should not be called!" @pytest.fixture def bar(foo): return 'bar' """)) subsub = sub.mkdir("subsub") subsub.join("__init__.py").write("") subsub.join("test_bar.py").write(py.std.textwrap.dedent(""" import pytest @pytest.fixture def bar(): return 'sub bar' def test_event_fixture(bar): assert bar == 'sub bar' """)) result = testdir.runpytest("sub") result.stdout.fnmatch_lines(["*1 passed*"]) def test_conftest_found_with_double_dash(testdir): sub = testdir.mkdir("sub") sub.join("conftest.py").write(py.std.textwrap.dedent(""" def pytest_addoption(parser): parser.addoption("--hello-world", action="store_true") """)) p = sub.join("test_hello.py") p.write(py.std.textwrap.dedent(""" import pytest def test_hello(found): assert found == 1 """)) result = testdir.runpytest(str(p) + "::test_hello", "-h") result.stdout.fnmatch_lines(""" *--hello-world* """) class TestConftestVisibility: def _setup_tree(self, testdir): # for issue616 # example mostly taken from: # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html runner = testdir.mkdir("empty") package = testdir.mkdir("package") package.join("conftest.py").write(dedent("""\ import pytest @pytest.fixture def fxtr(): return "from-package" """)) package.join("test_pkgroot.py").write(dedent("""\ def test_pkgroot(fxtr): assert fxtr == "from-package" """)) swc = package.mkdir("swc") swc.join("__init__.py").ensure() swc.join("conftest.py").write(dedent("""\ import pytest @pytest.fixture def fxtr(): return "from-swc" """)) swc.join("test_with_conftest.py").write(dedent("""\ def test_with_conftest(fxtr): assert fxtr == "from-swc" """)) snc = package.mkdir("snc") snc.join("__init__.py").ensure() snc.join("test_no_conftest.py").write(dedent("""\ def test_no_conftest(fxtr): assert fxtr == "from-package" # No local conftest.py, so should # use value from parent dir's """)) print ("created directory structure:") for x in testdir.tmpdir.visit(): print (" " + x.relto(testdir.tmpdir)) return { "runner": runner, "package": package, "swc": swc, "snc": snc} # N.B.: "swc" stands for "subdir with conftest.py" # "snc" stands for "subdir no [i.e. without] conftest.py" @pytest.mark.parametrize("chdir,testarg,expect_ntests_passed", [ # Effective target: package/.. ("runner", "..", 3), ("package", "..", 3), ("swc", "../..", 3), ("snc", "../..", 3), # Effective target: package ("runner", "../package", 3), ("package", ".", 3), ("swc", "..", 3), ("snc", "..", 3), # Effective target: package/swc ("runner", "../package/swc", 1), ("package", "./swc", 1), ("swc", ".", 1), ("snc", "../swc", 1), # Effective target: package/snc ("runner", "../package/snc", 1), ("package", "./snc", 1), ("swc", "../snc", 1), ("snc", ".", 1), ]) @pytest.mark.issue616 def test_parsefactories_relative_node_ids( self, testdir, chdir,testarg, expect_ntests_passed): dirs = self._setup_tree(testdir) print("pytest run in cwd: %s" %( dirs[chdir].relto(testdir.tmpdir))) print("pytestarg : %s" %(testarg)) print("expected pass : %s" %(expect_ntests_passed)) with dirs[chdir].as_cwd(): reprec = testdir.inline_run(testarg, "-q", "--traceconfig") reprec.assertoutcome(passed=expect_ntests_passed) @pytest.mark.parametrize('confcutdir,passed,error', [ ('.', 2, 0), ('src', 1, 1), (None, 1, 1), ]) def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error): """Test that conftest files are detected only up to a ini file, unless an explicit --confcutdir option is given. """ root = testdir.tmpdir src = root.join('src').ensure(dir=1) src.join('pytest.ini').write('[pytest]') src.join('conftest.py').write(_pytest._code.Source(""" import pytest @pytest.fixture def fix1(): pass """)) src.join('test_foo.py').write(_pytest._code.Source(""" def test_1(fix1): pass def test_2(out_of_reach): pass """)) root.join('conftest.py').write(_pytest._code.Source(""" import pytest @pytest.fixture def out_of_reach(): pass """)) args = [str(src)] if confcutdir: args = ['--confcutdir=%s' % root.join(confcutdir)] result = testdir.runpytest(*args) match = '' if passed: match += '*%d passed*' % passed if error: match += '*%d error*' % error result.stdout.fnmatch_lines(match) def test_issue1073_conftest_special_objects(testdir): testdir.makeconftest(""" class DontTouchMe: def __getattr__(self, x): raise Exception('cant touch me') x = DontTouchMe() """) testdir.makepyfile(""" def test_some(): pass """) res = testdir.runpytest() assert res.ret == 0
ArcherSys/ArcherSys
refs/heads/master
Lib/test/test_spwd.py
1
<<<<<<< HEAD <<<<<<< HEAD import os import unittest from test import support spwd = support.import_module('spwd') @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0, 'root privileges required') class TestSpwdRoot(unittest.TestCase): def test_getspall(self): entries = spwd.getspall() self.assertIsInstance(entries, list) for entry in entries: self.assertIsInstance(entry, spwd.struct_spwd) def test_getspnam(self): entries = spwd.getspall() if not entries: self.skipTest('empty shadow password database') random_name = entries[0].sp_namp entry = spwd.getspnam(random_name) self.assertIsInstance(entry, spwd.struct_spwd) self.assertEqual(entry.sp_namp, random_name) self.assertEqual(entry.sp_namp, entry[0]) self.assertEqual(entry.sp_namp, entry.sp_nam) self.assertIsInstance(entry.sp_pwdp, str) self.assertEqual(entry.sp_pwdp, entry[1]) self.assertEqual(entry.sp_pwdp, entry.sp_pwd) self.assertIsInstance(entry.sp_lstchg, int) self.assertEqual(entry.sp_lstchg, entry[2]) self.assertIsInstance(entry.sp_min, int) self.assertEqual(entry.sp_min, entry[3]) self.assertIsInstance(entry.sp_max, int) self.assertEqual(entry.sp_max, entry[4]) self.assertIsInstance(entry.sp_warn, int) self.assertEqual(entry.sp_warn, entry[5]) self.assertIsInstance(entry.sp_inact, int) self.assertEqual(entry.sp_inact, entry[6]) self.assertIsInstance(entry.sp_expire, int) self.assertEqual(entry.sp_expire, entry[7]) self.assertIsInstance(entry.sp_flag, int) self.assertEqual(entry.sp_flag, entry[8]) with self.assertRaises(KeyError) as cx: spwd.getspnam('invalid user name') self.assertEqual(str(cx.exception), "'getspnam(): name not found'") self.assertRaises(TypeError, spwd.getspnam) self.assertRaises(TypeError, spwd.getspnam, 0) self.assertRaises(TypeError, spwd.getspnam, random_name, 0) try: bytes_name = os.fsencode(random_name) except UnicodeEncodeError: pass else: self.assertRaises(TypeError, spwd.getspnam, bytes_name) if __name__ == "__main__": unittest.main() ======= import os import unittest from test import support spwd = support.import_module('spwd') @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0, 'root privileges required') class TestSpwdRoot(unittest.TestCase): def test_getspall(self): entries = spwd.getspall() self.assertIsInstance(entries, list) for entry in entries: self.assertIsInstance(entry, spwd.struct_spwd) def test_getspnam(self): entries = spwd.getspall() if not entries: self.skipTest('empty shadow password database') random_name = entries[0].sp_namp entry = spwd.getspnam(random_name) self.assertIsInstance(entry, spwd.struct_spwd) self.assertEqual(entry.sp_namp, random_name) self.assertEqual(entry.sp_namp, entry[0]) self.assertEqual(entry.sp_namp, entry.sp_nam) self.assertIsInstance(entry.sp_pwdp, str) self.assertEqual(entry.sp_pwdp, entry[1]) self.assertEqual(entry.sp_pwdp, entry.sp_pwd) self.assertIsInstance(entry.sp_lstchg, int) self.assertEqual(entry.sp_lstchg, entry[2]) self.assertIsInstance(entry.sp_min, int) self.assertEqual(entry.sp_min, entry[3]) self.assertIsInstance(entry.sp_max, int) self.assertEqual(entry.sp_max, entry[4]) self.assertIsInstance(entry.sp_warn, int) self.assertEqual(entry.sp_warn, entry[5]) self.assertIsInstance(entry.sp_inact, int) self.assertEqual(entry.sp_inact, entry[6]) self.assertIsInstance(entry.sp_expire, int) self.assertEqual(entry.sp_expire, entry[7]) self.assertIsInstance(entry.sp_flag, int) self.assertEqual(entry.sp_flag, entry[8]) with self.assertRaises(KeyError) as cx: spwd.getspnam('invalid user name') self.assertEqual(str(cx.exception), "'getspnam(): name not found'") self.assertRaises(TypeError, spwd.getspnam) self.assertRaises(TypeError, spwd.getspnam, 0) self.assertRaises(TypeError, spwd.getspnam, random_name, 0) try: bytes_name = os.fsencode(random_name) except UnicodeEncodeError: pass else: self.assertRaises(TypeError, spwd.getspnam, bytes_name) if __name__ == "__main__": unittest.main() >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= import os import unittest from test import support spwd = support.import_module('spwd') @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0, 'root privileges required') class TestSpwdRoot(unittest.TestCase): def test_getspall(self): entries = spwd.getspall() self.assertIsInstance(entries, list) for entry in entries: self.assertIsInstance(entry, spwd.struct_spwd) def test_getspnam(self): entries = spwd.getspall() if not entries: self.skipTest('empty shadow password database') random_name = entries[0].sp_namp entry = spwd.getspnam(random_name) self.assertIsInstance(entry, spwd.struct_spwd) self.assertEqual(entry.sp_namp, random_name) self.assertEqual(entry.sp_namp, entry[0]) self.assertEqual(entry.sp_namp, entry.sp_nam) self.assertIsInstance(entry.sp_pwdp, str) self.assertEqual(entry.sp_pwdp, entry[1]) self.assertEqual(entry.sp_pwdp, entry.sp_pwd) self.assertIsInstance(entry.sp_lstchg, int) self.assertEqual(entry.sp_lstchg, entry[2]) self.assertIsInstance(entry.sp_min, int) self.assertEqual(entry.sp_min, entry[3]) self.assertIsInstance(entry.sp_max, int) self.assertEqual(entry.sp_max, entry[4]) self.assertIsInstance(entry.sp_warn, int) self.assertEqual(entry.sp_warn, entry[5]) self.assertIsInstance(entry.sp_inact, int) self.assertEqual(entry.sp_inact, entry[6]) self.assertIsInstance(entry.sp_expire, int) self.assertEqual(entry.sp_expire, entry[7]) self.assertIsInstance(entry.sp_flag, int) self.assertEqual(entry.sp_flag, entry[8]) with self.assertRaises(KeyError) as cx: spwd.getspnam('invalid user name') self.assertEqual(str(cx.exception), "'getspnam(): name not found'") self.assertRaises(TypeError, spwd.getspnam) self.assertRaises(TypeError, spwd.getspnam, 0) self.assertRaises(TypeError, spwd.getspnam, random_name, 0) try: bytes_name = os.fsencode(random_name) except UnicodeEncodeError: pass else: self.assertRaises(TypeError, spwd.getspnam, bytes_name) if __name__ == "__main__": unittest.main() >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
rajalokan/nova
refs/heads/master
nova/virt/xenapi/driver.py
2
# Copyright (c) 2010 Citrix Systems, Inc. # Copyright 2010 OpenStack Foundation # # 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 driver for XenServer or Xen Cloud Platform. **Variable Naming Scheme** - suffix "_ref" for opaque references - suffix "_uuid" for UUIDs - suffix "_rec" for record objects """ import math from os_xenapi.client import session from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import units from oslo_utils import versionutils import six.moves.urllib.parse as urlparse import nova.conf from nova.i18n import _, _LE, _LW from nova import exception from nova.virt import driver from nova.virt.xenapi import host from nova.virt.xenapi import pool from nova.virt.xenapi import vm_utils from nova.virt.xenapi import vmops from nova.virt.xenapi import volumeops LOG = logging.getLogger(__name__) CONF = nova.conf.CONF OVERHEAD_BASE = 3 OVERHEAD_PER_MB = 0.00781 OVERHEAD_PER_VCPU = 1.5 def invalid_option(option_name, recommended_value): LOG.exception(_LE('Current value of ' 'CONF.xenserver.%(option)s option incompatible with ' 'CONF.xenserver.independent_compute=True. ' 'Consider using "%(recommended)s"'), {'option': option_name, 'recommended': recommended_value}) raise exception.NotSupportedWithOption( operation=option_name, option='CONF.xenserver.independent_compute') class XenAPIDriver(driver.ComputeDriver): """A connection to XenServer or Xen Cloud Platform.""" capabilities = { "has_imagecache": False, "supports_recreate": False, "supports_migrate_to_same_host": False, "supports_attach_interface": True, "supports_device_tagging": False, } def __init__(self, virtapi, read_only=False): super(XenAPIDriver, self).__init__(virtapi) url = CONF.xenserver.connection_url username = CONF.xenserver.connection_username password = CONF.xenserver.connection_password if not url or password is None: raise Exception(_('Must specify connection_url, ' 'connection_username (optionally), and ' 'connection_password to use ' 'compute_driver=xenapi.XenAPIDriver')) self._session = session.XenAPISession(url, username, password, originator="nova") self._volumeops = volumeops.VolumeOps(self._session) self._host_state = None self._host = host.Host(self._session, self.virtapi) self._vmops = vmops.VMOps(self._session, self.virtapi) self._initiator = None self._hypervisor_hostname = None self._pool = pool.ResourcePool(self._session, self.virtapi) @property def host_state(self): if not self._host_state: self._host_state = host.HostState(self._session) return self._host_state def init_host(self, host): if CONF.xenserver.independent_compute: # Check various options are in the correct state: if CONF.xenserver.check_host: invalid_option('CONF.xenserver.check_host', False) if CONF.flat_injected: invalid_option('CONF.flat_injected', False) if CONF.default_ephemeral_format and \ CONF.default_ephemeral_format != 'ext3': invalid_option('CONF.default_ephemeral_format', 'ext3') if CONF.xenserver.check_host: vm_utils.ensure_correct_host(self._session) if not CONF.xenserver.independent_compute: try: vm_utils.cleanup_attached_vdis(self._session) except Exception: LOG.exception(_LE('Failure while cleaning up attached VDIs')) def instance_exists(self, instance): """Checks existence of an instance on the host. :param instance: The instance to lookup Returns True if supplied instance exists on the host, False otherwise. NOTE(belliott): This is an override of the base method for efficiency. """ return self._vmops.instance_exists(instance.name) def estimate_instance_overhead(self, instance_info): """Get virtualization overhead required to build an instance of the given flavor. :param instance_info: Instance/flavor to calculate overhead for. :returns: Overhead memory in MB. """ # XenServer memory overhead is proportional to the size of the # VM. Larger flavor VMs become more efficient with respect to # overhead. # interpolated formula to predict overhead required per vm. # based on data from: # https://wiki.openstack.org/wiki/XenServer/Overhead # Some padding is done to each value to fit all available VM data memory_mb = instance_info['memory_mb'] vcpus = instance_info.get('vcpus', 1) overhead = ((memory_mb * OVERHEAD_PER_MB) + (vcpus * OVERHEAD_PER_VCPU) + OVERHEAD_BASE) overhead = math.ceil(overhead) return {'memory_mb': overhead} def list_instances(self): """List VM instances.""" return self._vmops.list_instances() def list_instance_uuids(self): """Get the list of nova instance uuids for VMs found on the hypervisor. """ return self._vmops.list_instance_uuids() def spawn(self, context, instance, image_meta, injected_files, admin_password, network_info=None, block_device_info=None): """Create VM instance.""" self._vmops.spawn(context, instance, image_meta, injected_files, admin_password, network_info, block_device_info) def confirm_migration(self, context, migration, instance, network_info): """Confirms a resize, destroying the source VM.""" self._vmops.confirm_migration(migration, instance, network_info) def finish_revert_migration(self, context, instance, network_info, block_device_info=None, power_on=True): """Finish reverting a resize.""" # NOTE(vish): Xen currently does not use network info. self._vmops.finish_revert_migration(context, instance, block_device_info, power_on) def finish_migration(self, context, migration, instance, disk_info, network_info, image_meta, resize_instance, block_device_info=None, power_on=True): """Completes a resize, turning on the migrated instance.""" self._vmops.finish_migration(context, migration, instance, disk_info, network_info, image_meta, resize_instance, block_device_info, power_on) def snapshot(self, context, instance, image_id, update_task_state): """Create snapshot from a running VM instance.""" self._vmops.snapshot(context, instance, image_id, update_task_state) def post_interrupted_snapshot_cleanup(self, context, instance): """Cleans up any resources left after a failed snapshot.""" self._vmops.post_interrupted_snapshot_cleanup(context, instance) def reboot(self, context, instance, network_info, reboot_type, block_device_info=None, bad_volumes_callback=None): """Reboot VM instance.""" self._vmops.reboot(instance, reboot_type, bad_volumes_callback=bad_volumes_callback) def set_admin_password(self, instance, new_pass): """Set the root/admin password on the VM instance.""" self._vmops.set_admin_password(instance, new_pass) def inject_file(self, instance, b64_path, b64_contents): """Create a file on the VM instance. The file path and contents should be base64-encoded. """ self._vmops.inject_file(instance, b64_path, b64_contents) def change_instance_metadata(self, context, instance, diff): """Apply a diff to the instance metadata.""" self._vmops.change_instance_metadata(instance, diff) def destroy(self, context, instance, network_info, block_device_info=None, destroy_disks=True, migrate_data=None): """Destroy VM instance.""" self._vmops.destroy(instance, network_info, block_device_info, destroy_disks) def cleanup(self, context, instance, network_info, block_device_info=None, destroy_disks=True, migrate_data=None, destroy_vifs=True): """Cleanup after instance being destroyed by Hypervisor.""" pass def pause(self, instance): """Pause VM instance.""" self._vmops.pause(instance) def unpause(self, instance): """Unpause paused VM instance.""" self._vmops.unpause(instance) def migrate_disk_and_power_off(self, context, instance, dest, flavor, network_info, block_device_info=None, timeout=0, retry_interval=0): """Transfers the VHD of a running instance to another host, then shuts off the instance copies over the COW disk """ # NOTE(vish): Xen currently does not use network info. # TODO(PhilDay): Add support for timeout (clean shutdown) return self._vmops.migrate_disk_and_power_off(context, instance, dest, flavor, block_device_info) def suspend(self, context, instance): """suspend the specified instance.""" self._vmops.suspend(instance) def resume(self, context, instance, network_info, block_device_info=None): """resume the specified instance.""" self._vmops.resume(instance) def rescue(self, context, instance, network_info, image_meta, rescue_password): """Rescue the specified instance.""" self._vmops.rescue(context, instance, network_info, image_meta, rescue_password) def set_bootable(self, instance, is_bootable): """Set the ability to power on/off an instance.""" self._vmops.set_bootable(instance, is_bootable) def unrescue(self, instance, network_info): """Unrescue the specified instance.""" self._vmops.unrescue(instance) def power_off(self, instance, timeout=0, retry_interval=0): """Power off the specified instance.""" # TODO(PhilDay): Add support for timeout (clean shutdown) self._vmops.power_off(instance) def power_on(self, context, instance, network_info, block_device_info=None): """Power on the specified instance.""" self._vmops.power_on(instance) def soft_delete(self, instance): """Soft delete the specified instance.""" self._vmops.soft_delete(instance) def restore(self, instance): """Restore the specified instance.""" self._vmops.restore(instance) def poll_rebooting_instances(self, timeout, instances): """Poll for rebooting instances.""" self._vmops.poll_rebooting_instances(timeout, instances) def reset_network(self, instance): """reset networking for specified instance.""" self._vmops.reset_network(instance) def inject_network_info(self, instance, nw_info): """inject network info for specified instance.""" self._vmops.inject_network_info(instance, nw_info) def plug_vifs(self, instance, network_info): """Plug VIFs into networks.""" self._vmops.plug_vifs(instance, network_info) def unplug_vifs(self, instance, network_info): """Unplug VIFs from networks.""" self._vmops.unplug_vifs(instance, network_info) def get_info(self, instance): """Return data about VM instance.""" return self._vmops.get_info(instance) def get_diagnostics(self, instance): """Return data about VM diagnostics.""" return self._vmops.get_diagnostics(instance) def get_instance_diagnostics(self, instance): """Return data about VM diagnostics.""" return self._vmops.get_instance_diagnostics(instance) def get_all_bw_counters(self, instances): """Return bandwidth usage counters for each interface on each running VM. """ # we only care about VMs that correspond to a nova-managed # instance: imap = {inst['name']: inst['uuid'] for inst in instances} bwcounters = [] # get a dictionary of instance names. values are dictionaries # of mac addresses with values that are the bw counters: # e.g. {'instance-001' : { 12:34:56:78:90:12 : {'bw_in': 0, ....}} all_counters = self._vmops.get_all_bw_counters() for instance_name, counters in all_counters.items(): if instance_name in imap: # yes these are stats for a nova-managed vm # correlate the stats with the nova instance uuid: for vif_counter in counters.values(): vif_counter['uuid'] = imap[instance_name] bwcounters.append(vif_counter) return bwcounters def get_console_output(self, context, instance): """Return snapshot of console.""" return self._vmops.get_console_output(instance) def get_vnc_console(self, context, instance): """Return link to instance's VNC console.""" return self._vmops.get_vnc_console(instance) def get_volume_connector(self, instance): """Return volume connector information.""" if not self._initiator or not self._hypervisor_hostname: stats = self.host_state.get_host_stats(refresh=True) try: self._initiator = stats['host_other-config']['iscsi_iqn'] self._hypervisor_hostname = stats['host_hostname'] except (TypeError, KeyError) as err: LOG.warning(_LW('Could not determine key: %s'), err, instance=instance) self._initiator = None return { 'ip': self._get_block_storage_ip(), 'initiator': self._initiator, 'host': self._hypervisor_hostname } def _get_block_storage_ip(self): # If CONF.my_block_storage_ip is set, use it. if CONF.my_block_storage_ip != CONF.my_ip: return CONF.my_block_storage_ip return self.get_host_ip_addr() def get_host_ip_addr(self): xs_url = urlparse.urlparse(CONF.xenserver.connection_url) return xs_url.netloc def attach_volume(self, context, connection_info, instance, mountpoint, disk_bus=None, device_type=None, encryption=None): """Attach volume storage to VM instance.""" self._volumeops.attach_volume(connection_info, instance['name'], mountpoint) def detach_volume(self, connection_info, instance, mountpoint, encryption=None): """Detach volume storage from VM instance.""" self._volumeops.detach_volume(connection_info, instance['name'], mountpoint) def get_console_pool_info(self, console_type): xs_url = urlparse.urlparse(CONF.xenserver.connection_url) return {'address': xs_url.netloc, 'username': CONF.xenserver.connection_username, 'password': CONF.xenserver.connection_password} def get_available_resource(self, nodename): """Retrieve resource information. This method is called when nova-compute launches, and as part of a periodic task that records the results in the DB. :param nodename: ignored in this driver :returns: dictionary describing resources """ host_stats = self.host_state.get_host_stats(refresh=True) # Updating host information total_ram_mb = host_stats['host_memory_total'] / units.Mi # NOTE(belliott) memory-free-computed is a value provided by XenServer # for gauging free memory more conservatively than memory-free. free_ram_mb = host_stats['host_memory_free_computed'] / units.Mi total_disk_gb = host_stats['disk_total'] / units.Gi used_disk_gb = host_stats['disk_used'] / units.Gi allocated_disk_gb = host_stats['disk_allocated'] / units.Gi hyper_ver = versionutils.convert_version_to_int( self._session.product_version) dic = {'vcpus': host_stats['host_cpu_info']['cpu_count'], 'memory_mb': total_ram_mb, 'local_gb': total_disk_gb, 'vcpus_used': host_stats['vcpus_used'], 'memory_mb_used': total_ram_mb - free_ram_mb, 'local_gb_used': used_disk_gb, 'hypervisor_type': 'XenServer', 'hypervisor_version': hyper_ver, 'hypervisor_hostname': host_stats['host_hostname'], 'cpu_info': jsonutils.dumps(host_stats['cpu_model']), 'disk_available_least': total_disk_gb - allocated_disk_gb, 'supported_instances': host_stats['supported_instances'], 'pci_passthrough_devices': jsonutils.dumps( host_stats['pci_passthrough_devices']), 'numa_topology': None} return dic def ensure_filtering_rules_for_instance(self, instance, network_info): # NOTE(salvatore-orlando): it enforces security groups on # host initialization and live migration. # In XenAPI we do not assume instances running upon host initialization return def check_can_live_migrate_destination(self, context, instance, src_compute_info, dst_compute_info, block_migration=False, disk_over_commit=False): """Check if it is possible to execute live migration. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance object :param block_migration: if true, prepare for block migration :param disk_over_commit: if true, allow disk over commit :returns: a XenapiLiveMigrateData object """ return self._vmops.check_can_live_migrate_destination(context, instance, block_migration, disk_over_commit) def cleanup_live_migration_destination_check(self, context, dest_check_data): """Do required cleanup on dest host after check_can_live_migrate calls :param context: security context :param dest_check_data: result of check_can_live_migrate_destination """ pass def check_can_live_migrate_source(self, context, instance, dest_check_data, block_device_info=None): """Check if it is possible to execute live migration. This checks if the live migration can succeed, based on the results from check_can_live_migrate_destination. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance :param dest_check_data: result of check_can_live_migrate_destination includes the block_migration flag :param block_device_info: result of _get_instance_block_device_info :returns: a XenapiLiveMigrateData object """ return self._vmops.check_can_live_migrate_source(context, instance, dest_check_data) def get_instance_disk_info(self, instance, block_device_info=None): """Used by libvirt for live migration. We rely on xenapi checks to do this for us. """ pass def live_migration(self, context, instance, dest, post_method, recover_method, block_migration=False, migrate_data=None): """Performs the live migration of the specified instance. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance object instance object that is migrated. :param dest: destination host :param post_method: post operation method. expected nova.compute.manager._post_live_migration. :param recover_method: recovery method when any exception occurs. expected nova.compute.manager._rollback_live_migration. :param block_migration: if true, migrate VM disk. :param migrate_data: a XenapiLiveMigrateData object """ self._vmops.live_migrate(context, instance, dest, post_method, recover_method, block_migration, migrate_data) def rollback_live_migration_at_destination(self, context, instance, network_info, block_device_info, destroy_disks=True, migrate_data=None): """Performs a live migration rollback. :param context: security context :param instance: instance object that was being migrated :param network_info: instance network information :param block_device_info: instance block device information :param destroy_disks: if true, destroy disks at destination during cleanup :param migrate_data: A XenapiLiveMigrateData object """ # NOTE(johngarbutt) Destroying the VM is not appropriate here # and in the cases where it might make sense, # XenServer has already done it. # NOTE(sulo): The only cleanup we do explicitly is to forget # any volume that was attached to the destination during # live migration. XAPI should take care of all other cleanup. self._vmops.rollback_live_migration_at_destination(instance, network_info, block_device_info) def pre_live_migration(self, context, instance, block_device_info, network_info, disk_info, migrate_data): """Preparation live migration. :param block_device_info: It must be the result of _get_instance_volume_bdms() at compute manager. :returns: a XenapiLiveMigrateData object """ return self._vmops.pre_live_migration(context, instance, block_device_info, network_info, disk_info, migrate_data) def post_live_migration(self, context, instance, block_device_info, migrate_data=None): """Post operation of live migration at source host. :param context: security context :instance: instance object that was migrated :block_device_info: instance block device information :param migrate_data: a XenapiLiveMigrateData object """ self._vmops.post_live_migration(context, instance, migrate_data) def post_live_migration_at_source(self, context, instance, network_info): """Unplug VIFs from networks at source. :param context: security context :param instance: instance object reference :param network_info: instance network information """ self._vmops.post_live_migration_at_source(context, instance, network_info) def post_live_migration_at_destination(self, context, instance, network_info, block_migration=False, block_device_info=None): """Post operation of live migration at destination host. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance object instance object that is migrated. :param network_info: instance network information :param block_migration: if true, post operation of block_migration. """ self._vmops.post_live_migration_at_destination(context, instance, network_info, block_device_info, block_device_info) def unfilter_instance(self, instance, network_info): """Removes security groups configured for an instance.""" return self._vmops.unfilter_instance(instance, network_info) def refresh_security_group_rules(self, security_group_id): """Updates security group rules for all instances associated with a given security group. Invoked when security group rules are updated. """ return self._vmops.refresh_security_group_rules(security_group_id) def refresh_instance_security_rules(self, instance): """Updates security group rules for specified instance. Invoked when instances are added/removed to a security group or when a rule is added/removed to a security group. """ return self._vmops.refresh_instance_security_rules(instance) def get_available_nodes(self, refresh=False): stats = self.host_state.get_host_stats(refresh=refresh) return [stats["hypervisor_hostname"]] def host_power_action(self, action): """The only valid values for 'action' on XenServer are 'reboot' or 'shutdown', even though the API also accepts 'startup'. As this is not technically possible on XenServer, since the host is the same physical machine as the hypervisor, if this is requested, we need to raise an exception. """ if action in ("reboot", "shutdown"): return self._host.host_power_action(action) else: msg = _("Host startup on XenServer is not supported.") raise NotImplementedError(msg) def set_host_enabled(self, enabled): """Sets the compute host's ability to accept new instances.""" return self._host.set_host_enabled(enabled) def get_host_uptime(self): """Returns the result of calling "uptime" on the target host.""" return self._host.get_host_uptime() def host_maintenance_mode(self, host, mode): """Start/Stop host maintenance window. On start, it triggers guest VMs evacuation. """ return self._host.host_maintenance_mode(host, mode) def add_to_aggregate(self, context, aggregate, host, **kwargs): """Add a compute host to an aggregate.""" return self._pool.add_to_aggregate(context, aggregate, host, **kwargs) def remove_from_aggregate(self, context, aggregate, host, **kwargs): """Remove a compute host from an aggregate.""" return self._pool.remove_from_aggregate(context, aggregate, host, **kwargs) def undo_aggregate_operation(self, context, op, aggregate, host, set_error=True): """Undo aggregate operation when pool error raised.""" return self._pool.undo_aggregate_operation(context, op, aggregate, host, set_error) def resume_state_on_host_boot(self, context, instance, network_info, block_device_info=None): """resume guest state when a host is booted.""" self._vmops.power_on(instance) def get_per_instance_usage(self): """Get information about instance resource usage. :returns: dict of nova uuid => dict of usage info """ return self._vmops.get_per_instance_usage() def attach_interface(self, context, instance, image_meta, vif): """Use hotplug to add a network interface to a running instance. The counter action to this is :func:`detach_interface`. :param context: The request context. :param nova.objects.instance.Instance instance: The instance which will get an additional network interface. :param nova.objects.ImageMeta image_meta: The metadata of the image of the instance. :param nova.network.model.VIF vif: The object which has the information about the interface to attach. :raise nova.exception.NovaException: If the attach fails. :return: None """ self._vmops.attach_interface(instance, vif) def detach_interface(self, context, instance, vif): """Use hotunplug to remove a network interface from a running instance. The counter action to this is :func:`attach_interface`. :param context: The request context. :param nova.objects.instance.Instance instance: The instance which gets a network interface removed. :param nova.network.model.VIF vif: The object which has the information about the interface to detach. :raise nova.exception.NovaException: If the detach fails. :return: None """ self._vmops.detach_interface(instance, vif)
spooky/lobby
refs/heads/the-purge
src/games/view_models.py
1
import asyncio import logging from PyQt5.QtCore import QVariant, QUrl, QCoreApplication, pyqtSignal, pyqtSlot import relays.game from models import Map from utils.async import asyncSlot from widgets import Application from view_models.adapters import ListModelFor, SelectionList, NotifyablePropertyObject, notifyableProperty from models import FeaturedMod from .models import Game, Preset, load_presets, save_presets class GameViewModel(NotifyablePropertyObject): ''' View model for game tile ''' id = notifyableProperty(int) mapPreviewSmall = notifyableProperty(QUrl) mapPreviewBig = notifyableProperty(QUrl) mapName = notifyableProperty(str) title = notifyableProperty(str) host = notifyableProperty(str) featuredModName = notifyableProperty(str) mods = notifyableProperty(QVariant) slots = notifyableProperty(int) players = notifyableProperty(int) teams = notifyableProperty(QVariant) balance = notifyableProperty(int) def __init__(self, source=None, mapLookup=None, modLookup=None, parent=None): super().__init__(parent) self._mapLookup = mapLookup or {} self._modLookup = modLookup or {} if not source: return # TODO: fix this .... seems that I need a dict or a named tuple, not a class... for attr in ['id', 'title', 'host', 'players', 'teams', 'balance', 'private']: setattr(self, attr, getattr(source, attr)) gameMap = self.__getMap(source.mapCode) self.mapPreviewSmall = QUrl(gameMap.previewSmall) self.mapPreviewBig = QUrl(gameMap.previewBig) self.mapName = gameMap.name self.slots = gameMap.slots self.featuredModName = self.__getFeaturedModName(source.featuredModUid) self.mods = sorted([self.__getModName(m) for m in source.mods]) if source.mods else [] def __eq__(self, other): return isinstance(other, self.__class__) and other.id == self.id def __ne__(self, other): return not self.__eq__(other) def __getMap(self, mapCode): try: return self._mapLookup[mapCode] except KeyError: return Map() def __getFeaturedModName(self, uid): try: return FeaturedMod.ALL[uid].name except KeyError: return QCoreApplication.translate('GamesViewModel', 'unknown') def __getModName(self, uid): try: return self._modLookup[uid].name except KeyError: return QCoreApplication.translate('GamesViewModel', 'unknown') class GameListModel(ListModelFor(GameViewModel)): ''' View model for a list of games ''' def update(self, item): index = self._items.index(item) super().update(index, item) class GamesViewModel(NotifyablePropertyObject): ''' Main view model for games screen ''' games = notifyableProperty(GameListModel) presets = notifyableProperty(SelectionList) title = notifyableProperty(str) private = notifyableProperty(bool) featured = notifyableProperty(SelectionList) maps = notifyableProperty(SelectionList) mods = notifyableProperty(SelectionList) savePreset = pyqtSignal(str) hostGame = pyqtSignal() joinGame = pyqtSignal(int) def __init__(self, parent=None): super().__init__(parent) self.log = logging.getLogger(__name__) self.app = Application.instance() self.client = relays.game.GameClient() self.client.subscribeForNewGame(self.__onNewGame) self.savePreset.connect(self.onSavePreset) self.hostGame.connect(self.onHostGame) self.joinGame.connect(self.onJoinGame) self.mapLookup = self.app.mapLookup self.modLookup = self.app.modLookup self.games = GameListModel() self.presets = SelectionList() self.__restorePresets() self.title = None self.private = False self.featured = SelectionList() self.maps = SelectionList() self.mods = SelectionList(multiple=True) self.app.initComplete.connect(self.onAppInitComplete) for uid, f in FeaturedMod.ALL.items(): self.featured.append(f) # TODO self.featured[0].selected = True # TODO: async def __restorePresets(self): self.presets.append(None) for preset in load_presets(): self.presets.append(preset) def __createGameViewModel(self, game): return GameViewModel(game, self.mapLookup, self.modLookup) def __onNewGame(self, game): self.log.debug('new game: {}'.format(game)) g = self.__createGameViewModel(game) self.games.append(g) @pyqtSlot() def onAppInitComplete(self): for m in sorted(self.mapLookup.values(), key=lambda m: m.name.lower()): self.maps.append(m) self.maps.setSelected(0) for m in sorted(self.modLookup.values(), key=lambda m: m.name.lower()): if not m.uiOnly: self.mods.append(m) self.app.initComplete.disconnect(self.onAppInitComplete) @pyqtSlot(str) def onSavePreset(self, name=None): selected = self.presets.selected() if selected is None: preset = Preset(name=name) self.presets.append(preset) else: preset = self.presets.selected() preset.name = name try: preset.title = self.title preset.featuredModUid = self.featured.selected().uid preset.mapCode = self.maps.selected().code preset.mods = [m.uid for m in self.mods.selected()] preset.private = self.private save_presets(self.presets.items) except Exception as e: self.log.error(e) @asyncSlot @pyqtSlot() def onHostGame(self): featuredMod = self.featured.selected() mods = [m.uid for m in self.mods.selected()] selectedMap = self.maps.selected() newGame = Game(title=self.title, private=self.private, featuredModUid=featuredMod.uid, mods=mods, mapCode=selectedMap.code) self.log.debug('hosting game: {}'.format(newGame)) with self.app.report(QCoreApplication.translate('GamesViewModel', 'hosting game')): response = yield from self.client.host(newGame) self.log.debug('server response for host: {}'.format(response)) # TODO: add game starting logic yield from asyncio.sleep(5) @asyncSlot @pyqtSlot(int) def onJoinGame(self, id): self.log.debug('joining: {}'.format(id)) with self.app.report(QCoreApplication.translate('GamesViewModel', 'joining game')): response = yield from self.client.join(id) self.log.debug('server response for join: {}'.format(response)) # TODO: add game joining logic yield from asyncio.sleep(5)
manisandro/gtkspellmm
refs/heads/master
codegen/tools/defs_gen/definitions.py
10
# -*- Mode: Python; py-indent-offset: 4 -*- import copy import sys def get_valid_scheme_definitions(defs): return [x for x in defs if isinstance(x, tuple) and len(x) >= 2] def unescape(s): s = s.replace('\r\n', '\\r\\n').replace('\t', '\\t') return s.replace('\r', '\\r').replace('\n', '\\n') def make_docstring(lines): return "(char *) " + '\n'.join(['"%s"' % unescape(s) for s in lines]) # New Parameter class, wich emulates a tuple for compatibility reasons class Parameter(object): def __init__(self, ptype, pname, pdflt, pnull, pdir=None): self.ptype = ptype self.pname = pname self.pdflt = pdflt self.pnull = pnull self.pdir = pdir def __len__(self): return 4 def __getitem__(self, i): return (self.ptype, self.pname, self.pdflt, self.pnull)[i] def merge(self, old): if old.pdflt is not None: self.pdflt = old.pdflt if old.pnull is not None: self.pnull = old.pnull # We currently subclass 'str' to make impact on the rest of codegen as # little as possible. Later we can subclass 'object' instead, but # then we must find and adapt all places which expect return types to # be strings. class ReturnType(str): def __new__(cls, *args, **kwds): return str.__new__(cls, *args[:1]) def __init__(self, type_name, optional=False): str.__init__(self) self.optional = optional # Parameter for property based constructors class Property(object): def __init__(self, pname, optional, argname): self.pname = pname self.optional = optional self.argname = argname def __len__(self): return 4 def __getitem__(self, i): return ('', self.pname, self.optional, self.argname)[i] def merge(self, old): if old.optional is not None: self.optional = old.optional if old.argname is not None: self.argname = old.argname class Definition(object): docstring = "NULL" def py_name(self): return '%s.%s' % (self.module, self.name) py_name = property(py_name) def __init__(self, *args): """Create a new defs object of this type. The arguments are the components of the definition""" raise RuntimeError("this is an abstract class") def merge(self, old): """Merge in customisations from older version of definition""" raise RuntimeError("this is an abstract class") def write_defs(self, fp=sys.stdout): """write out this definition in defs file format""" raise RuntimeError("this is an abstract class") def guess_return_value_ownership(self): "return 1 if caller owns return value" if getattr(self, 'is_constructor_of', False): self.caller_owns_return = True elif self.ret in ('char*', 'gchar*', 'string'): self.caller_owns_return = True else: self.caller_owns_return = False class ObjectDef(Definition): def __init__(self, name, *args): self.name = name self.module = None self.parent = None self.c_name = None self.typecode = None self.fields = [] self.implements = [] self.class_init_func = None self.has_new_constructor_api = False for arg in get_valid_scheme_definitions(args): if arg[0] == 'in-module': self.module = arg[1] elif arg[0] == 'docstring': self.docstring = make_docstring(arg[1:]) elif arg[0] == 'parent': self.parent = arg[1] elif arg[0] == 'c-name': self.c_name = arg[1] elif arg[0] == 'gtype-id': self.typecode = arg[1] elif arg[0] == 'fields': for parg in arg[1:]: self.fields.append((parg[0], parg[1])) elif arg[0] == 'implements': self.implements.append(arg[1]) def merge(self, old): # currently the .h parser doesn't try to work out what fields of # an object structure should be public, so we just copy the list # from the old version ... self.fields = old.fields self.implements = old.implements def write_defs(self, fp=sys.stdout): fp.write('(define-object ' + self.name + '\n') if self.module: fp.write(' (in-module "' + self.module + '")\n') if self.parent != (None, None): fp.write(' (parent "' + self.parent + '")\n') for interface in self.implements: fp.write(' (implements "' + interface + '")\n') if self.c_name: fp.write(' (c-name "' + self.c_name + '")\n') if self.typecode: fp.write(' (gtype-id "' + self.typecode + '")\n') if self.fields: fp.write(' (fields\n') for (ftype, fname) in self.fields: fp.write(' \'("' + ftype + '" "' + fname + '")\n') fp.write(' )\n') fp.write(')\n\n') class InterfaceDef(Definition): def __init__(self, name, *args): self.name = name self.module = None self.c_name = None self.typecode = None self.vtable = None self.fields = [] self.interface_info = None for arg in get_valid_scheme_definitions(args): if arg[0] == 'in-module': self.module = arg[1] elif arg[0] == 'docstring': self.docstring = make_docstring(arg[1:]) elif arg[0] == 'c-name': self.c_name = arg[1] elif arg[0] == 'gtype-id': self.typecode = arg[1] elif arg[0] == 'vtable': self.vtable = arg[1] if self.vtable is None: self.vtable = self.c_name + "Iface" def write_defs(self, fp=sys.stdout): fp.write('(define-interface ' + self.name + '\n') if self.module: fp.write(' (in-module "' + self.module + '")\n') if self.c_name: fp.write(' (c-name "' + self.c_name + '")\n') if self.typecode: fp.write(' (gtype-id "' + self.typecode + '")\n') fp.write(')\n\n') class EnumDef(Definition): def __init__(self, name, *args): self.deftype = 'enum' self.name = name self.in_module = None self.c_name = None self.typecode = None self.values = [] for arg in get_valid_scheme_definitions(args): if arg[0] == 'in-module': self.in_module = arg[1] elif arg[0] == 'c-name': self.c_name = arg[1] elif arg[0] == 'gtype-id': self.typecode = arg[1] elif arg[0] == 'values': for varg in arg[1:]: self.values.append((varg[0], varg[1])) def merge(self, old): pass def write_defs(self, fp=sys.stdout): fp.write('(define-' + self.deftype + ' ' + self.name + '\n') if self.in_module: fp.write(' (in-module "' + self.in_module + '")\n') fp.write(' (c-name "' + self.c_name + '")\n') fp.write(' (gtype-id "' + self.typecode + '")\n') if self.values: fp.write(' (values\n') for name, val in self.values: fp.write(' \'("' + name + '" "' + val + '")\n') fp.write(' )\n') fp.write(')\n\n') class FlagsDef(EnumDef): def __init__(self, *args): apply(EnumDef.__init__, (self,) + args) self.deftype = 'flags' class BoxedDef(Definition): def __init__(self, name, *args): self.name = name self.module = None self.c_name = None self.typecode = None self.copy = None self.release = None self.fields = [] for arg in get_valid_scheme_definitions(args): if arg[0] == 'in-module': self.module = arg[1] elif arg[0] == 'c-name': self.c_name = arg[1] elif arg[0] == 'gtype-id': self.typecode = arg[1] elif arg[0] == 'copy-func': self.copy = arg[1] elif arg[0] == 'release-func': self.release = arg[1] elif arg[0] == 'fields': for parg in arg[1:]: self.fields.append((parg[0], parg[1])) def merge(self, old): # currently the .h parser doesn't try to work out what fields of # an object structure should be public, so we just copy the list # from the old version ... self.fields = old.fields def write_defs(self, fp=sys.stdout): fp.write('(define-boxed ' + self.name + '\n') if self.module: fp.write(' (in-module "' + self.module + '")\n') if self.c_name: fp.write(' (c-name "' + self.c_name + '")\n') if self.typecode: fp.write(' (gtype-id "' + self.typecode + '")\n') if self.copy: fp.write(' (copy-func "' + self.copy + '")\n') if self.release: fp.write(' (release-func "' + self.release + '")\n') if self.fields: fp.write(' (fields\n') for (ftype, fname) in self.fields: fp.write(' \'("' + ftype + '" "' + fname + '")\n') fp.write(' )\n') fp.write(')\n\n') class PointerDef(Definition): def __init__(self, name, *args): self.name = name self.module = None self.c_name = None self.typecode = None self.fields = [] for arg in get_valid_scheme_definitions(args): if arg[0] == 'in-module': self.module = arg[1] elif arg[0] == 'c-name': self.c_name = arg[1] elif arg[0] == 'gtype-id': self.typecode = arg[1] elif arg[0] == 'fields': for parg in arg[1:]: self.fields.append((parg[0], parg[1])) def merge(self, old): # currently the .h parser doesn't try to work out what fields of # an object structure should be public, so we just copy the list # from the old version ... self.fields = old.fields def write_defs(self, fp=sys.stdout): fp.write('(define-pointer ' + self.name + '\n') if self.module: fp.write(' (in-module "' + self.module + '")\n') if self.c_name: fp.write(' (c-name "' + self.c_name + '")\n') if self.typecode: fp.write(' (gtype-id "' + self.typecode + '")\n') if self.fields: fp.write(' (fields\n') for (ftype, fname) in self.fields: fp.write(' \'("' + ftype + '" "' + fname + '")\n') fp.write(' )\n') fp.write(')\n\n') class MethodDefBase(Definition): def __init__(self, name, *args): dump = 0 self.name = name self.ret = None self.caller_owns_return = None self.unblock_threads = None self.c_name = None self.typecode = None self.of_object = None self.params = [] # of form (type, name, default, nullok) self.varargs = 0 self.deprecated = None for arg in get_valid_scheme_definitions(args): if arg[0] == 'of-object': self.of_object = arg[1] elif arg[0] == 'docstring': self.docstring = make_docstring(arg[1:]) elif arg[0] == 'c-name': self.c_name = arg[1] elif arg[0] == 'gtype-id': self.typecode = arg[1] elif arg[0] == 'return-type': type_name = arg[1] optional = False for prop in arg[2:]: if prop[0] == 'optional': optional = True self.ret = ReturnType(type_name, optional) elif arg[0] == 'caller-owns-return': self.caller_owns_return = arg[1] in ('t', '#t') elif arg[0] == 'unblock-threads': self.unblock_threads = arg[1] in ('t', '#t') elif arg[0] == 'parameters': for parg in arg[1:]: ptype = parg[0] pname = parg[1] pdflt = None pnull = 0 pdir = None for farg in parg[2:]: assert isinstance(farg, tuple) if farg[0] == 'default': pdflt = farg[1] elif farg[0] == 'null-ok': pnull = 1 elif farg[0] == 'direction': pdir = farg[1] self.params.append(Parameter(ptype, pname, pdflt, pnull, pdir)) elif arg[0] == 'varargs': self.varargs = arg[1] in ('t', '#t') elif arg[0] == 'deprecated': self.deprecated = arg[1] else: sys.stderr.write("Warning: %s argument unsupported.\n" % (arg[0])) dump = 1 if dump: self.write_defs(sys.stderr) if self.caller_owns_return is None and self.ret is not None: self.guess_return_value_ownership() def merge(self, old, parmerge): self.caller_owns_return = old.caller_owns_return self.varargs = old.varargs # here we merge extra parameter flags accross to the new object. if not parmerge: self.params = copy.deepcopy(old.params) return for i in range(len(self.params)): ptype, pname, pdflt, pnull = self.params[i] for p2 in old.params: if p2[1] == pname: self.params[i] = (ptype, pname, p2[2], p2[3]) break def _write_defs(self, fp=sys.stdout): if self.of_object != (None, None): fp.write(' (of-object "' + self.of_object + '")\n') if self.c_name: fp.write(' (c-name "' + self.c_name + '")\n') if self.typecode: fp.write(' (gtype-id "' + self.typecode + '")\n') if self.caller_owns_return: fp.write(' (caller-owns-return #t)\n') if self.unblock_threads: fp.write(' (unblock_threads #t)\n') if self.ret: fp.write(' (return-type "' + self.ret + '")\n') if self.deprecated: fp.write(' (deprecated "' + self.deprecated + '")\n') if self.params: fp.write(' (parameters\n') for ptype, pname, pdflt, pnull in self.params: fp.write(' \'("' + ptype + '" "' + pname +'"') if pdflt: fp.write(' (default "' + pdflt + '")') if pnull: fp.write(' (null-ok)') fp.write(')\n') fp.write(' )\n') if self.varargs: fp.write(' (varargs #t)\n') fp.write(')\n\n') class MethodDef(MethodDefBase): def __init__(self, name, *args): MethodDefBase.__init__(self, name, *args) for item in ('c_name', 'of_object'): if self.__dict__[item] == None: self.write_defs(sys.stderr) raise RuntimeError("definition missing required %s" % (item,)) def write_defs(self, fp=sys.stdout): fp.write('(define-method ' + self.name + '\n') self._write_defs(fp) class VirtualDef(MethodDefBase): def write_defs(self, fp=sys.stdout): fp.write('(define-virtual ' + self.name + '\n') self._write_defs(fp) class FunctionDef(Definition): def __init__(self, name, *args): dump = 0 self.name = name self.in_module = None self.is_constructor_of = None self.ret = None self.caller_owns_return = None self.unblock_threads = None self.c_name = None self.typecode = None self.params = [] # of form (type, name, default, nullok) self.varargs = 0 self.deprecated = None for arg in get_valid_scheme_definitions(args): if arg[0] == 'in-module': self.in_module = arg[1] elif arg[0] == 'docstring': self.docstring = make_docstring(arg[1:]) elif arg[0] == 'is-constructor-of': self.is_constructor_of = arg[1] elif arg[0] == 'c-name': self.c_name = arg[1] elif arg[0] == 'gtype-id': self.typecode = arg[1] elif arg[0] == 'return-type': self.ret = arg[1] elif arg[0] == 'caller-owns-return': self.caller_owns_return = arg[1] in ('t', '#t') elif arg[0] == 'unblock-threads': self.unblock_threads = arg[1] in ('t', '#t') elif arg[0] == 'parameters': for parg in arg[1:]: ptype = parg[0] pname = parg[1] pdflt = None pnull = 0 for farg in parg[2:]: if farg[0] == 'default': pdflt = farg[1] elif farg[0] == 'null-ok': pnull = 1 self.params.append(Parameter(ptype, pname, pdflt, pnull)) elif arg[0] == 'properties': if self.is_constructor_of is None: print >> sys.stderr, "Warning: (properties ...) "\ "is only valid for constructors" for prop in arg[1:]: pname = prop[0] optional = False argname = pname for farg in prop[1:]: if farg[0] == 'optional': optional = True elif farg[0] == 'argname': argname = farg[1] self.params.append(Property(pname, optional, argname)) elif arg[0] == 'varargs': self.varargs = arg[1] in ('t', '#t') elif arg[0] == 'deprecated': self.deprecated = arg[1] else: sys.stderr.write("Warning: %s argument unsupported\n" % (arg[0],)) dump = 1 if dump: self.write_defs(sys.stderr) if self.caller_owns_return is None and self.ret is not None: self.guess_return_value_ownership() for item in ('c_name',): if self.__dict__[item] == None: self.write_defs(sys.stderr) raise RuntimeError("definition missing required %s" % (item,)) _method_write_defs = MethodDef.__dict__['write_defs'] def merge(self, old, parmerge): self.caller_owns_return = old.caller_owns_return self.varargs = old.varargs if not parmerge: self.params = copy.deepcopy(old.params) return # here we merge extra parameter flags accross to the new object. def merge_param(param): for old_param in old.params: if old_param.pname == param.pname: if isinstance(old_param, Property): # h2def never scans Property's, therefore if # we have one it was manually written, so we # keep it. return copy.deepcopy(old_param) else: param.merge(old_param) return param raise RuntimeError("could not find %s in old_parameters %r" % ( param.pname, [p.pname for p in old.params])) try: self.params = map(merge_param, self.params) except RuntimeError: # parameter names changed and we can't find a match; it's # safer to keep the old parameter list untouched. self.params = copy.deepcopy(old.params) if not self.is_constructor_of: try: self.is_constructor_of = old.is_constructor_of except AttributeError: pass if isinstance(old, MethodDef): self.name = old.name # transmogrify from function into method ... self.write_defs = self._method_write_defs self.of_object = old.of_object del self.params[0] def write_defs(self, fp=sys.stdout): fp.write('(define-function ' + self.name + '\n') if self.in_module: fp.write(' (in-module "' + self.in_module + '")\n') if self.is_constructor_of: fp.write(' (is-constructor-of "' + self.is_constructor_of +'")\n') if self.c_name: fp.write(' (c-name "' + self.c_name + '")\n') if self.typecode: fp.write(' (gtype-id "' + self.typecode + '")\n') if self.caller_owns_return: fp.write(' (caller-owns-return #t)\n') if self.unblock_threads: fp.write(' (unblock-threads #t)\n') if self.ret: fp.write(' (return-type "' + self.ret + '")\n') if self.deprecated: fp.write(' (deprecated "' + self.deprecated + '")\n') if self.params: if isinstance(self.params[0], Parameter): fp.write(' (parameters\n') for ptype, pname, pdflt, pnull in self.params: fp.write(' \'("' + ptype + '" "' + pname +'"') if pdflt: fp.write(' (default "' + pdflt + '")') if pnull: fp.write(' (null-ok)') fp.write(')\n') fp.write(' )\n') elif isinstance(self.params[0], Property): fp.write(' (properties\n') for prop in self.params: fp.write(' \'("' + prop.pname +'"') if prop.optional: fp.write(' (optional)') fp.write(')\n') fp.write(' )\n') else: assert False, "strange parameter list %r" % self.params[0] if self.varargs: fp.write(' (varargs #t)\n') fp.write(')\n\n')
tboyce021/home-assistant
refs/heads/dev
tests/components/zwave/test_climate.py
16
"""Test Z-Wave climate devices.""" import pytest from homeassistant.components.climate.const import ( ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, CURRENT_HVAC_COOL, CURRENT_HVAC_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, HVAC_MODES, PRESET_AWAY, PRESET_BOOST, PRESET_ECO, PRESET_NONE, SUPPORT_AUX_HEAT, SUPPORT_FAN_MODE, SUPPORT_PRESET_MODE, SUPPORT_SWING_MODE, SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_RANGE, ) from homeassistant.components.zwave import climate, const from homeassistant.components.zwave.climate import ( AUX_HEAT_ZWAVE_MODE, DEFAULT_HVAC_MODES, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from tests.mock.zwave import MockEntityValues, MockNode, MockValue, value_changed @pytest.fixture def device(hass, mock_openzwave): """Fixture to provide a precreated climate device.""" node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data=HVAC_MODE_HEAT, data_items=[ HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, ], node=node, ), setpoint_heating=MockValue(data=1, node=node), setpoint_cooling=MockValue(data=10, node=node), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data=CURRENT_HVAC_HEAT, node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_zxt_120(hass, mock_openzwave): """Fixture to provide a precreated climate device.""" node = MockNode(manufacturer_id="5254", product_id="8377") values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data=HVAC_MODE_HEAT, data_items=[ HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, ], node=node, ), setpoint_heating=MockValue(data=1, node=node), setpoint_cooling=MockValue(data=10, node=node), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data=CURRENT_HVAC_HEAT, node=node), fan_action=MockValue(data=7, node=node), zxt_120_swing_mode=MockValue(data="test3", data_items=[6, 7, 8], node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_mapping(hass, mock_openzwave): """Fixture to provide a precreated climate device. Test state mapping.""" node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data="Heat", data_items=["Off", "Cool", "Heat", "Full Power", "Auto"], node=node, ), setpoint_heating=MockValue(data=1, node=node), setpoint_cooling=MockValue(data=10, node=node), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data="heating", node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_unknown(hass, mock_openzwave): """Fixture to provide a precreated climate device. Test state unknown.""" node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data="Heat", data_items=["Off", "Cool", "Heat", "heat_cool", "Abcdefg"], node=node, ), setpoint_heating=MockValue(data=1, node=node), setpoint_cooling=MockValue(data=10, node=node), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data="test4", node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_heat_cool(hass, mock_openzwave): """Fixture to provide a precreated climate device. Test state heat only.""" node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data=HVAC_MODE_HEAT, data_items=[ HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_COOL, "Heat Eco", "Cool Eco", ], node=node, ), setpoint_heating=MockValue(data=1, node=node), setpoint_cooling=MockValue(data=10, node=node), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data="test4", node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_heat_cool_range(hass, mock_openzwave): """Fixture to provide a precreated climate device. Target range mode.""" node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data=HVAC_MODE_HEAT_COOL, data_items=[ HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, ], node=node, ), setpoint_heating=MockValue(data=1, node=node), setpoint_cooling=MockValue(data=10, node=node), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data="test4", node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_heat_cool_away(hass, mock_openzwave): """Fixture to provide a precreated climate device. Target range mode.""" node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data=HVAC_MODE_HEAT_COOL, data_items=[ HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, PRESET_AWAY, ], node=node, ), setpoint_heating=MockValue(data=2, node=node), setpoint_cooling=MockValue(data=9, node=node), setpoint_away_heating=MockValue(data=1, node=node), setpoint_away_cooling=MockValue(data=10, node=node), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data="test4", node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_heat_eco(hass, mock_openzwave): """Fixture to provide a precreated climate device. heat/heat eco.""" node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data=HVAC_MODE_HEAT, data_items=[HVAC_MODE_OFF, HVAC_MODE_HEAT, "heat econ"], node=node, ), setpoint_heating=MockValue(data=2, node=node), setpoint_eco_heating=MockValue(data=1, node=node), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data="test4", node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_aux_heat(hass, mock_openzwave): """Fixture to provide a precreated climate device. aux heat.""" node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data=HVAC_MODE_HEAT, data_items=[HVAC_MODE_OFF, HVAC_MODE_HEAT, "Aux Heat"], node=node, ), setpoint_heating=MockValue(data=2, node=node), setpoint_eco_heating=MockValue(data=1, node=node), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data="test4", node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_single_setpoint(hass, mock_openzwave): """Fixture to provide a precreated climate device. SETPOINT_THERMOSTAT device class. """ node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, data=1, node=node ), mode=None, temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data=CURRENT_HVAC_HEAT, node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device @pytest.fixture def device_single_setpoint_with_mode(hass, mock_openzwave): """Fixture to provide a precreated climate device. SETPOINT_THERMOSTAT device class with COMMAND_CLASS_THERMOSTAT_MODE command class """ node = MockNode() values = MockEntityValues( primary=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, data=1, node=node ), mode=MockValue( command_class=const.COMMAND_CLASS_THERMOSTAT_MODE, data=HVAC_MODE_HEAT, data_items=[HVAC_MODE_OFF, HVAC_MODE_HEAT], node=node, ), temperature=MockValue(data=5, node=node, units=None), fan_mode=MockValue(data="test2", data_items=[3, 4, 5], node=node), operating_state=MockValue(data=CURRENT_HVAC_HEAT, node=node), fan_action=MockValue(data=7, node=node), ) device = climate.get_device(hass, node=node, values=values, node_config={}) yield device def test_get_device_detects_none(hass, mock_openzwave): """Test get_device returns None.""" node = MockNode() value = MockValue(data=0, node=node) values = MockEntityValues(primary=value) device = climate.get_device(hass, node=node, values=values, node_config={}) assert device is None def test_get_device_detects_multiple_setpoint_device(device): """Test get_device returns a Z-Wave multiple setpoint device.""" assert isinstance(device, climate.ZWaveClimateMultipleSetpoint) def test_get_device_detects_single_setpoint_device(device_single_setpoint): """Test get_device returns a Z-Wave single setpoint device.""" assert isinstance(device_single_setpoint, climate.ZWaveClimateSingleSetpoint) def test_default_hvac_modes(): """Test whether all hvac modes are included in default_hvac_modes.""" for hvac_mode in HVAC_MODES: assert hvac_mode in DEFAULT_HVAC_MODES def test_supported_features(device): """Test supported features flags.""" assert ( device.supported_features == SUPPORT_FAN_MODE + SUPPORT_TARGET_TEMPERATURE + SUPPORT_TARGET_TEMPERATURE_RANGE ) def test_supported_features_temp_range(device_heat_cool_range): """Test supported features flags with target temp range.""" device = device_heat_cool_range assert ( device.supported_features == SUPPORT_FAN_MODE + SUPPORT_TARGET_TEMPERATURE + SUPPORT_TARGET_TEMPERATURE_RANGE ) def test_supported_features_preset_mode(device_mapping): """Test supported features flags with swing mode.""" device = device_mapping assert ( device.supported_features == SUPPORT_FAN_MODE + SUPPORT_TARGET_TEMPERATURE + SUPPORT_TARGET_TEMPERATURE_RANGE + SUPPORT_PRESET_MODE ) def test_supported_features_preset_mode_away(device_heat_cool_away): """Test supported features flags with swing mode.""" device = device_heat_cool_away assert ( device.supported_features == SUPPORT_FAN_MODE + SUPPORT_TARGET_TEMPERATURE + SUPPORT_TARGET_TEMPERATURE_RANGE + SUPPORT_PRESET_MODE ) def test_supported_features_swing_mode(device_zxt_120): """Test supported features flags with swing mode.""" device = device_zxt_120 assert ( device.supported_features == SUPPORT_FAN_MODE + SUPPORT_TARGET_TEMPERATURE + SUPPORT_TARGET_TEMPERATURE_RANGE + SUPPORT_SWING_MODE ) def test_supported_features_aux_heat(device_aux_heat): """Test supported features flags with aux heat.""" device = device_aux_heat assert ( device.supported_features == SUPPORT_FAN_MODE + SUPPORT_TARGET_TEMPERATURE + SUPPORT_AUX_HEAT ) def test_supported_features_single_setpoint(device_single_setpoint): """Test supported features flags for SETPOINT_THERMOSTAT.""" device = device_single_setpoint assert device.supported_features == SUPPORT_FAN_MODE + SUPPORT_TARGET_TEMPERATURE def test_supported_features_single_setpoint_with_mode(device_single_setpoint_with_mode): """Test supported features flags for SETPOINT_THERMOSTAT.""" device = device_single_setpoint_with_mode assert device.supported_features == SUPPORT_FAN_MODE + SUPPORT_TARGET_TEMPERATURE def test_zxt_120_swing_mode(device_zxt_120): """Test operation of the zxt 120 swing mode.""" device = device_zxt_120 assert device.swing_modes == [6, 7, 8] assert device._zxt_120 == 1 # Test set mode assert device.values.zxt_120_swing_mode.data == "test3" device.set_swing_mode("test_swing_set") assert device.values.zxt_120_swing_mode.data == "test_swing_set" # Test mode changed value_changed(device.values.zxt_120_swing_mode) assert device.swing_mode == "test_swing_set" device.values.zxt_120_swing_mode.data = "test_swing_updated" value_changed(device.values.zxt_120_swing_mode) assert device.swing_mode == "test_swing_updated" def test_temperature_unit(device): """Test temperature unit.""" assert device.temperature_unit == TEMP_CELSIUS device.values.temperature.units = "F" value_changed(device.values.temperature) assert device.temperature_unit == TEMP_FAHRENHEIT device.values.temperature.units = "C" value_changed(device.values.temperature) assert device.temperature_unit == TEMP_CELSIUS def test_data_lists(device): """Test data lists from zwave value items.""" assert device.fan_modes == [3, 4, 5] assert device.hvac_modes == [ HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, ] assert device.preset_modes == [] device.values.primary = None assert device.preset_modes == [] def test_data_lists_single_setpoint(device_single_setpoint): """Test data lists from zwave value items.""" device = device_single_setpoint assert device.fan_modes == [3, 4, 5] assert device.hvac_modes == [] assert device.preset_modes == [] def test_data_lists_single_setpoint_with_mode(device_single_setpoint_with_mode): """Test data lists from zwave value items.""" device = device_single_setpoint_with_mode assert device.fan_modes == [3, 4, 5] assert device.hvac_modes == [HVAC_MODE_OFF, HVAC_MODE_HEAT] assert device.preset_modes == [] def test_data_lists_mapping(device_mapping): """Test data lists from zwave value items.""" device = device_mapping assert device.hvac_modes == ["off", "cool", "heat", "heat_cool"] assert device.preset_modes == ["boost", "none"] device.values.primary = None assert device.preset_modes == [] def test_target_value_set(device): """Test values changed for climate device.""" assert device.values.setpoint_heating.data == 1 assert device.values.setpoint_cooling.data == 10 device.set_temperature() assert device.values.setpoint_heating.data == 1 assert device.values.setpoint_cooling.data == 10 device.set_temperature(**{ATTR_TEMPERATURE: 2}) assert device.values.setpoint_heating.data == 2 assert device.values.setpoint_cooling.data == 10 device.set_hvac_mode(HVAC_MODE_COOL) value_changed(device.values.primary) assert device.values.setpoint_heating.data == 2 assert device.values.setpoint_cooling.data == 10 device.set_temperature(**{ATTR_TEMPERATURE: 9}) assert device.values.setpoint_heating.data == 2 assert device.values.setpoint_cooling.data == 9 def test_target_value_set_range(device_heat_cool_range): """Test values changed for climate device.""" device = device_heat_cool_range assert device.values.setpoint_heating.data == 1 assert device.values.setpoint_cooling.data == 10 device.set_temperature() assert device.values.setpoint_heating.data == 1 assert device.values.setpoint_cooling.data == 10 device.set_temperature(**{ATTR_TARGET_TEMP_LOW: 2}) assert device.values.setpoint_heating.data == 2 assert device.values.setpoint_cooling.data == 10 device.set_temperature(**{ATTR_TARGET_TEMP_HIGH: 9}) assert device.values.setpoint_heating.data == 2 assert device.values.setpoint_cooling.data == 9 device.set_temperature(**{ATTR_TARGET_TEMP_LOW: 3, ATTR_TARGET_TEMP_HIGH: 8}) assert device.values.setpoint_heating.data == 3 assert device.values.setpoint_cooling.data == 8 def test_target_value_set_range_away(device_heat_cool_away): """Test values changed for climate device.""" device = device_heat_cool_away assert device.values.setpoint_heating.data == 2 assert device.values.setpoint_cooling.data == 9 assert device.values.setpoint_away_heating.data == 1 assert device.values.setpoint_away_cooling.data == 10 device.set_preset_mode(PRESET_AWAY) device.set_temperature(**{ATTR_TARGET_TEMP_LOW: 0, ATTR_TARGET_TEMP_HIGH: 11}) assert device.values.setpoint_heating.data == 2 assert device.values.setpoint_cooling.data == 9 assert device.values.setpoint_away_heating.data == 0 assert device.values.setpoint_away_cooling.data == 11 def test_target_value_set_eco(device_heat_eco): """Test values changed for climate device.""" device = device_heat_eco assert device.values.setpoint_heating.data == 2 assert device.values.setpoint_eco_heating.data == 1 device.set_preset_mode("heat econ") device.set_temperature(**{ATTR_TEMPERATURE: 0}) assert device.values.setpoint_heating.data == 2 assert device.values.setpoint_eco_heating.data == 0 def test_target_value_set_single_setpoint(device_single_setpoint): """Test values changed for climate device.""" device = device_single_setpoint assert device.values.primary.data == 1 device.set_temperature(**{ATTR_TEMPERATURE: 2}) assert device.values.primary.data == 2 def test_operation_value_set(device): """Test values changed for climate device.""" assert device.values.primary.data == HVAC_MODE_HEAT device.set_hvac_mode(HVAC_MODE_COOL) assert device.values.primary.data == HVAC_MODE_COOL device.set_preset_mode(PRESET_ECO) assert device.values.primary.data == PRESET_ECO device.set_preset_mode(PRESET_NONE) assert device.values.primary.data == HVAC_MODE_HEAT_COOL device.values.primary = None device.set_hvac_mode("test_set_failes") assert device.values.primary is None device.set_preset_mode("test_set_failes") assert device.values.primary is None def test_operation_value_set_mapping(device_mapping): """Test values changed for climate device. Mapping.""" device = device_mapping assert device.values.primary.data == "Heat" device.set_hvac_mode(HVAC_MODE_COOL) assert device.values.primary.data == "Cool" device.set_hvac_mode(HVAC_MODE_OFF) assert device.values.primary.data == "Off" device.set_preset_mode(PRESET_BOOST) assert device.values.primary.data == "Full Power" device.set_preset_mode(PRESET_ECO) assert device.values.primary.data == "eco" def test_operation_value_set_unknown(device_unknown): """Test values changed for climate device. Unknown.""" device = device_unknown assert device.values.primary.data == "Heat" device.set_preset_mode("Abcdefg") assert device.values.primary.data == "Abcdefg" device.set_preset_mode(PRESET_NONE) assert device.values.primary.data == HVAC_MODE_HEAT_COOL def test_operation_value_set_heat_cool(device_heat_cool): """Test values changed for climate device. Heat/Cool only.""" device = device_heat_cool assert device.values.primary.data == HVAC_MODE_HEAT device.set_preset_mode("Heat Eco") assert device.values.primary.data == "Heat Eco" device.set_preset_mode(PRESET_NONE) assert device.values.primary.data == HVAC_MODE_HEAT device.set_preset_mode("Cool Eco") assert device.values.primary.data == "Cool Eco" device.set_preset_mode(PRESET_NONE) assert device.values.primary.data == HVAC_MODE_COOL def test_fan_mode_value_set(device): """Test values changed for climate device.""" assert device.values.fan_mode.data == "test2" device.set_fan_mode("test_fan_set") assert device.values.fan_mode.data == "test_fan_set" device.values.fan_mode = None device.set_fan_mode("test_fan_set_failes") assert device.values.fan_mode is None def test_target_value_changed(device): """Test values changed for climate device.""" assert device.target_temperature == 1 device.values.setpoint_heating.data = 2 value_changed(device.values.setpoint_heating) assert device.target_temperature == 2 device.values.primary.data = HVAC_MODE_COOL value_changed(device.values.primary) assert device.target_temperature == 10 device.values.setpoint_cooling.data = 9 value_changed(device.values.setpoint_cooling) assert device.target_temperature == 9 def test_target_range_changed(device_heat_cool_range): """Test values changed for climate device.""" device = device_heat_cool_range assert device.target_temperature_low == 1 assert device.target_temperature_high == 10 device.values.setpoint_heating.data = 2 value_changed(device.values.setpoint_heating) assert device.target_temperature_low == 2 assert device.target_temperature_high == 10 device.values.setpoint_cooling.data = 9 value_changed(device.values.setpoint_cooling) assert device.target_temperature_low == 2 assert device.target_temperature_high == 9 def test_target_changed_preset_range(device_heat_cool_away): """Test values changed for climate device.""" device = device_heat_cool_away assert device.target_temperature_low == 2 assert device.target_temperature_high == 9 device.values.primary.data = PRESET_AWAY value_changed(device.values.primary) assert device.target_temperature_low == 1 assert device.target_temperature_high == 10 device.values.setpoint_away_heating.data = 0 value_changed(device.values.setpoint_away_heating) device.values.setpoint_away_cooling.data = 11 value_changed(device.values.setpoint_away_cooling) assert device.target_temperature_low == 0 assert device.target_temperature_high == 11 device.values.primary.data = HVAC_MODE_HEAT_COOL value_changed(device.values.primary) assert device.target_temperature_low == 2 assert device.target_temperature_high == 9 def test_target_changed_eco(device_heat_eco): """Test values changed for climate device.""" device = device_heat_eco assert device.target_temperature == 2 device.values.primary.data = "heat econ" value_changed(device.values.primary) assert device.target_temperature == 1 device.values.setpoint_eco_heating.data = 0 value_changed(device.values.setpoint_eco_heating) assert device.target_temperature == 0 device.values.primary.data = HVAC_MODE_HEAT value_changed(device.values.primary) assert device.target_temperature == 2 def test_target_changed_with_mode(device): """Test values changed for climate device.""" assert device.hvac_mode == HVAC_MODE_HEAT assert device.target_temperature == 1 device.values.primary.data = HVAC_MODE_COOL value_changed(device.values.primary) assert device.target_temperature == 10 device.values.primary.data = HVAC_MODE_HEAT_COOL value_changed(device.values.primary) assert device.target_temperature_low == 1 assert device.target_temperature_high == 10 def test_target_value_changed_single_setpoint(device_single_setpoint): """Test values changed for climate device.""" device = device_single_setpoint assert device.target_temperature == 1 device.values.primary.data = 2 value_changed(device.values.primary) assert device.target_temperature == 2 def test_temperature_value_changed(device): """Test values changed for climate device.""" assert device.current_temperature == 5 device.values.temperature.data = 3 value_changed(device.values.temperature) assert device.current_temperature == 3 def test_operation_value_changed(device): """Test values changed for climate device.""" assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == PRESET_NONE device.values.primary.data = HVAC_MODE_COOL value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_COOL assert device.preset_mode == PRESET_NONE device.values.primary.data = HVAC_MODE_OFF value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_OFF assert device.preset_mode == PRESET_NONE device.values.primary = None assert device.hvac_mode == HVAC_MODE_HEAT_COOL assert device.preset_mode == PRESET_NONE def test_operation_value_changed_preset(device_mapping): """Test preset changed for climate device.""" device = device_mapping assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == PRESET_NONE device.values.primary.data = PRESET_ECO value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_HEAT_COOL assert device.preset_mode == PRESET_ECO def test_operation_value_changed_mapping(device_mapping): """Test values changed for climate device. Mapping.""" device = device_mapping assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == PRESET_NONE device.values.primary.data = "Off" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_OFF assert device.preset_mode == PRESET_NONE device.values.primary.data = "Cool" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_COOL assert device.preset_mode == PRESET_NONE def test_operation_value_changed_mapping_preset(device_mapping): """Test values changed for climate device. Mapping with presets.""" device = device_mapping assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == PRESET_NONE device.values.primary.data = "Full Power" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_HEAT_COOL assert device.preset_mode == PRESET_BOOST device.values.primary = None assert device.hvac_mode == HVAC_MODE_HEAT_COOL assert device.preset_mode == PRESET_NONE def test_operation_value_changed_unknown(device_unknown): """Test preset changed for climate device. Unknown.""" device = device_unknown assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == PRESET_NONE device.values.primary.data = "Abcdefg" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_HEAT_COOL assert device.preset_mode == "Abcdefg" def test_operation_value_changed_heat_cool(device_heat_cool): """Test preset changed for climate device. Heat/Cool only.""" device = device_heat_cool assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == PRESET_NONE device.values.primary.data = "Cool Eco" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_COOL assert device.preset_mode == "Cool Eco" device.values.primary.data = "Heat Eco" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == "Heat Eco" def test_fan_mode_value_changed(device): """Test values changed for climate device.""" assert device.fan_mode == "test2" device.values.fan_mode.data = "test_updated_fan" value_changed(device.values.fan_mode) assert device.fan_mode == "test_updated_fan" def test_hvac_action_value_changed(device): """Test values changed for climate device.""" assert device.hvac_action == CURRENT_HVAC_HEAT device.values.operating_state.data = CURRENT_HVAC_COOL value_changed(device.values.operating_state) assert device.hvac_action == CURRENT_HVAC_COOL def test_hvac_action_value_changed_mapping(device_mapping): """Test values changed for climate device.""" device = device_mapping assert device.hvac_action == CURRENT_HVAC_HEAT device.values.operating_state.data = "cooling" value_changed(device.values.operating_state) assert device.hvac_action == CURRENT_HVAC_COOL def test_hvac_action_value_changed_unknown(device_unknown): """Test values changed for climate device.""" device = device_unknown assert device.hvac_action == "test4" device.values.operating_state.data = "another_hvac_action" value_changed(device.values.operating_state) assert device.hvac_action == "another_hvac_action" def test_fan_action_value_changed(device): """Test values changed for climate device.""" assert device.device_state_attributes[climate.ATTR_FAN_ACTION] == 7 device.values.fan_action.data = 9 value_changed(device.values.fan_action) assert device.device_state_attributes[climate.ATTR_FAN_ACTION] == 9 def test_aux_heat_unsupported_set(device): """Test aux heat for climate device.""" assert device.values.primary.data == HVAC_MODE_HEAT device.turn_aux_heat_on() assert device.values.primary.data == HVAC_MODE_HEAT device.turn_aux_heat_off() assert device.values.primary.data == HVAC_MODE_HEAT def test_aux_heat_unsupported_value_changed(device): """Test aux heat for climate device.""" assert device.is_aux_heat is None device.values.primary.data = HVAC_MODE_HEAT value_changed(device.values.primary) assert device.is_aux_heat is None def test_aux_heat_set(device_aux_heat): """Test aux heat for climate device.""" device = device_aux_heat assert device.values.primary.data == HVAC_MODE_HEAT device.turn_aux_heat_on() assert device.values.primary.data == AUX_HEAT_ZWAVE_MODE device.turn_aux_heat_off() assert device.values.primary.data == HVAC_MODE_HEAT def test_aux_heat_value_changed(device_aux_heat): """Test aux heat for climate device.""" device = device_aux_heat assert device.is_aux_heat is False device.values.primary.data = AUX_HEAT_ZWAVE_MODE value_changed(device.values.primary) assert device.is_aux_heat is True device.values.primary.data = HVAC_MODE_HEAT value_changed(device.values.primary) assert device.is_aux_heat is False
psav/cfme_tests
refs/heads/master
cfme/tests/cloud_infra_common/test_rest_providers.py
2
import fauxfactory import pytest from cfme import test_requirements from cfme.common.provider import CloudInfraProvider from cfme.infrastructure.provider import InfraProvider from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.utils.blockers import BZ from cfme.utils.rest import ( assert_response, delete_resources_from_collection, delete_resources_from_detail, query_resource_attributes, ) from cfme.utils.wait import wait_for pytestmark = [ test_requirements.rest, pytest.mark.tier(1), pytest.mark.provider([CloudInfraProvider]) ] def delete_provider(appliance, name): provs = appliance.rest_api.collections.providers.find_by(name=name) if not provs: return prov = provs[0] prov.action.delete() prov.wait_not_exists() @pytest.fixture(scope="function") def provider_rest(request, appliance, provider): """Creates provider using REST API.""" delete_provider(appliance, provider.name) request.addfinalizer(lambda: delete_provider(appliance, provider.name)) provider.create_rest() assert_response(appliance) provider_rest = appliance.rest_api.collections.providers.get(name=provider.name) return provider_rest @pytest.mark.rhv1 def test_query_provider_attributes(provider, provider_rest, soft_assert): """Tests access to attributes of /api/providers. Metadata: test_flag: rest """ outcome = query_resource_attributes(provider_rest) for failure in outcome.failed: if provider.one_of(InfraProvider): # once BZ1545240 is fixed other failure than internal server # error is expected if failure.name == 'cloud_tenants' and BZ( 1545240, forced_streams=['5.8', '5.9', 'upstream']).blocks: continue if failure.name == 'flavors' and BZ( 1545240, forced_streams=['5.9', 'upstream']).blocks: continue if provider.one_of(RHEVMProvider): # once BZ1546112 is fixed other failure than internal server # error is expected if failure.name in ('cloud_networks', 'cloud_subnets', 'security_groups') and BZ( 1546112, forced_streams=['5.9', 'upstream']).blocks: continue soft_assert(False, '{0} "{1}": status: {2}, error: `{3}`'.format( failure.type, failure.name, failure.response.status_code, failure.error)) @pytest.mark.rhv3 @pytest.mark.uncollectif(lambda appliance: appliance.version < '5.9') def test_provider_options(appliance): """Tests that provider settings are present in OPTIONS listing. Metadata: test_flag: rest """ options = appliance.rest_api.options(appliance.rest_api.collections.providers._href) assert 'provider_settings' in options['data'] @pytest.mark.rhv3 def test_create_provider(provider_rest): """Tests creating provider using REST API. Metadata: test_flag: rest """ assert "ManageIQ::Providers::" in provider_rest.type @pytest.mark.rhv1 def test_provider_refresh(provider_rest, appliance): """Test checking that refresh invoked from the REST API works. Metadata: test_flag: rest """ # initiate refresh def _refresh_success(): provider_rest.action.refresh() # the provider might not be ready yet, wait a bit if "failed last authentication check" in appliance.rest_api.response.json()["message"]: return False return True if not wait_for(_refresh_success, num_sec=30, delay=2, silent_failure=True): pytest.fail("Authentication failed, check credentials.") task_id = appliance.rest_api.response.json().get("task_id") assert_response(appliance, task_wait=0) # wait for an acceptable task state if task_id: task = appliance.rest_api.get_entity("tasks", task_id) wait_for( lambda: task.state.lower() in ("finished", "queued"), fail_func=task.reload, num_sec=30, ) assert task.status.lower() == "ok", "Task failed with status '{}'".format(task.status) @pytest.mark.rhv3 def test_provider_edit(request, provider_rest, appliance): """Test editing a provider using REST API. Metadata: test_flag: rest """ new_name = fauxfactory.gen_alphanumeric() old_name = provider_rest.name request.addfinalizer(lambda: provider_rest.action.edit(name=old_name)) edited = provider_rest.action.edit(name=new_name) assert_response(appliance) provider_rest.reload() assert provider_rest.name == new_name == edited.name @pytest.mark.rhv3 @pytest.mark.parametrize("method", ["post", "delete"], ids=["POST", "DELETE"]) def test_provider_delete_from_detail(provider_rest, method): """Tests deletion of the provider from detail using REST API. Testing BZs 1525498, 1501941 Metadata: test_flag: rest """ delete_resources_from_detail([provider_rest], method=method, num_sec=50) @pytest.mark.rhv3 def test_provider_delete_from_collection(provider_rest): """Tests deletion of the provider from collection using REST API. Testing BZs 1525498, 1501941 Metadata: test_flag: rest """ delete_resources_from_collection([provider_rest], num_sec=50)
jsirois/pants
refs/heads/master
tests/python/pants_test/integration/list_integration_test.py
4
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.testutil.pants_integration_test import run_pants def test_list_all() -> None: pants_run = run_pants(["--backend-packages=pants.backend.python", "list", "::"]) pants_run.assert_success() assert len(pants_run.stdout.strip().split()) > 1 def test_list_none() -> None: pants_run = run_pants(["list"]) pants_run.assert_success() assert "WARNING: No targets were matched in" in pants_run.stderr def test_list_invalid_dir() -> None: pants_run = run_pants(["list", "abcde::"]) pants_run.assert_failure() assert "ResolveError" in pants_run.stderr def test_list_testproject() -> None: pants_run = run_pants( [ "--backend-packages=pants.backend.python", "list", "testprojects/src/python/hello::", ] ) pants_run.assert_success() assert pants_run.stdout.strip() == "\n".join( [ "testprojects/src/python/hello", "testprojects/src/python/hello/greet", "testprojects/src/python/hello/main", "testprojects/src/python/hello/main:lib", ] )
urisimchoni/samba
refs/heads/master
auth/credentials/tests/bind.py
35
#!/usr/bin/env python # -*- coding: utf-8 -*- # This is unit with tests for LDAP access checks import optparse import sys import base64 import copy import time sys.path.insert(0, "bin/python") import samba from samba.tests.subunitrun import SubunitOptions, TestProgram import samba.getopt as options from ldb import SCOPE_BASE, SCOPE_SUBTREE from samba import gensec import samba.tests from samba.tests import delete_force parser = optparse.OptionParser("ldap [options] <host>") sambaopts = options.SambaOptions(parser) parser.add_option_group(sambaopts) # use command line creds if available credopts = options.CredentialsOptions(parser) parser.add_option_group(credopts) subunitopts = SubunitOptions(parser) parser.add_option_group(subunitopts) opts, args = parser.parse_args() if len(args) < 1: parser.print_usage() sys.exit(1) host = args[0] lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL) creds_machine = copy.deepcopy(creds) creds_user1 = copy.deepcopy(creds) creds_user2 = copy.deepcopy(creds) creds_user3 = copy.deepcopy(creds) class BindTests(samba.tests.TestCase): info_dc = None def setUp(self): super(BindTests, self).setUp() # fetch rootDSEs self.ldb = samba.tests.connect_samdb(host, credentials=creds, lp=lp, ldap_only=True) if self.info_dc is None: res = self.ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"]) self.assertEquals(len(res), 1) BindTests.info_dc = res[0] # cache some of RootDSE props self.schema_dn = self.info_dc["schemaNamingContext"][0] self.domain_dn = self.info_dc["defaultNamingContext"][0] self.config_dn = self.info_dc["configurationNamingContext"][0] self.computer_dn = "CN=centos53,CN=Computers,%s" % self.domain_dn self.password = "P@ssw0rd" self.username = "BindTestUser_" + time.strftime("%s", time.gmtime()) def tearDown(self): super(BindTests, self).tearDown() def test_computer_account_bind(self): # create a computer acocount for the test delete_force(self.ldb, self.computer_dn) self.ldb.add_ldif(""" dn: """ + self.computer_dn + """ cn: CENTOS53 displayName: CENTOS53$ name: CENTOS53 sAMAccountName: CENTOS53$ countryCode: 0 objectClass: computer objectClass: organizationalPerson objectClass: person objectClass: top objectClass: user codePage: 0 userAccountControl: 4096 dNSHostName: centos53.alabala.test operatingSystemVersion: 5.2 (3790) operatingSystem: Windows Server 2003 """) self.ldb.modify_ldif(""" dn: """ + self.computer_dn + """ changetype: modify replace: unicodePwd unicodePwd:: """ + base64.b64encode("\"P@ssw0rd\"".encode('utf-16-le')) + """ """) # do a simple bind and search with the machine account creds_machine.set_bind_dn(self.computer_dn) creds_machine.set_password(self.password) print "BindTest with: " + creds_machine.get_bind_dn() ldb_machine = samba.tests.connect_samdb(host, credentials=creds_machine, lp=lp, ldap_only=True) res = ldb_machine.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"]) def test_user_account_bind(self): # create user self.ldb.newuser(username=self.username, password=self.password) ldb_res = self.ldb.search(base=self.domain_dn, scope=SCOPE_SUBTREE, expression="(samAccountName=%s)" % self.username) self.assertEquals(len(ldb_res), 1) user_dn = ldb_res[0]["dn"] # do a simple bind and search with the user account in format user@realm creds_user1.set_bind_dn(self.username + "@" + creds.get_realm()) creds_user1.set_password(self.password) print "BindTest with: " + creds_user1.get_bind_dn() ldb_user1 = samba.tests.connect_samdb(host, credentials=creds_user1, lp=lp, ldap_only=True) res = ldb_user1.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"]) # do a simple bind and search with the user account in format domain\user creds_user2.set_bind_dn(creds.get_domain() + "\\" + self.username) creds_user2.set_password(self.password) print "BindTest with: " + creds_user2.get_bind_dn() ldb_user2 = samba.tests.connect_samdb(host, credentials=creds_user2, lp=lp, ldap_only=True) res = ldb_user2.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"]) # do a simple bind and search with the user account DN creds_user3.set_bind_dn(str(user_dn)) creds_user3.set_password(self.password) print "BindTest with: " + creds_user3.get_bind_dn() ldb_user3 = samba.tests.connect_samdb(host, credentials=creds_user3, lp=lp, ldap_only=True) res = ldb_user3.search(base="", expression="", scope=SCOPE_BASE, attrs=["*"]) TestProgram(module=__name__, opts=subunitopts)
19kestier/taiga-back
refs/heads/master
taiga/base/utils/db.py
12
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014 David Barragán <bameda@dbarragan.com> # 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/>. from django.contrib.contenttypes.models import ContentType from django.db import transaction from . import functions def get_typename_for_model_class(model:object, for_concrete_model=True) -> str: """ Get typename for model instance. """ if for_concrete_model: model = model._meta.concrete_model else: model = model._meta.proxy_for_model return "{0}.{1}".format(model._meta.app_label, model._meta.model_name) def get_typename_for_model_instance(model_instance): """ Get content type tuple from model instance. """ ct = ContentType.objects.get_for_model(model_instance) return ".".join([ct.app_label, ct.model]) def reload_attribute(model_instance, attr_name): """Fetch the stored value of a model instance attribute. :param model_instance: Model instance. :param attr_name: Attribute name to fetch. """ qs = type(model_instance).objects.filter(id=model_instance.id) return qs.values_list(attr_name, flat=True)[0] @transaction.atomic def save_in_bulk(instances, callback=None, precall=None, **save_options): """Save a list of model instances. :params instances: List of model instances. :params callback: Callback to call after each save. :params save_options: Additional options to use when saving each instance. """ if callback is None: callback = functions.noop if precall is None: precall = functions.noop for instance in instances: created = False if instance.pk is None: created = True precall(instance) instance.save(**save_options) callback(instance, created=created) @transaction.atomic def update_in_bulk(instances, list_of_new_values, callback=None, precall=None): """Update a list of model instances. :params instances: List of model instances. :params new_values: List of dicts where each dict is the new data corresponding to the instance in the same index position as the dict. """ if callback is None: callback = functions.noop if precall is None: precall = functions.noop for instance, new_values in zip(instances, list_of_new_values): for attribute, value in new_values.items(): setattr(instance, attribute, value) precall(instance) instance.save() callback(instance) @transaction.atomic def update_in_bulk_with_ids(ids, list_of_new_values, model): """Update a table using a list of ids. :params ids: List of ids. :params new_values: List of dicts or duples where each dict/duple is the new data corresponding to the instance in the same index position as the dict. :param model: Model of the ids. """ for id, new_values in zip(ids, list_of_new_values): model.objects.filter(id=id).update(**new_values)
claudep/pootle
refs/heads/master
pootle/core/utils/db.py
11
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from contextlib import contextmanager from django.db import connection @contextmanager def useable_connection(): connection.close_if_unusable_or_obsolete() yield connection.close_if_unusable_or_obsolete() def set_mysql_collation_for_column(apps, cursor, model, column, collation, schema): """Set the collation for a mysql column if it is not set already """ # Check its mysql - should probs check its not too old. if not hasattr(cursor.db, "mysql_version"): return # Get the db_name db_name = cursor.db.get_connection_params()['db'] # Get table_name table_name = apps.get_model(model)._meta.db_table # Get the current collation cursor.execute( "SELECT COLLATION_NAME" " FROM `information_schema`.`columns`" " WHERE TABLE_SCHEMA = '%s'" " AND TABLE_NAME = '%s'" " AND COLUMN_NAME = '%s';" % (db_name, table_name, column)) current_collation = cursor.fetchone()[0] if current_collation != collation: # set collation cursor.execute( "ALTER TABLE `%s`.`%s`" " MODIFY `%s`" " %s" " CHARACTER SET utf8" " COLLATE %s" " NOT NULL;" % (db_name, table_name, column, schema, collation))
OpenPymeMx/OCB
refs/heads/7.0
addons/email_template/__openerp__.py
56
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2009 Sharoon Thomas # Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## { 'name' : 'Email Templates', 'version' : '1.1', 'author' : 'OpenERP,OpenLabs', 'website' : 'http://openerp.com', 'category' : 'Marketing', 'depends' : ['mail'], 'description': """ Email Templating (simplified version of the original Power Email by Openlabs). ============================================================================== Lets you design complete email templates related to any OpenERP document (Sale Orders, Invoices and so on), including sender, recipient, subject, body (HTML and Text). You may also automatically attach files to your templates, or print and attach a report. For advanced use, the templates may include dynamic attributes of the document they are related to. For example, you may use the name of a Partner's country when writing to them, also providing a safe default in case the attribute is not defined. Each template contains a built-in assistant to help with the inclusion of these dynamic values. If you enable the option, a composition assistant will also appear in the sidebar of the OpenERP documents to which the template applies (e.g. Invoices). This serves as a quick way to send a new email based on the template, after reviewing and adapting the contents, if needed. This composition assistant will also turn into a mass mailing system when called for multiple documents at once. These email templates are also at the heart of the marketing campaign system (see the ``marketing_campaign`` application), if you need to automate larger campaigns on any OpenERP document. **Technical note:** only the templating system of the original Power Email by Openlabs was kept. """, 'data': [ 'wizard/email_template_preview_view.xml', 'email_template_view.xml', 'res_partner_view.xml', 'wizard/mail_compose_message_view.xml', 'security/ir.model.access.csv' ], 'demo': ['res_partner_demo.yml'], 'installable': True, 'auto_install': True, 'images': ['images/1_email_account.jpeg','images/2_email_template.jpeg','images/3_emails.jpeg'], } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
zhaochao/fuel-web
refs/heads/master
fuel_agent/fuel_agent/drivers/nailgun.py
1
# Copyright 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from fuel_agent.drivers import ks_spaces_validator from fuel_agent import errors from fuel_agent import objects from fuel_agent.openstack.common import log as logging from fuel_agent.utils import hardware_utils as hu from fuel_agent.utils import utils import yaml LOG = logging.getLogger(__name__) def match_device(hu_disk, ks_disk): """Tries to figure out if hu_disk got from hu.list_block_devices and ks_spaces_disk given correspond to the same disk device. This is the simplified version of hu.match_device :param hu_disk: A dict representing disk device how it is given by list_block_devices method. :param ks_disk: A dict representing disk device according to ks_spaces format. :returns: True if hu_disk matches ks_spaces_disk else False. """ uspec = hu_disk['uspec'] # True if at least one by-id link matches ks_disk if ('DEVLINKS' in uspec and len(ks_disk.get('extra', [])) > 0 and any(x.startswith('/dev/disk/by-id') for x in set(uspec['DEVLINKS']) & set(['/dev/%s' % l for l in ks_disk['extra']]))): return True # True if one of DEVLINKS matches ks_disk id if (len(ks_disk.get('extra', [])) == 0 and 'DEVLINKS' in uspec and 'id' in ks_disk and '/dev/%s' % ks_disk['id'] in uspec['DEVLINKS']): return True return False class Nailgun(object): def __init__(self, data): # Here data is expected to be raw provisioning data # how it is given by nailgun self.data = data def partition_data(self): return self.data['ks_meta']['pm_data']['ks_spaces'] @property def ks_disks(self): disk_filter = lambda x: x['type'] == 'disk' and x['size'] > 0 return filter(disk_filter, self.partition_data()) @property def ks_vgs(self): vg_filter = lambda x: x['type'] == 'vg' return filter(vg_filter, self.partition_data()) @property def hu_disks(self): """Actual disks which are available on this node it is a list of dicts which are formatted other way than ks_spaces disks. To match both of those formats use _match_device method. """ if not getattr(self, '_hu_disks', None): self._hu_disks = hu.list_block_devices(disks=True) return self._hu_disks def _disk_dev(self, ks_disk): # first we try to find a device that matches ks_disk # comparing by-id and by-path links matched = [hu_disk['device'] for hu_disk in self.hu_disks if match_device(hu_disk, ks_disk)] # if we can not find a device by its by-id and by-path links # we try to find a device by its name fallback = [hu_disk['device'] for hu_disk in self.hu_disks if '/dev/%s' % ks_disk['name'] == hu_disk['device']] found = matched or fallback if not found or len(found) > 1: raise errors.DiskNotFoundError( 'Disk not found: %s' % ks_disk['name']) return found[0] def _getlabel(self, label): if not label: return '' # XFS will refuse to format a partition if the # disk label is > 12 characters. return ' -L {0} '.format(label[:12]) def _get_partition_count(self, name): count = 0 for disk in self.ks_disks: count += len([v for v in disk["volumes"] if v.get('name') == name and v['size'] > 0]) return count def _num_ceph_journals(self): return self._get_partition_count('cephjournal') def _num_ceph_osds(self): return self._get_partition_count('ceph') def partition_scheme(self): LOG.debug('--- Preparing partition scheme ---') data = self.partition_data() ks_spaces_validator.validate(data) partition_scheme = objects.PartitionScheme() ceph_osds = self._num_ceph_osds() journals_left = ceph_osds ceph_journals = self._num_ceph_journals() LOG.debug('Looping over all disks in provision data') for disk in self.ks_disks: LOG.debug('Processing disk %s' % disk['name']) LOG.debug('Adding gpt table on disk %s' % disk['name']) parted = partition_scheme.add_parted( name=self._disk_dev(disk), label='gpt') # we install bootloader on every disk LOG.debug('Adding bootloader stage0 on disk %s' % disk['name']) parted.install_bootloader = True # legacy boot partition LOG.debug('Adding bios_grub partition on disk %s: size=24' % disk['name']) parted.add_partition(size=24, flags=['bios_grub']) # uefi partition (for future use) LOG.debug('Adding UEFI partition on disk %s: size=200' % disk['name']) parted.add_partition(size=200) LOG.debug('Looping over all volumes on disk %s' % disk['name']) for volume in disk['volumes']: LOG.debug('Processing volume: ' 'name=%s type=%s size=%s mount=%s vg=%s' % (volume.get('name'), volume.get('type'), volume.get('size'), volume.get('mount'), volume.get('vg'))) if volume['size'] <= 0: LOG.debug('Volume size is zero. Skipping.') continue if volume.get('name') == 'cephjournal': LOG.debug('Volume seems to be a CEPH journal volume. ' 'Special procedure is supposed to be applied.') # We need to allocate a journal partition for each ceph OSD # Determine the number of journal partitions we need on # each device ratio = math.ceil(float(ceph_osds) / ceph_journals) # No more than 10GB will be allocated to a single journal # partition size = volume["size"] / ratio if size > 10240: size = 10240 # This will attempt to evenly spread partitions across # multiple devices e.g. 5 osds with 2 journal devices will # create 3 partitions on the first device and 2 on the # second if ratio < journals_left: end = ratio else: end = journals_left for i in range(0, end): journals_left -= 1 if volume['type'] == 'partition': LOG.debug('Adding CEPH journal partition on ' 'disk %s: size=%s' % (disk['name'], size)) prt = parted.add_partition(size=size) LOG.debug('Partition name: %s' % prt.name) if 'partition_guid' in volume: LOG.debug('Setting partition GUID: %s' % volume['partition_guid']) prt.set_guid(volume['partition_guid']) continue if volume['type'] in ('partition', 'pv', 'raid'): LOG.debug('Adding partition on disk %s: size=%s' % (disk['name'], volume['size'])) prt = parted.add_partition(size=volume['size']) LOG.debug('Partition name: %s' % prt.name) if volume['type'] == 'partition': if 'partition_guid' in volume: LOG.debug('Setting partition GUID: %s' % volume['partition_guid']) prt.set_guid(volume['partition_guid']) if 'mount' in volume and volume['mount'] != 'none': LOG.debug('Adding file system on partition: ' 'mount=%s type=%s' % (volume['mount'], volume.get('file_system', 'xfs'))) partition_scheme.add_fs( device=prt.name, mount=volume['mount'], fs_type=volume.get('file_system', 'xfs'), fs_label=self._getlabel(volume.get('disk_label'))) if volume['type'] == 'pv': LOG.debug('Creating pv on partition: pv=%s vg=%s' % (prt.name, volume['vg'])) lvm_meta_size = volume.get('lvm_meta_size', 64) # The reason for that is to make sure that # there will be enough space for creating logical volumes. # Default lvm extension size is 4M. Nailgun volume # manager does not care of it and if physical volume size # is 4M * N + 3M and lvm metadata size is 4M * L then only # 4M * (N-L) + 3M of space will be available for # creating logical extensions. So only 4M * (N-L) of space # will be available for logical volumes, while nailgun # volume manager might reguire 4M * (N-L) + 3M # logical volume. Besides, parted aligns partitions # according to its own algorithm and actual partition might # be a bit smaller than integer number of mebibytes. if lvm_meta_size < 10: raise errors.WrongPartitionSchemeError( 'Error while creating physical volume: ' 'lvm metadata size is too small') metadatasize = int(math.floor((lvm_meta_size - 8) / 2)) metadatacopies = 2 partition_scheme.vg_attach_by_name( pvname=prt.name, vgname=volume['vg'], metadatasize=metadatasize, metadatacopies=metadatacopies) if volume['type'] == 'raid': if 'mount' in volume and volume['mount'] != 'none': LOG.debug('Attaching partition to RAID ' 'by its mount point %s' % volume['mount']) partition_scheme.md_attach_by_mount( device=prt.name, mount=volume['mount'], fs_type=volume.get('file_system', 'xfs'), fs_label=self._getlabel(volume.get('disk_label'))) # this partition will be used to put there configdrive image if partition_scheme.configdrive_device() is None: LOG.debug('Adding configdrive partition on disk %s: size=20' % disk['name']) parted.add_partition(size=20, configdrive=True) LOG.debug('Looping over all volume groups in provision data') for vg in self.ks_vgs: LOG.debug('Processing vg %s' % vg['id']) LOG.debug('Looping over all logical volumes in vg %s' % vg['id']) for volume in vg['volumes']: LOG.debug('Processing lv %s' % volume['name']) if volume['size'] <= 0: LOG.debug('Lv size is zero. Skipping.') continue if volume['type'] == 'lv': LOG.debug('Adding lv to vg %s: name=%s, size=%s' % (vg['id'], volume['name'], volume['size'])) lv = partition_scheme.add_lv(name=volume['name'], vgname=vg['id'], size=volume['size']) if 'mount' in volume and volume['mount'] != 'none': LOG.debug('Adding file system on lv: ' 'mount=%s type=%s' % (volume['mount'], volume.get('file_system', 'xfs'))) partition_scheme.add_fs( device=lv.device_name, mount=volume['mount'], fs_type=volume.get('file_system', 'xfs'), fs_label=self._getlabel(volume.get('disk_label'))) LOG.debug('Appending kernel parameters: %s' % self.data['ks_meta']['pm_data']['kernel_params']) partition_scheme.append_kernel_params( self.data['ks_meta']['pm_data']['kernel_params']) return partition_scheme def configdrive_scheme(self): LOG.debug('--- Preparing configdrive scheme ---') data = self.data configdrive_scheme = objects.ConfigDriveScheme() LOG.debug('Adding common parameters') admin_interface = filter( lambda x: (x['mac_address'] == data['kernel_options']['netcfg/choose_interface']), [dict(name=name, **spec) for name, spec in data['interfaces'].iteritems()])[0] ssh_auth_keys = data['ks_meta']['authorized_keys'] if data['ks_meta']['auth_key']: ssh_auth_keys.append(data['ks_meta']['auth_key']) configdrive_scheme.set_common( ssh_auth_keys=ssh_auth_keys, hostname=data['hostname'], fqdn=data['hostname'], name_servers=data['name_servers'], search_domain=data['name_servers_search'], master_ip=data['ks_meta']['master_ip'], master_url='http://%s:8000/api' % data['ks_meta']['master_ip'], udevrules=data['kernel_options']['udevrules'], admin_mac=data['kernel_options']['netcfg/choose_interface'], admin_ip=admin_interface['ip_address'], admin_mask=admin_interface['netmask'], admin_iface_name=admin_interface['name'], timezone=data['ks_meta'].get('timezone', 'America/Los_Angeles'), gw=data['ks_meta']['gw'], ks_repos=data['ks_meta']['repo_setup']['repos'] ) LOG.debug('Adding puppet parameters') configdrive_scheme.set_puppet( master=data['ks_meta']['puppet_master'], enable=data['ks_meta']['puppet_enable'] ) LOG.debug('Adding mcollective parameters') configdrive_scheme.set_mcollective( pskey=data['ks_meta']['mco_pskey'], vhost=data['ks_meta']['mco_vhost'], host=data['ks_meta']['mco_host'], user=data['ks_meta']['mco_user'], password=data['ks_meta']['mco_password'], connector=data['ks_meta']['mco_connector'], enable=data['ks_meta']['mco_enable'] ) LOG.debug('Setting configdrive profile %s' % data['profile']) configdrive_scheme.set_profile(profile=data['profile']) return configdrive_scheme def image_scheme(self, partition_scheme): LOG.debug('--- Preparing image scheme ---') data = self.data image_scheme = objects.ImageScheme() #FIXME(agordeev): this piece of code for fetching additional image # meta data should be factored out of this particular nailgun driver # into more common and absract data getter which should be able to deal # with various data sources (local file, http(s), etc.) and different # data formats ('blob', json, yaml, etc.). # So, the manager will combine and manipulate all those multiple data # getter instances. # Also, the initial data source should be set to sort out chicken/egg # problem. Command line option may be useful for such a case. # BUG: https://bugs.launchpad.net/fuel/+bug/1430418 metadata_url = data['ks_meta']['image_data']['/']['uri'].\ split('.')[0] + '.yaml' image_meta = {} raw_image_meta = None try: raw_image_meta = yaml.load( utils.init_http_request(metadata_url).text) except Exception as e: LOG.exception(e) LOG.debug('Failed to fetch/decode image meta data') if raw_image_meta: [image_meta.update(img_info) for img_info in raw_image_meta] # We assume for every file system user may provide a separate # file system image. For example if partitioning scheme has # /, /boot, /var/lib file systems then we will try to get images # for all those mount points. Images data are to be defined # at provision.json -> ['ks_meta']['image_data'] LOG.debug('Looping over all file systems in partition scheme') for fs in partition_scheme.fss: LOG.debug('Processing fs %s' % fs.mount) if fs.mount not in data['ks_meta']['image_data']: LOG.debug('There is no image for fs %s. Skipping.' % fs.mount) continue image_data = data['ks_meta']['image_data'][fs.mount] LOG.debug('Adding image for fs %s: uri=%s format=%s container=%s' % (fs.mount, image_data['uri'], image_data['format'], image_data['container'])) image_scheme.add_image( uri=image_data['uri'], target_device=fs.device, # In the future we will get format and container # from provision.json, but currently it is hard coded. format=image_data['format'], container=image_data['container'], size=image_meta.get(fs.mount, {}).get('size'), md5=image_meta.get(fs.mount, {}).get('md5'), ) return image_scheme
le9i0nx/ansible
refs/heads/devel
lib/ansible/modules/cloud/atomic/atomic_host.py
85
#!/usr/bin/python # -*- coding: utf-8 -*- # 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: atomic_host short_description: Manage the atomic host platform description: - Manage the atomic host platform. - Rebooting of Atomic host platform should be done outside this module. version_added: "2.2" author: - Saravanan KR (@krsacme) notes: - Host should be an atomic platform (verified by existence of '/run/ostree-booted' file). requirements: - atomic - python >= 2.6 options: revision: description: - The version number of the atomic host to be deployed. Providing C(latest) will upgrade to the latest available version. default: latest aliases: [ version ] ''' EXAMPLES = ''' - name: Upgrade the atomic host platform to the latest version (atomic host upgrade) atomic_host: revision: latest - name: Deploy a specific revision as the atomic host (atomic host deploy 23.130) atomic_host: revision: 23.130 ''' RETURN = ''' msg: description: The command standard output returned: always type: string sample: 'Already on latest' ''' import os import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native def core(module): revision = module.params['revision'] args = [] module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C') if revision == 'latest': args = ['atomic', 'host', 'upgrade'] else: args = ['atomic', 'host', 'deploy', revision] out = {} err = {} rc = 0 rc, out, err = module.run_command(args, check_rc=False) if rc == 77 and revision == 'latest': module.exit_json(msg="Already on latest", changed=False) elif rc != 0: module.fail_json(rc=rc, msg=err) else: module.exit_json(msg=out, changed=True) def main(): module = AnsibleModule( argument_spec=dict( revision=dict(type='str', default='latest', aliases=["version"]), ), ) # Verify that the platform is atomic host if not os.path.exists("/run/ostree-booted"): module.fail_json(msg="Module atomic_host is applicable for Atomic Host Platforms only") try: core(module) except Exception as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) if __name__ == '__main__': main()
dfunckt/django
refs/heads/master
tests/migrations/test_migrations_first/thefirst.py
2995
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): operations = [ migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=255)), ("slug", models.SlugField(null=True)), ("age", models.IntegerField(default=0)), ("silly_field", models.BooleanField(default=False)), ], ), migrations.CreateModel( "Tribble", [ ("id", models.AutoField(primary_key=True)), ("fluffy", models.BooleanField(default=True)), ], ) ]
pim89/youtube-dl
refs/heads/master
youtube_dl/extractor/restudy.py
62
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class RestudyIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?restudy\.dk/video/play/id/(?P<id>[0-9]+)' _TEST = { 'url': 'https://www.restudy.dk/video/play/id/1637', 'info_dict': { 'id': '1637', 'ext': 'flv', 'title': 'Leiden-frosteffekt', 'description': 'Denne video er et eksperiment med flydende kvælstof.', }, 'params': { # rtmp download 'skip_download': True, } } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) title = self._og_search_title(webpage).strip() description = self._og_search_description(webpage).strip() formats = self._extract_smil_formats( 'https://www.restudy.dk/awsmedia/SmilDirectory/video_%s.xml' % video_id, video_id) self._sort_formats(formats) return { 'id': video_id, 'title': title, 'description': description, 'formats': formats, }
chamikaramj/incubator-beam
refs/heads/master
sdks/python/apache_beam/runners/dataflow/internal/clients/dataflow/message_matchers.py
21
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from hamcrest.core.base_matcher import BaseMatcher IGNORED = object() class MetricStructuredNameMatcher(BaseMatcher): """Matches a MetricStructuredName.""" def __init__(self, name=IGNORED, origin=IGNORED, context=IGNORED): """Creates a MetricsStructuredNameMatcher. Any property not passed in to the constructor will be ignored when matching. Args: name: A string with the metric name. origin: A string with the metric namespace. context: A key:value dictionary that will be matched to the structured name. """ if context != IGNORED and not isinstance(context, dict): raise ValueError('context must be a Python dictionary.') self.name = name self.origin = origin self.context = context def _matches(self, item): if self.name != IGNORED and item.name != self.name: return False if self.origin != IGNORED and item.origin != self.origin: return False if self.context != IGNORED: for key, name in self.context.iteritems(): if key not in item.context: return False if name != IGNORED and item.context[key] != name: return False return True def describe_to(self, description): descriptors = [] if self.name != IGNORED: descriptors.append('name is {}'.format(self.name)) if self.origin != IGNORED: descriptors.append('origin is {}'.format(self.origin)) if self.context != IGNORED: descriptors.append('context is ({})'.format(str(self.context))) item_description = ' and '.join(descriptors) description.append(item_description) class MetricUpdateMatcher(BaseMatcher): """Matches a metrics update protocol buffer.""" def __init__(self, cumulative=IGNORED, name=IGNORED, scalar=IGNORED, kind=IGNORED): """Creates a MetricUpdateMatcher. Any property not passed in to the constructor will be ignored when matching. Args: cumulative: A boolean. name: A MetricStructuredNameMatcher object that matches the name. scalar: An integer with the metric update. kind: A string defining the kind of counter. """ if name != IGNORED and not isinstance(name, MetricStructuredNameMatcher): raise ValueError('name must be a MetricStructuredNameMatcher.') self.cumulative = cumulative self.name = name self.scalar = scalar self.kind = kind def _matches(self, item): if self.cumulative != IGNORED and item.cumulative != self.cumulative: return False if self.name != IGNORED and not self.name._matches(item.name): return False if self.kind != IGNORED and item.kind != self.kind: return False if self.scalar != IGNORED: value_property = [p for p in item.scalar.object_value.properties if p.key == 'value'] int_value = value_property[0].value.integer_value if self.scalar != int_value: return False return True def describe_to(self, description): descriptors = [] if self.cumulative != IGNORED: descriptors.append('cumulative is {}'.format(self.cumulative)) if self.name != IGNORED: descriptors.append('name is {}'.format(self.name)) if self.scalar != IGNORED: descriptors.append('scalar is ({})'.format(str(self.scalar))) item_description = ' and '.join(descriptors) description.append(item_description)
bricky/xbmc-addon-tvtumbler
refs/heads/master
resources/lib/dns/rdtypes/IN/APL.py
85
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct import dns.exception import dns.inet import dns.rdata import dns.tokenizer class APLItem(object): """An APL list item. @ivar family: the address family (IANA address family registry) @type family: int @ivar negation: is this item negated? @type negation: bool @ivar address: the address @type address: string @ivar prefix: the prefix length @type prefix: int """ __slots__ = ['family', 'negation', 'address', 'prefix'] def __init__(self, family, negation, address, prefix): self.family = family self.negation = negation self.address = address self.prefix = prefix def __str__(self): if self.negation: return "!%d:%s/%s" % (self.family, self.address, self.prefix) else: return "%d:%s/%s" % (self.family, self.address, self.prefix) def to_wire(self, file): if self.family == 1: address = dns.inet.inet_pton(dns.inet.AF_INET, self.address) elif self.family == 2: address = dns.inet.inet_pton(dns.inet.AF_INET6, self.address) else: address = self.address.decode('hex_codec') # # Truncate least significant zero bytes. # last = 0 for i in xrange(len(address) - 1, -1, -1): if address[i] != chr(0): last = i + 1 break address = address[0 : last] l = len(address) assert l < 128 if self.negation: l |= 0x80 header = struct.pack('!HBB', self.family, self.prefix, l) file.write(header) file.write(address) class APL(dns.rdata.Rdata): """APL record. @ivar items: a list of APL items @type items: list of APL_Item @see: RFC 3123""" __slots__ = ['items'] def __init__(self, rdclass, rdtype, items): super(APL, self).__init__(rdclass, rdtype) self.items = items def to_text(self, origin=None, relativize=True, **kw): return ' '.join(map(lambda x: str(x), self.items)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): items = [] while 1: token = tok.get().unescape() if token.is_eol_or_eof(): break item = token.value if item[0] == '!': negation = True item = item[1:] else: negation = False (family, rest) = item.split(':', 1) family = int(family) (address, prefix) = rest.split('/', 1) prefix = int(prefix) item = APLItem(family, negation, address, prefix) items.append(item) return cls(rdclass, rdtype, items) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): for item in self.items: item.to_wire(file) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): items = [] while 1: if rdlen < 4: raise dns.exception.FormError header = struct.unpack('!HBB', wire[current : current + 4]) afdlen = header[2] if afdlen > 127: negation = True afdlen -= 128 else: negation = False current += 4 rdlen -= 4 if rdlen < afdlen: raise dns.exception.FormError address = wire[current : current + afdlen].unwrap() l = len(address) if header[0] == 1: if l < 4: address += '\x00' * (4 - l) address = dns.inet.inet_ntop(dns.inet.AF_INET, address) elif header[0] == 2: if l < 16: address += '\x00' * (16 - l) address = dns.inet.inet_ntop(dns.inet.AF_INET6, address) else: # # This isn't really right according to the RFC, but it # seems better than throwing an exception # address = address.encode('hex_codec') current += afdlen rdlen -= afdlen item = APLItem(header[0], negation, address, header[1]) items.append(item) if rdlen == 0: break return cls(rdclass, rdtype, items) from_wire = classmethod(from_wire) def _cmp(self, other): f = cStringIO.StringIO() self.to_wire(f) wire1 = f.getvalue() f.seek(0) f.truncate() other.to_wire(f) wire2 = f.getvalue() f.close() return cmp(wire1, wire2)
benoitsteiner/tensorflow-opencl
refs/heads/master
tensorflow/contrib/learn/python/learn/datasets/text_datasets.py
124
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Text datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tarfile import numpy as np from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.python.platform import gfile DBPEDIA_URL = 'https://github.com/le-scientifique/torchDatasets/raw/master/dbpedia_csv.tar.gz' def maybe_download_dbpedia(data_dir): """Download if DBpedia data is not present.""" train_path = os.path.join(data_dir, 'dbpedia_csv/train.csv') test_path = os.path.join(data_dir, 'dbpedia_csv/test.csv') if not (gfile.Exists(train_path) and gfile.Exists(test_path)): archive_path = base.maybe_download( 'dbpedia_csv.tar.gz', data_dir, DBPEDIA_URL) tfile = tarfile.open(archive_path, 'r:*') tfile.extractall(data_dir) def load_dbpedia(size='small', test_with_fake_data=False): """Get DBpedia datasets from CSV files.""" if not test_with_fake_data: data_dir = os.path.join(os.getenv('TF_EXP_BASE_DIR', ''), 'dbpedia_data') maybe_download_dbpedia(data_dir) train_path = os.path.join(data_dir, 'dbpedia_csv', 'train.csv') test_path = os.path.join(data_dir, 'dbpedia_csv', 'test.csv') if size == 'small': # Reduce the size of original data by a factor of 1000. base.shrink_csv(train_path, 1000) base.shrink_csv(test_path, 1000) train_path = train_path.replace('train.csv', 'train_small.csv') test_path = test_path.replace('test.csv', 'test_small.csv') else: module_path = os.path.dirname(__file__) train_path = os.path.join(module_path, 'data', 'text_train.csv') test_path = os.path.join(module_path, 'data', 'text_test.csv') train = base.load_csv_without_header( train_path, target_dtype=np.int32, features_dtype=np.str, target_column=0) test = base.load_csv_without_header( test_path, target_dtype=np.int32, features_dtype=np.str, target_column=0) return base.Datasets(train=train, validation=None, test=test)
DazWorrall/zulip
refs/heads/master
tools/send_github_payloads.py
115
#!/usr/bin/python import sys import os import simplejson sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'api')) import zulip zulip_client = zulip.Client(site="http://localhost:9991", client="ZulipGithubPayloadSender/0.1") payload_dir = "zerver/fixtures/github" for filename in os.listdir(payload_dir): with open(os.path.join(payload_dir, filename)) as f: req = simplejson.loads(f.read()) req['api-key'] = zulip_client.api_key req['email'] = zulip_client.email zulip_client.do_api_query(req, zulip.API_VERSTRING + "external/github")
Udayraj123/dashboard_IITG
refs/heads/master
Binder/alpha/models.py
278
from django.db import models
Jcfunk/zva
refs/heads/master
tools/perf/python/twatch.py
7370
#! /usr/bin/python # -*- python -*- # -*- coding: utf-8 -*- # twatch - Experimental use of the perf python interface # Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com> # # This application is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; version 2. # # This application 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. import perf def main(): cpus = perf.cpu_map() threads = perf.thread_map() evsel = perf.evsel(task = 1, comm = 1, mmap = 0, wakeup_events = 1, watermark = 1, sample_id_all = 1, sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU | perf.SAMPLE_TID) evsel.open(cpus = cpus, threads = threads); evlist = perf.evlist(cpus, threads) evlist.add(evsel) evlist.mmap() while True: evlist.poll(timeout = -1) for cpu in cpus: event = evlist.read_on_cpu(cpu) if not event: continue print "cpu: %2d, pid: %4d, tid: %4d" % (event.sample_cpu, event.sample_pid, event.sample_tid), print event if __name__ == '__main__': main()
da1z/intellij-community
refs/heads/master
python/lib/Lib/site-packages/django/contrib/messages/storage/user_messages.py
308
""" Storages used to assist in the deprecation of contrib.auth User messages. """ from django.contrib.messages import constants from django.contrib.messages.storage.base import BaseStorage, Message from django.contrib.auth.models import User from django.contrib.messages.storage.fallback import FallbackStorage class UserMessagesStorage(BaseStorage): """ Retrieves messages from the User, using the legacy user.message_set API. This storage is "read-only" insofar as it can only retrieve and delete messages, not store them. """ session_key = '_messages' def _get_messages_queryset(self): """ Returns the QuerySet containing all user messages (or ``None`` if request.user is not a contrib.auth User). """ user = getattr(self.request, 'user', None) if isinstance(user, User): return user._message_set.all() def add(self, *args, **kwargs): raise NotImplementedError('This message storage is read-only.') def _get(self, *args, **kwargs): """ Retrieves a list of messages assigned to the User. This backend never stores anything, so all_retrieved is assumed to be False. """ queryset = self._get_messages_queryset() if queryset is None: # This is a read-only and optional storage, so to ensure other # storages will also be read if used with FallbackStorage an empty # list is returned rather than None. return [], False messages = [] for user_message in queryset: messages.append(Message(constants.INFO, user_message.message)) return messages, False def _store(self, messages, *args, **kwargs): """ Removes any messages assigned to the User and returns the list of messages (since no messages are stored in this read-only storage). """ queryset = self._get_messages_queryset() if queryset is not None: queryset.delete() return messages class LegacyFallbackStorage(FallbackStorage): """ Works like ``FallbackStorage`` but also handles retrieving (and clearing) contrib.auth User messages. """ storage_classes = (UserMessagesStorage,) + FallbackStorage.storage_classes
drufat/vispy
refs/heads/master
vispy/geometry/polygon.py
21
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2015, Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- import numpy as np from .triangulation import Triangulation class PolygonData(object): """Polygon class for data handling Parameters ---------- vertices : (Nv, 3) array Vertex coordinates. If faces is not specified, then this will instead be interpreted as (Nf, 3, 3) array of coordinates. edges : (Nv, 2) array Constraining edges specified by vertex indices. faces : (Nf, 3) array Indexes into the vertex array. Notes ----- All arguments are optional. """ def __init__(self, vertices=None, edges=None, faces=None): self._vertices = vertices self._edges = edges self._faces = faces self._convex_hull = None @property def faces(self): """Return an array (Nf, 3) of vertex indexes, three per triangular face in the mesh. If faces have not been computed for this mesh, the function computes them. If no vertices or faces are specified, the function returns None. """ if self._faces is None: if self._vertices is None: return None self.triangulate() return self._faces @faces.setter def faces(self, f): """ If vertices and faces are incompatible, this will generate vertices from these faces and set them. """ self._faces = f @property def vertices(self): """Return an array (Nf, 3) of vertices. If only faces exist, the function computes the vertices and returns them. If no vertices or faces are specified, the function returns None. """ if self._faces is None: if self._vertices is None: return None self.triangulate() return self._vertices @vertices.setter def vertices(self, v): """ If vertices and faces are incompatible, this will generate faces from these vertices and set them. """ self._vertices = v @property def edges(self): """Return an array (Nv, 2) of vertex indices. If no vertices or faces are specified, the function returns None. """ return self._edges @edges.setter def edges(self, e): """ Ensures that all edges are valid. """ self._edges = e @property def convex_hull(self): """Return an array of vertex indexes representing the convex hull. If faces have not been computed for this mesh, the function computes them. If no vertices or faces are specified, the function returns None. """ if self._faces is None: if self._vertices is None: return None self.triangulate() return self._convex_hull def triangulate(self): """ Triangulates the set of vertices and stores the triangles in faces and the convex hull in convex_hull. """ npts = self._vertices.shape[0] if np.any(self._vertices[0] != self._vertices[1]): # start != end, so edges must wrap around to beginning. edges = np.empty((npts, 2), dtype=np.uint32) edges[:, 0] = np.arange(npts) edges[:, 1] = edges[:, 0] + 1 edges[-1, 1] = 0 else: # start == end; no wrapping required. edges = np.empty((npts-1, 2), dtype=np.uint32) edges[:, 0] = np.arange(npts) edges[:, 1] = edges[:, 0] + 1 tri = Triangulation(self._vertices, edges) tri.triangulate() return tri.pts, tri.tris def add_vertex(self, vertex): """ Adds given vertex and retriangulates to generate new faces. Parameters ---------- vertex : array-like The vertex to add. """ raise NotImplementedError
KlausTrainer/bigcouch
refs/heads/master
couchjs/scons/scons-local-2.0.1/SCons/Tool/gcc.py
61
"""SCons.Tool.gcc Tool-specific initialization for gcc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/gcc.py 5134 2010/08/16 23:02:40 bdeegan" import cc import os import re import subprocess import SCons.Util compilers = ['gcc', 'cc'] def generate(env): """Add Builders and construction variables for gcc to an Environment.""" cc.generate(env) env['CC'] = env.Detect(compilers) or 'gcc' if env['PLATFORM'] in ['cygwin', 'win32']: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') else: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC') # determine compiler version if env['CC']: #pipe = SCons.Action._subproc(env, [env['CC'], '-dumpversion'], pipe = SCons.Action._subproc(env, [env['CC'], '--version'], stdin = 'devnull', stderr = 'devnull', stdout = subprocess.PIPE) if pipe.wait() != 0: return # -dumpversion was added in GCC 3.0. As long as we're supporting # GCC versions older than that, we should use --version and a # regular expression. #line = pipe.stdout.read().strip() #if line: # env['CCVERSION'] = line line = pipe.stdout.readline() match = re.search(r'[0-9]+(\.[0-9]+)+', line) if match: env['CCVERSION'] = match.group(0) def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
rrva/uwsgi
refs/heads/master
tests/grunter.py
21
import uwsgi import time def application(env, start_response): start_response('200 Ok', [('Content-Type', 'text/html')]) yield "I am the worker %d<br/>" % uwsgi.worker_id() grunt = uwsgi.grunt() if grunt is None: print "worker %d detached" % uwsgi.worker_id() else: yield "And now i am the grunt with a fix worker id of %d<br/>" % uwsgi.worker_id() time.sleep(2) yield "Now, i will start a very slow task...<br/>" for i in xrange(1, 10): yield "waiting for %d seconds<br/>" % i time.sleep(i)
peercoin/peercoin
refs/heads/master
test/functional/wallet_txn_doublespend.py
10
#!/usr/bin/env python3 # Copyright (c) 2014-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the wallet accounts properly when there is a double-spend conflict.""" from decimal import Decimal from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, connect_nodes, disconnect_nodes, find_output, ) class TxnMallTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 self.supports_cli = False def skip_test_if_missing_module(self): self.skip_if_no_wallet() def add_options(self, parser): parser.add_argument("--mineblock", dest="mine_block", default=False, action="store_true", help="Test double-spend of 1-confirmed transaction") def setup_network(self): # Start with split network: super().setup_network() disconnect_nodes(self.nodes[1], 2) disconnect_nodes(self.nodes[2], 1) def run_test(self): # All nodes should start with 1,250 BTC: starting_balance = 1250 # All nodes should be out of IBD. # If the nodes are not all out of IBD, that can interfere with # blockchain sync later in the test when nodes are connected, due to # timing issues. for n in self.nodes: assert n.getblockchaininfo()["initialblockdownload"] == False for i in range(4): assert_equal(self.nodes[i].getbalance(), starting_balance) self.nodes[i].getnewaddress("") # bug workaround, coins generated assigned to first getnewaddress! # Assign coins to foo and bar addresses: node0_address_foo = self.nodes[0].getnewaddress() fund_foo_txid = self.nodes[0].sendtoaddress(node0_address_foo, 1219) fund_foo_tx = self.nodes[0].gettransaction(fund_foo_txid) node0_address_bar = self.nodes[0].getnewaddress() fund_bar_txid = self.nodes[0].sendtoaddress(node0_address_bar, 29) fund_bar_tx = self.nodes[0].gettransaction(fund_bar_txid) assert_equal(self.nodes[0].getbalance(), starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"]) # Coins are sent to node1_address node1_address = self.nodes[1].getnewaddress() # First: use raw transaction API to send 1240 BTC to node1_address, # but don't broadcast: doublespend_fee = Decimal('-.02') rawtx_input_0 = {} rawtx_input_0["txid"] = fund_foo_txid rawtx_input_0["vout"] = find_output(self.nodes[0], fund_foo_txid, 1219) rawtx_input_1 = {} rawtx_input_1["txid"] = fund_bar_txid rawtx_input_1["vout"] = find_output(self.nodes[0], fund_bar_txid, 29) inputs = [rawtx_input_0, rawtx_input_1] change_address = self.nodes[0].getnewaddress() outputs = {} outputs[node1_address] = 1240 outputs[change_address] = 1248 - 1240 + doublespend_fee rawtx = self.nodes[0].createrawtransaction(inputs, outputs) doublespend = self.nodes[0].signrawtransactionwithwallet(rawtx) assert_equal(doublespend["complete"], True) # Create two spends using 1 50 BTC coin each txid1 = self.nodes[0].sendtoaddress(node1_address, 40) txid2 = self.nodes[0].sendtoaddress(node1_address, 20) # Have node0 mine a block: if (self.options.mine_block): self.nodes[0].generate(1) self.sync_blocks(self.nodes[0:2]) tx1 = self.nodes[0].gettransaction(txid1) tx2 = self.nodes[0].gettransaction(txid2) # Node0's balance should be starting balance, plus 50BTC for another # matured block, minus 40, minus 20, and minus transaction fees: expected = starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"] if self.options.mine_block: expected += 50 expected += tx1["amount"] + tx1["fee"] expected += tx2["amount"] + tx2["fee"] assert_equal(self.nodes[0].getbalance(), expected) if self.options.mine_block: assert_equal(tx1["confirmations"], 1) assert_equal(tx2["confirmations"], 1) # Node1's balance should be both transaction amounts: assert_equal(self.nodes[1].getbalance(), starting_balance - tx1["amount"] - tx2["amount"]) else: assert_equal(tx1["confirmations"], 0) assert_equal(tx2["confirmations"], 0) # Now give doublespend and its parents to miner: self.nodes[2].sendrawtransaction(fund_foo_tx["hex"]) self.nodes[2].sendrawtransaction(fund_bar_tx["hex"]) doublespend_txid = self.nodes[2].sendrawtransaction(doublespend["hex"]) # ... mine a block... self.nodes[2].generate(1) # Reconnect the split network, and sync chain: connect_nodes(self.nodes[1], 2) self.nodes[2].generate(1) # Mine another block to make sure we sync self.sync_blocks() assert_equal(self.nodes[0].gettransaction(doublespend_txid)["confirmations"], 2) # Re-fetch transaction info: tx1 = self.nodes[0].gettransaction(txid1) tx2 = self.nodes[0].gettransaction(txid2) # Both transactions should be conflicted assert_equal(tx1["confirmations"], -2) assert_equal(tx2["confirmations"], -2) # Node0's total balance should be starting balance, plus 100BTC for # two more matured blocks, minus 1240 for the double-spend, plus fees (which are # negative): expected = starting_balance + 100 - 1240 + fund_foo_tx["fee"] + fund_bar_tx["fee"] + doublespend_fee assert_equal(self.nodes[0].getbalance(), expected) # Node1's balance should be its initial balance (1250 for 25 block rewards) plus the doublespend: assert_equal(self.nodes[1].getbalance(), 1250 + 1240) if __name__ == '__main__': TxnMallTest().main()
shahar-stratoscale/nova
refs/heads/master
nova/api/openstack/compute/plugins/v3/hypervisors.py
13
# Copyright (c) 2012 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. """The hypervisors admin extension.""" import webob.exc from nova.api.openstack import extensions from nova import compute from nova import exception from nova.openstack.common.gettextutils import _ ALIAS = "os-hypervisors" authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS) class HypervisorsController(object): """The Hypervisors API controller for the OpenStack API.""" def __init__(self): self.host_api = compute.HostAPI() super(HypervisorsController, self).__init__() def _view_hypervisor(self, hypervisor, detail, servers=None, **kwargs): hyp_dict = { 'id': hypervisor['id'], 'hypervisor_hostname': hypervisor['hypervisor_hostname'], } if detail and not servers: for field in ('vcpus', 'memory_mb', 'local_gb', 'vcpus_used', 'memory_mb_used', 'local_gb_used', 'hypervisor_type', 'hypervisor_version', 'free_ram_mb', 'free_disk_gb', 'current_workload', 'running_vms', 'cpu_info', 'disk_available_least', 'host_ip'): hyp_dict[field] = hypervisor[field] hyp_dict['service'] = { 'id': hypervisor['service_id'], 'host': hypervisor['service']['host'], } if servers != None: hyp_dict['servers'] = [dict(name=serv['name'], id=serv['uuid']) for serv in servers] # Add any additional info if kwargs: hyp_dict.update(kwargs) return hyp_dict @extensions.expected_errors(()) def index(self, req): context = req.environ['nova.context'] authorize(context) compute_nodes = self.host_api.compute_node_get_all(context) req.cache_db_compute_nodes(compute_nodes) return dict(hypervisors=[self._view_hypervisor(hyp, False) for hyp in compute_nodes]) @extensions.expected_errors(()) def detail(self, req): context = req.environ['nova.context'] authorize(context) compute_nodes = self.host_api.compute_node_get_all(context) req.cache_db_compute_nodes(compute_nodes) return dict(hypervisors=[self._view_hypervisor(hyp, True) for hyp in compute_nodes]) @extensions.expected_errors(404) def show(self, req, id): context = req.environ['nova.context'] authorize(context) try: hyp = self.host_api.compute_node_get(context, id) req.cache_db_compute_node(hyp) except (ValueError, exception.ComputeHostNotFound): msg = _("Hypervisor with ID '%s' could not be found.") % id raise webob.exc.HTTPNotFound(explanation=msg) return dict(hypervisor=self._view_hypervisor(hyp, True)) @extensions.expected_errors((404, 501)) def uptime(self, req, id): context = req.environ['nova.context'] authorize(context) try: hyp = self.host_api.compute_node_get(context, id) req.cache_db_compute_node(hyp) except (ValueError, exception.ComputeHostNotFound): msg = _("Hypervisor with ID '%s' could not be found.") % id raise webob.exc.HTTPNotFound(explanation=msg) # Get the uptime try: host = hyp['service']['host'] uptime = self.host_api.get_host_uptime(context, host) except NotImplementedError: msg = _("Virt driver does not implement uptime function.") raise webob.exc.HTTPNotImplemented(explanation=msg) return dict(hypervisor=self._view_hypervisor(hyp, False, uptime=uptime)) @extensions.expected_errors(400) def search(self, req): context = req.environ['nova.context'] authorize(context) query = req.GET.get('query', None) if not query: msg = _("Need parameter 'query' to specify " "which hypervisor to filter on") raise webob.exc.HTTPBadRequest(explanation=msg) hypervisors = self.host_api.compute_node_search_by_hypervisor( context, query) return dict(hypervisors=[self._view_hypervisor(hyp, False) for hyp in hypervisors]) @extensions.expected_errors(404) def servers(self, req, id): context = req.environ['nova.context'] authorize(context) try: compute_node = self.host_api.compute_node_get(context, id) except (ValueError, exception.ComputeHostNotFound): msg = _("Hypervisor with ID '%s' could not be found.") % id raise webob.exc.HTTPNotFound(explanation=msg) instances = self.host_api.instance_get_all_by_host(context, compute_node['service']['host']) return dict(hypervisor=self._view_hypervisor(compute_node, False, instances)) @extensions.expected_errors(()) def statistics(self, req): context = req.environ['nova.context'] authorize(context) stats = self.host_api.compute_node_statistics(context) return dict(hypervisor_statistics=stats) class Hypervisors(extensions.V3APIExtensionBase): """Admin-only hypervisor administration.""" name = "Hypervisors" alias = ALIAS version = 1 def get_resources(self): resources = [extensions.ResourceExtension(ALIAS, HypervisorsController(), collection_actions={'detail': 'GET', 'search': 'GET', 'statistics': 'GET'}, member_actions={'uptime': 'GET', 'servers': 'GET'})] return resources def get_controller_extensions(self): return []
Lord-Nazdar/mini-sentry
refs/heads/master
sentry.py
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Sentry This is a dead-simple movement detection application with slack notification. The computer's camera is used to take a picture at a given speed, then use opencv to detect movement. When a movement is detected, a picture is uploaded to slack. Installation/Configuration: 1. `pip install opencv-python requests docopt` 2. If you want slack integration set your token and channel accordingly in the command line arguments Usage: sentry.py [--speed=<speed>] [--training] [--debug] [(--slack --slack-token=<token> --slack-channel=<channel>)] [--slack-blind] sentry.py [--speed=<speed>] [--capture=<number>] sentry.py (-h | --help) sentry.py --version Options: -h --help Show this screen --version Show version --speed=<speed> Set playback or record speed in millisecond [default: 2000] --training Use training sequence located under export --capture=<number> Capture and save a set of images --debug Display in a window the images used and processed --slack Send messages for events on slack --slack-token=<token> OAuth token to interact on slack --slack-channel=<channel> Which slack channel to interact on --slack-blind Only send message notification to slack (no images) LICENSE: MIT (see LICENSE file) """ import os, sys import subprocess import time from datetime import datetime from docopt import docopt import cv2 import requests import slack SPEED = 0 SLACK = None def detected(frame): """ Movement was detected, send notification to slack, get the frame where the movement was detected""" now = datetime.now() image_name = 'detected/{:%d%m%y%H%M%S}.jpg'.format(now) result = cv2.imwrite(image_name, frame) if SLACK: if arguments["--slack-blind"]: SLACK.post_message("Alert! A red spy is in the base!! At: {}".format(now)) else: image = open(image_name, "rb") SLACK.post_image(image, "Alert! A red spy is in the base!!", "{}".format(now)) # This method is based on the work of Kameda, Y. & Minoh, M. "A human motion # estimation method using 3-successive video frames." # The idea is to estimate movement based on the analysis on three frames to # eliminate ghosting artifacts. def process_frame(frame_tm1, frame_t, frame_tp1): """ Process the frame to extract movement Get previous, under analysis, and next frame as arguments Return gray scale version of the next frame and boolean corresponding to movement detection """ gray_frame = cv2.cvtColor(frame_tp1, cv2.COLOR_BGR2GRAY) if frame_tm1 is None or frame_t is None: return (gray_frame, False) # Get the difference between t-1 and t, and t and t+1 diff_image_im1 = cv2.absdiff(frame_tm1, frame_t) diff_image_i = cv2.absdiff(frame_t, gray_frame) # And between the wo previous images double_diff = cv2.bitwise_and(diff_image_im1,diff_image_i); # Clean the result a bit ret, thres_double_diff = cv2.threshold(double_diff, 40, 255, cv2.THRESH_BINARY) # Enough pixel changed but not too much (aka. background change) number_changed = cv2.countNonZero(thres_double_diff) height, width = thres_double_diff.shape nb_pixel = height*width if number_changed > nb_pixel * 0.01 and number_changed < nb_pixel * 0.4: if arguments["--debug"]: cv2.imshow("frame",thres_double_diff) cv2.waitKey(0) return (gray_frame, True) return (gray_frame, False) def play_feed(): """ Play the video feed, either from file or from camera """ camera = cv2.VideoCapture(0) frame_tm1 = None frame_t = None if arguments["--debug"]: cv2.namedWindow('frame', cv2.WINDOW_NORMAL) i = 0 while True: frame = None if arguments["--training"]: frame = cv2.imread("export/{}.jpg".format(i)) if frame is None: return else: (success, frame) = camera.read() # Process the frame temp, detection = process_frame(frame_tm1, frame_t, frame) # Alert! A red spy is in the base!! if detection: detected(frame_t) frame_tm1 = frame_t; frame_t = temp if arguments["--debug"]: cv2.imshow("frame",frame) cv2.waitKey(int(SPEED)) else: time.sleep(int(SPEED)/1000) i+=1 camera.release() def capture_training(number): """ Capture a define number of training frames in order to be used later """ # Use the video capture camera = cv2.VideoCapture(0) # Capture number images for i in range(0, int(number)): (success, frame) = camera.read() cv2.imwrite("export/{}.jpg".format(i), frame) time.sleep(int(SPEED)/1000) camera.release() # Get the argument dictionnary arguments = docopt(__doc__, version='Sentry 0.1.1') SPEED = arguments["--speed"] # Create the slack instance if needs be if arguments["--slack"]: SLACK = slack.slack_instance(arguments["--slack-token"], arguments["--slack-channel"]) if arguments["--capture"]: capture_training(arguments["--capture"]) else: play_feed()
tbreloff/Qwt.jl
refs/heads/master
src/python/pythonwidgets.py
2
from qwt_common import * from PyQt4.QtCore import * from PyQt4.QtGui import * import PyQt4.Qwt5 as Qwt import signal def sigint_handler(*args): sys.stderr.write('\r') QApplication.quit() signal.signal(signal.SIGINT, sigint_handler) colorList = [Qt.black, Qt.red, Qt.green, Qt.blue, Qt.cyan, Qt.magenta, Qt.darkRed, Qt.darkGreen, Qt.darkBlue, Qt.darkCyan, Qt.darkMagenta] class TextTable: def __init__(self, widths, rjust = None, headers = None): self.widths = widths if rjust is None: self.rjust = [True for x in widths] else: self.rjust = rjust self.headers = headers self.numCols = len(widths) if len(self.rjust) != self.numCols or (headers != None and len(headers) != self.numCols): raise 'Error in TextTable initialization. %s %s %s' % (str(widths), str(self.rjust), str(headers)) def get(self, data): final = '' if self.headers != None: data = [self.headers] + data lines = [] for row in data: thisRow = '' for c,cell in enumerate(row): s = str(cell) if self.rjust[c]: thisRow += s.rjust(self.widths[c]) else: thisRow += s.ljust(self.widths[c]) thisRow += ' ' lines.append(thisRow) #final += '\n' return '\n'.join(lines), max([len(l) for l in lines]) class SimpleText(QTextEdit): def __init__(self, widths, rjust = None, headers = None): QTextEdit.__init__(self) self.setReadOnly(True) self.setFontSize(12) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) #self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table = TextTable(widths, rjust, headers) def update(self, data): text, totalWidth = self.table.get(data) self.setText(text) self.setMinimumWidth(totalWidth * self.widthPerChar + 30) self.setMinimumHeight(min(300, len(data) * self.heightPerChar + 20)) def setFontSize(self, pt): font = QFont('Courier', pt) self.setCurrentFont(font) fm = QFontMetrics(font) self.widthPerChar = fm.width('a') self.heightPerChar = fm.height() class LayoutSplitter(QSplitter): def __init__(self, layouts, o = Qt.Vertical): QSplitter.__init__(self, o) for layout in layouts: frame = QFrame() frame.setLayout(layout) self.addWidget(frame) class YbLabel(QLabel): def __init__(self, txt): super(YbLabel, self).__init__(txt) #self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.setAlignment(Qt.AlignRight | Qt.AlignVCenter) class YbListInput(QWidget): def __init__(self, fn, buttonText, buttonClickedFunction): QWidget.__init__(self) self.fn = fn self.text = QTextEdit() try: self.text.setText(open(self.fn).read()) except: pass self.text.textChanged.connect(self.chg) self.button = QPushButton('Set: %s' % buttonText) self.button.clicked.connect(buttonClickedFunction) for x in [self.text,self.button,self]: x.setMinimumWidth(50) layout = QVBoxLayout() layout.addWidget(self.text) layout.addWidget(self.button) self.setLayout(layout) self.chg() def chg(self): #self.text.setTextBackgroundColor(QColor(Qt.lightGray)) self.button.setStyleSheet("QPushButton { background-color: darkGray }") def parseText(self, minColumns = 2): #print self.text.toPlainText() res = [] try: lines = [l.upper() for l in str(self.text.toPlainText()).split('\n')] lines.sort() linesout = [] for l in lines: tmp = l.strip().split() if len(tmp) >= minColumns: res.append(tmp) linesout.append(l) else: print 'Not enough columns: line "%s"' % l f = open(self.fn, 'w') f.write('\n'.join(linesout)) f.close() self.text.setText('\n'.join(linesout)) except Exception, e: print 'Error: %s' % e #self.text.setTextBackgroundColor(QColor(Qt.white)) self.button.setStyleSheet("QPushButton { background-color: lightGray }") return res class SelectOnFocusLineEdit(QLineEdit): #def __init__(self, text, parent=None): # super(SelectOnFocusLineEdit, self).__init__(text, parent) # self.selectOnMousePress = False #def focusInEvent(self, evt): # QLineEdit.focusInEvent(self, evt) # self.setFocus() # self.selectAll() # self.selectOnMousePress = True def mousePressEvent(self, evt): self.clear() QLineEdit.mousePressEvent(self, evt) #if self.selectOnMousePress: # #self.selectAll() # self.selectOnMousePress = False # takes a nested list and returns a layered layout def buildLayout(widgets, horizontal = False, splitters = []): layout = QHBoxLayout() if horizontal else QVBoxLayout() if len(widgets) > 0 and widgets[-1] == 'splitter': splitter = QSplitter(Qt.Horizontal if horizontal else Qt.Vertical) for w in widgets[:-1]: #print '!!!!!!!!!!!', w, type(w) if type(w) == list: frame = QFrame() frame.setLayout(buildLayout(w, not horizontal, splitters)) splitter.addWidget(frame) elif type(w) in [QHBoxLayout, QVBoxLayout, QFormLayout, QGridLayout, QLayout]: frame = QFrame() frame.setLayout(w) splitter.addWidget(frame) else: splitter.addWidget(w) layout.addWidget(splitter) splitters.append(splitter) else: for w in widgets: #print '!!!!!!!!!xx', w, type(w) if type(w) == list: layout.addLayout(buildLayout(w, not horizontal, splitters)) elif type(w) in [QHBoxLayout, QVBoxLayout, QFormLayout, QGridLayout, QLayout]: layout.addLayout(w) else: layout.addWidget(w) return layout def pdb(debug = False): print traceback.print_exc() if debug: from PyQt4.QtCore import pyqtRemoveInputHook import pdb pyqtRemoveInputHook() pdb.set_trace()
hrishioa/Aviato
refs/heads/master
flask/Lib/site-packages/requests/packages/chardet/__init__.py
1777
######################## BEGIN LICENSE BLOCK ######################## # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### __version__ = "2.3.0" from sys import version_info def detect(aBuf): if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or (version_info >= (3, 0) and not isinstance(aBuf, bytes))): raise ValueError('Expected a bytes object, not a unicode object') from . import universaldetector u = universaldetector.UniversalDetector() u.reset() u.feed(aBuf) u.close() return u.result
dlazz/ansible
refs/heads/devel
lib/ansible/modules/monitoring/logentries.py
122
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Ivan Vanderbyl <ivan@app.io> # 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: logentries author: "Ivan Vanderbyl (@ivanvanderbyl)" 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 = ''' # Track nginx logs - logentries: path: /var/log/nginx/access.log state: present name: nginx-access-log # Stop tracking nginx logs - logentries: path: /var/log/nginx/error.log state: absent ''' from ansible.module_utils.basic import AnsibleModule 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 in case 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) if __name__ == '__main__': main()
swcarpentry/amy
refs/heads/develop
amy/dashboard/forms.py
1
from django import forms from django.core.exceptions import ValidationError from django.db.models import Q from django_countries.fields import CountryField from workshops.models import ( Language, GenderMixin, Person, TrainingProgress, TrainingRequirement, ) from workshops.forms import BootstrapHelper # this is used instead of Django Autocomplete Light widgets # see issue #1330: https://github.com/swcarpentry/amy/issues/1330 from workshops.fields import ( Select2Widget, ModelSelect2MultipleWidget, RadioSelectWithOther, ) class AssignmentForm(forms.Form): assigned_to = forms.ModelChoiceField( label="Assigned to:", required=False, queryset=Person.objects.filter( Q(is_superuser=True) | Q(groups__name="administrators") ).distinct(), widget=Select2Widget(), ) helper = BootstrapHelper( add_submit_button=False, add_cancel_button=False, wider_labels=True, use_get_method=True, form_id="assignment-form" ) class AutoUpdateProfileForm(forms.ModelForm): username = forms.CharField(disabled=True, required=False) email = forms.CharField( disabled=True, required=False, label=Person._meta.get_field('email').verbose_name, help_text=Person._meta.get_field('email').help_text, ) github = forms.CharField( disabled=True, required=False, help_text='If you want to change your github username, please email ' 'us at <a href="mailto:team@carpentries.org">' 'team@carpentries.org</a>.') country = CountryField().formfield( required=False, help_text='Your country of residence.', widget=Select2Widget, ) languages = forms.ModelMultipleChoiceField( label='Languages', required=False, queryset=Language.objects.all(), widget=ModelSelect2MultipleWidget(data_view='language-lookup') ) helper = BootstrapHelper(add_cancel_button=False) class Meta: model = Person fields = [ 'personal', 'middle', 'family', 'email', 'secondary_email', 'gender', 'gender_other', 'may_contact', 'publish_profile', 'lesson_publication_consent', 'country', 'airport', 'github', 'twitter', 'url', 'username', 'affiliation', 'domains', 'lessons', 'languages', 'occupation', 'orcid', ] readonly_fields = ( 'username', 'github', ) widgets = { 'gender': RadioSelectWithOther('gender_other'), 'domains': forms.CheckboxSelectMultiple(), 'lessons': forms.CheckboxSelectMultiple(), 'airport': Select2Widget, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # set up a layout object for the helper self.helper.layout = self.helper.build_default_layout(self) # set up `*WithOther` widgets so that they can display additional # fields inline self['gender'].field.widget.other_field = self['gender_other'] # remove additional fields self.helper.layout.fields.remove('gender_other') def clean(self): super().clean() errors = dict() # 1: require "other gender" field if "other" was selected in # "gender" field gender = self.cleaned_data.get('gender', '') gender_other = self.cleaned_data.get('gender_other', '') if gender == GenderMixin.OTHER and not gender_other: errors['gender'] = ValidationError("This field is required.") elif gender != GenderMixin.OTHER and gender_other: errors['gender'] = ValidationError( 'If you entered data in "Other" field, please select that ' "option.") # raise errors if any present if errors: raise ValidationError(errors) class SendHomeworkForm(forms.ModelForm): url = forms.URLField(label='URL') requirement = forms.ModelChoiceField( queryset=TrainingRequirement.objects.filter(name__endswith="Homework"), label="Type", required=True, ) helper = BootstrapHelper(add_cancel_button=False) class Meta: model = TrainingProgress fields = [ 'requirement', 'url', ] class SearchForm(forms.Form): """Represent general searching form.""" term = forms.CharField(label="Term", max_length=100) no_redirect = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) helper = BootstrapHelper(add_cancel_button=False, use_get_method=True)
ebifrier/one-godwhale2015
refs/heads/master
third-party/gtest-1.7.0/test/gtest_help_test.py
2968
#!/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. """Tests the --help flag of Google C++ Testing Framework. SYNOPSIS gtest_help_test.py --build_dir=BUILD/DIR # where BUILD/DIR contains the built gtest_help_test_ file. gtest_help_test.py """ __author__ = 'wan@google.com (Zhanyong Wan)' import os import re import gtest_test_utils IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_') FLAG_PREFIX = '--gtest_' DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style' STREAM_RESULT_TO_FLAG = FLAG_PREFIX + 'stream_result_to' UNKNOWN_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing' LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', LIST_TESTS_FLAG), re.sub('^--', '/', LIST_TESTS_FLAG), re.sub('_', '-', LIST_TESTS_FLAG)] INTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing' SUPPORTS_DEATH_TESTS = "DeathTest" in gtest_test_utils.Subprocess( [PROGRAM_PATH, LIST_TESTS_FLAG]).output # The help message must match this regex. HELP_REGEX = re.compile( FLAG_PREFIX + r'list_tests.*' + FLAG_PREFIX + r'filter=.*' + FLAG_PREFIX + r'also_run_disabled_tests.*' + FLAG_PREFIX + r'repeat=.*' + FLAG_PREFIX + r'shuffle.*' + FLAG_PREFIX + r'random_seed=.*' + FLAG_PREFIX + r'color=.*' + FLAG_PREFIX + r'print_time.*' + FLAG_PREFIX + r'output=.*' + FLAG_PREFIX + r'break_on_failure.*' + FLAG_PREFIX + r'throw_on_failure.*' + FLAG_PREFIX + r'catch_exceptions=0.*', re.DOTALL) def RunWithFlag(flag): """Runs gtest_help_test_ with the given flag. Returns: the exit code and the text output as a tuple. Args: flag: the command-line flag to pass to gtest_help_test_, or None. """ if flag is None: command = [PROGRAM_PATH] else: command = [PROGRAM_PATH, flag] child = gtest_test_utils.Subprocess(command) return child.exit_code, child.output class GTestHelpTest(gtest_test_utils.TestCase): """Tests the --help flag and its equivalent forms.""" def TestHelpFlag(self, flag): """Verifies correct behavior when help flag is specified. The right message must be printed and the tests must skipped when the given flag is specified. Args: flag: A flag to pass to the binary or None. """ exit_code, output = RunWithFlag(flag) self.assertEquals(0, exit_code) self.assert_(HELP_REGEX.search(output), output) if IS_LINUX: self.assert_(STREAM_RESULT_TO_FLAG in output, output) else: self.assert_(STREAM_RESULT_TO_FLAG not in output, output) if SUPPORTS_DEATH_TESTS and not IS_WINDOWS: self.assert_(DEATH_TEST_STYLE_FLAG in output, output) else: self.assert_(DEATH_TEST_STYLE_FLAG not in output, output) def TestNonHelpFlag(self, flag): """Verifies correct behavior when no help flag is specified. Verifies that when no help flag is specified, the tests are run and the help message is not printed. Args: flag: A flag to pass to the binary or None. """ exit_code, output = RunWithFlag(flag) self.assert_(exit_code != 0) self.assert_(not HELP_REGEX.search(output), output) def testPrintsHelpWithFullFlag(self): self.TestHelpFlag('--help') def testPrintsHelpWithShortFlag(self): self.TestHelpFlag('-h') def testPrintsHelpWithQuestionFlag(self): self.TestHelpFlag('-?') def testPrintsHelpWithWindowsStyleQuestionFlag(self): self.TestHelpFlag('/?') def testPrintsHelpWithUnrecognizedGoogleTestFlag(self): self.TestHelpFlag(UNKNOWN_FLAG) def testPrintsHelpWithIncorrectFlagStyle(self): for incorrect_flag in INCORRECT_FLAG_VARIANTS: self.TestHelpFlag(incorrect_flag) def testRunsTestsWithoutHelpFlag(self): """Verifies that when no help flag is specified, the tests are run and the help message is not printed.""" self.TestNonHelpFlag(None) def testRunsTestsWithGtestInternalFlag(self): """Verifies that the tests are run and no help message is printed when a flag starting with Google Test prefix and 'internal_' is supplied.""" self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING) if __name__ == '__main__': gtest_test_utils.Main()
adam111316/SickGear
refs/heads/master
lib/unidecode/x05b.py
252
data = ( 'Gui ', # 0x00 'Deng ', # 0x01 'Zhi ', # 0x02 'Xu ', # 0x03 'Yi ', # 0x04 'Hua ', # 0x05 'Xi ', # 0x06 'Hui ', # 0x07 'Rao ', # 0x08 'Xi ', # 0x09 'Yan ', # 0x0a 'Chan ', # 0x0b 'Jiao ', # 0x0c 'Mei ', # 0x0d 'Fan ', # 0x0e 'Fan ', # 0x0f 'Xian ', # 0x10 'Yi ', # 0x11 'Wei ', # 0x12 'Jiao ', # 0x13 'Fu ', # 0x14 'Shi ', # 0x15 'Bi ', # 0x16 'Shan ', # 0x17 'Sui ', # 0x18 'Qiang ', # 0x19 'Lian ', # 0x1a 'Huan ', # 0x1b 'Xin ', # 0x1c 'Niao ', # 0x1d 'Dong ', # 0x1e 'Yi ', # 0x1f 'Can ', # 0x20 'Ai ', # 0x21 'Niang ', # 0x22 'Neng ', # 0x23 'Ma ', # 0x24 'Tiao ', # 0x25 'Chou ', # 0x26 'Jin ', # 0x27 'Ci ', # 0x28 'Yu ', # 0x29 'Pin ', # 0x2a 'Yong ', # 0x2b 'Xu ', # 0x2c 'Nai ', # 0x2d 'Yan ', # 0x2e 'Tai ', # 0x2f 'Ying ', # 0x30 'Can ', # 0x31 'Niao ', # 0x32 'Wo ', # 0x33 'Ying ', # 0x34 'Mian ', # 0x35 'Kaka ', # 0x36 'Ma ', # 0x37 'Shen ', # 0x38 'Xing ', # 0x39 'Ni ', # 0x3a 'Du ', # 0x3b 'Liu ', # 0x3c 'Yuan ', # 0x3d 'Lan ', # 0x3e 'Yan ', # 0x3f 'Shuang ', # 0x40 'Ling ', # 0x41 'Jiao ', # 0x42 'Niang ', # 0x43 'Lan ', # 0x44 'Xian ', # 0x45 'Ying ', # 0x46 'Shuang ', # 0x47 'Shuai ', # 0x48 'Quan ', # 0x49 'Mi ', # 0x4a 'Li ', # 0x4b 'Luan ', # 0x4c 'Yan ', # 0x4d 'Zhu ', # 0x4e 'Lan ', # 0x4f 'Zi ', # 0x50 'Jie ', # 0x51 'Jue ', # 0x52 'Jue ', # 0x53 'Kong ', # 0x54 'Yun ', # 0x55 'Zi ', # 0x56 'Zi ', # 0x57 'Cun ', # 0x58 'Sun ', # 0x59 'Fu ', # 0x5a 'Bei ', # 0x5b 'Zi ', # 0x5c 'Xiao ', # 0x5d 'Xin ', # 0x5e 'Meng ', # 0x5f 'Si ', # 0x60 'Tai ', # 0x61 'Bao ', # 0x62 'Ji ', # 0x63 'Gu ', # 0x64 'Nu ', # 0x65 'Xue ', # 0x66 '[?] ', # 0x67 'Zhuan ', # 0x68 'Hai ', # 0x69 'Luan ', # 0x6a 'Sun ', # 0x6b 'Huai ', # 0x6c 'Mie ', # 0x6d 'Cong ', # 0x6e 'Qian ', # 0x6f 'Shu ', # 0x70 'Chan ', # 0x71 'Ya ', # 0x72 'Zi ', # 0x73 'Ni ', # 0x74 'Fu ', # 0x75 'Zi ', # 0x76 'Li ', # 0x77 'Xue ', # 0x78 'Bo ', # 0x79 'Ru ', # 0x7a 'Lai ', # 0x7b 'Nie ', # 0x7c 'Nie ', # 0x7d 'Ying ', # 0x7e 'Luan ', # 0x7f 'Mian ', # 0x80 'Zhu ', # 0x81 'Rong ', # 0x82 'Ta ', # 0x83 'Gui ', # 0x84 'Zhai ', # 0x85 'Qiong ', # 0x86 'Yu ', # 0x87 'Shou ', # 0x88 'An ', # 0x89 'Tu ', # 0x8a 'Song ', # 0x8b 'Wan ', # 0x8c 'Rou ', # 0x8d 'Yao ', # 0x8e 'Hong ', # 0x8f 'Yi ', # 0x90 'Jing ', # 0x91 'Zhun ', # 0x92 'Mi ', # 0x93 'Zhu ', # 0x94 'Dang ', # 0x95 'Hong ', # 0x96 'Zong ', # 0x97 'Guan ', # 0x98 'Zhou ', # 0x99 'Ding ', # 0x9a 'Wan ', # 0x9b 'Yi ', # 0x9c 'Bao ', # 0x9d 'Shi ', # 0x9e 'Shi ', # 0x9f 'Chong ', # 0xa0 'Shen ', # 0xa1 'Ke ', # 0xa2 'Xuan ', # 0xa3 'Shi ', # 0xa4 'You ', # 0xa5 'Huan ', # 0xa6 'Yi ', # 0xa7 'Tiao ', # 0xa8 'Shi ', # 0xa9 'Xian ', # 0xaa 'Gong ', # 0xab 'Cheng ', # 0xac 'Qun ', # 0xad 'Gong ', # 0xae 'Xiao ', # 0xaf 'Zai ', # 0xb0 'Zha ', # 0xb1 'Bao ', # 0xb2 'Hai ', # 0xb3 'Yan ', # 0xb4 'Xiao ', # 0xb5 'Jia ', # 0xb6 'Shen ', # 0xb7 'Chen ', # 0xb8 'Rong ', # 0xb9 'Huang ', # 0xba 'Mi ', # 0xbb 'Kou ', # 0xbc 'Kuan ', # 0xbd 'Bin ', # 0xbe 'Su ', # 0xbf 'Cai ', # 0xc0 'Zan ', # 0xc1 'Ji ', # 0xc2 'Yuan ', # 0xc3 'Ji ', # 0xc4 'Yin ', # 0xc5 'Mi ', # 0xc6 'Kou ', # 0xc7 'Qing ', # 0xc8 'Que ', # 0xc9 'Zhen ', # 0xca 'Jian ', # 0xcb 'Fu ', # 0xcc 'Ning ', # 0xcd 'Bing ', # 0xce 'Huan ', # 0xcf 'Mei ', # 0xd0 'Qin ', # 0xd1 'Han ', # 0xd2 'Yu ', # 0xd3 'Shi ', # 0xd4 'Ning ', # 0xd5 'Qin ', # 0xd6 'Ning ', # 0xd7 'Zhi ', # 0xd8 'Yu ', # 0xd9 'Bao ', # 0xda 'Kuan ', # 0xdb 'Ning ', # 0xdc 'Qin ', # 0xdd 'Mo ', # 0xde 'Cha ', # 0xdf 'Ju ', # 0xe0 'Gua ', # 0xe1 'Qin ', # 0xe2 'Hu ', # 0xe3 'Wu ', # 0xe4 'Liao ', # 0xe5 'Shi ', # 0xe6 'Zhu ', # 0xe7 'Zhai ', # 0xe8 'Shen ', # 0xe9 'Wei ', # 0xea 'Xie ', # 0xeb 'Kuan ', # 0xec 'Hui ', # 0xed 'Liao ', # 0xee 'Jun ', # 0xef 'Huan ', # 0xf0 'Yi ', # 0xf1 'Yi ', # 0xf2 'Bao ', # 0xf3 'Qin ', # 0xf4 'Chong ', # 0xf5 'Bao ', # 0xf6 'Feng ', # 0xf7 'Cun ', # 0xf8 'Dui ', # 0xf9 'Si ', # 0xfa 'Xun ', # 0xfb 'Dao ', # 0xfc 'Lu ', # 0xfd 'Dui ', # 0xfe 'Shou ', # 0xff )
indautgrp/frappe
refs/heads/develop
frappe/patches/v4_0/set_website_route_idx.py
75
from __future__ import unicode_literals import frappe def execute(): pass # from frappe.website.doctype.website_template.website_template import \ # get_pages_and_generators, get_template_controller # # frappe.reload_doc("website", "doctype", "website_template") # frappe.reload_doc("website", "doctype", "website_route") # # for app in frappe.get_installed_apps(): # pages, generators = get_pages_and_generators(app) # for g in generators: # doctype = frappe.get_attr(get_template_controller(app, g["path"], g["fname"]) + ".doctype") # module = frappe.db.get_value("DocType", doctype, "module") # frappe.reload_doc(frappe.scrub(module), "doctype", frappe.scrub(doctype)) # # frappe.db.sql("""update `tabBlog Category` set `title`=`name` where ifnull(`title`, '')=''""") # frappe.db.sql("""update `tabWebsite Route` set idx=null""") # for doctype in ["Blog Category", "Blog Post", "Web Page", "Website Group"]: # frappe.db.sql("""update `tab{}` set idx=null""".format(doctype)) # # from frappe.website.doctype.website_template.website_template import rebuild_website_template # rebuild_website_template()
kevinwilde/WildeBot
refs/heads/master
src/mybot/Lib/site-packages/pip/compat/dictconfig.py
921
# This is a copy of the Python logging.config.dictconfig module, # reproduced with permission. It is provided here for backwards # compatibility for Python versions prior to 2.7. # # Copyright 2009-2010 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from __future__ import absolute_import import logging.handlers import re import sys import types from pip._vendor import six # flake8: noqa IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I) def valid_ident(s): m = IDENTIFIER.match(s) if not m: raise ValueError('Not a valid Python identifier: %r' % s) return True # # This function is defined in logging only in recent versions of Python # try: from logging import _checkLevel except ImportError: def _checkLevel(level): if isinstance(level, int): rv = level elif str(level) == level: if level not in logging._levelNames: raise ValueError('Unknown level: %r' % level) rv = logging._levelNames[level] else: raise TypeError('Level not an integer or a ' 'valid string: %r' % level) return rv # The ConvertingXXX classes are wrappers around standard Python containers, # and they serve to convert any suitable values in the container. The # conversion converts base dicts, lists and tuples to their wrapped # equivalents, whereas strings which match a conversion format are converted # appropriately. # # Each wrapper should have a configurator attribute holding the actual # configurator to use for conversion. class ConvertingDict(dict): """A converting dictionary wrapper.""" def __getitem__(self, key): value = dict.__getitem__(self, key) result = self.configurator.convert(value) # If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def get(self, key, default=None): value = dict.get(self, key, default) result = self.configurator.convert(value) # If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def pop(self, key, default=None): value = dict.pop(self, key, default) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result class ConvertingList(list): """A converting list wrapper.""" def __getitem__(self, key): value = list.__getitem__(self, key) result = self.configurator.convert(value) # If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def pop(self, idx=-1): value = list.pop(self, idx) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self return result class ConvertingTuple(tuple): """A converting tuple wrapper.""" def __getitem__(self, key): value = tuple.__getitem__(self, key) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result class BaseConfigurator(object): """ The configurator base class which defines some useful defaults. """ CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$') WORD_PATTERN = re.compile(r'^\s*(\w+)\s*') DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*') INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*') DIGIT_PATTERN = re.compile(r'^\d+$') value_converters = { 'ext' : 'ext_convert', 'cfg' : 'cfg_convert', } # We might want to use a different one, e.g. importlib importer = __import__ def __init__(self, config): self.config = ConvertingDict(config) self.config.configurator = self def resolve(self, s): """ Resolve strings to objects using standard import and attribute syntax. """ name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += '.' + frag try: found = getattr(found, frag) except AttributeError: self.importer(used) found = getattr(found, frag) return found except ImportError: e, tb = sys.exc_info()[1:] v = ValueError('Cannot resolve %r: %s' % (s, e)) v.__cause__, v.__traceback__ = e, tb raise v def ext_convert(self, value): """Default converter for the ext:// protocol.""" return self.resolve(value) def cfg_convert(self, value): """Default converter for the cfg:// protocol.""" rest = value m = self.WORD_PATTERN.match(rest) if m is None: raise ValueError("Unable to convert %r" % value) else: rest = rest[m.end():] d = self.config[m.groups()[0]] # print d, rest while rest: m = self.DOT_PATTERN.match(rest) if m: d = d[m.groups()[0]] else: m = self.INDEX_PATTERN.match(rest) if m: idx = m.groups()[0] if not self.DIGIT_PATTERN.match(idx): d = d[idx] else: try: n = int(idx) # try as number first (most likely) d = d[n] except TypeError: d = d[idx] if m: rest = rest[m.end():] else: raise ValueError('Unable to convert ' '%r at %r' % (value, rest)) # rest should be empty return d def convert(self, value): """ Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. """ if not isinstance(value, ConvertingDict) and isinstance(value, dict): value = ConvertingDict(value) value.configurator = self elif not isinstance(value, ConvertingList) and isinstance(value, list): value = ConvertingList(value) value.configurator = self elif not isinstance(value, ConvertingTuple) and\ isinstance(value, tuple): value = ConvertingTuple(value) value.configurator = self elif isinstance(value, six.string_types): # str for py3k m = self.CONVERT_PATTERN.match(value) if m: d = m.groupdict() prefix = d['prefix'] converter = self.value_converters.get(prefix, None) if converter: suffix = d['suffix'] converter = getattr(self, converter) value = converter(suffix) return value def configure_custom(self, config): """Configure an object with a user-supplied factory.""" c = config.pop('()') if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: c = self.resolve(c) props = config.pop('.', None) # Check for valid identifiers kwargs = dict((k, config[k]) for k in config if valid_ident(k)) result = c(**kwargs) if props: for name, value in props.items(): setattr(result, name, value) return result def as_tuple(self, value): """Utility function which converts lists to tuples.""" if isinstance(value, list): value = tuple(value) return value class DictConfigurator(BaseConfigurator): """ Configure logging using a dictionary-like object to describe the configuration. """ def configure(self): """Do the configuration.""" config = self.config if 'version' not in config: raise ValueError("dictionary doesn't specify a version") if config['version'] != 1: raise ValueError("Unsupported version: %s" % config['version']) incremental = config.pop('incremental', False) EMPTY_DICT = {} logging._acquireLock() try: if incremental: handlers = config.get('handlers', EMPTY_DICT) # incremental handler config only if handler name # ties in to logging._handlers (Python 2.7) if sys.version_info[:2] == (2, 7): for name in handlers: if name not in logging._handlers: raise ValueError('No handler found with ' 'name %r' % name) else: try: handler = logging._handlers[name] handler_config = handlers[name] level = handler_config.get('level', None) if level: handler.setLevel(_checkLevel(level)) except StandardError as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) loggers = config.get('loggers', EMPTY_DICT) for name in loggers: try: self.configure_logger(name, loggers[name], True) except StandardError as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) root = config.get('root', None) if root: try: self.configure_root(root, True) except StandardError as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) else: disable_existing = config.pop('disable_existing_loggers', True) logging._handlers.clear() del logging._handlerList[:] # Do formatters first - they don't refer to anything else formatters = config.get('formatters', EMPTY_DICT) for name in formatters: try: formatters[name] = self.configure_formatter( formatters[name]) except StandardError as e: raise ValueError('Unable to configure ' 'formatter %r: %s' % (name, e)) # Next, do filters - they don't refer to anything else, either filters = config.get('filters', EMPTY_DICT) for name in filters: try: filters[name] = self.configure_filter(filters[name]) except StandardError as e: raise ValueError('Unable to configure ' 'filter %r: %s' % (name, e)) # Next, do handlers - they refer to formatters and filters # As handlers can refer to other handlers, sort the keys # to allow a deterministic order of configuration handlers = config.get('handlers', EMPTY_DICT) for name in sorted(handlers): try: handler = self.configure_handler(handlers[name]) handler.name = name handlers[name] = handler except StandardError as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) # Next, do loggers - they refer to handlers and filters # we don't want to lose the existing loggers, # since other threads may have pointers to them. # existing is set to contain all existing loggers, # and as we go through the new configuration we # remove any which are configured. At the end, # what's left in existing is the set of loggers # which were in the previous configuration but # which are not in the new configuration. root = logging.root existing = list(root.manager.loggerDict) # The list needs to be sorted so that we can # avoid disabling child loggers of explicitly # named loggers. With a sorted list it is easier # to find the child loggers. existing.sort() # We'll keep the list of existing loggers # which are children of named loggers here... child_loggers = [] # now set up the new ones... loggers = config.get('loggers', EMPTY_DICT) for name in loggers: if name in existing: i = existing.index(name) prefixed = name + "." pflen = len(prefixed) num_existing = len(existing) i = i + 1 # look at the entry after name while (i < num_existing) and\ (existing[i][:pflen] == prefixed): child_loggers.append(existing[i]) i = i + 1 existing.remove(name) try: self.configure_logger(name, loggers[name]) except StandardError as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) # Disable any old loggers. There's no point deleting # them as other threads may continue to hold references # and by disabling them, you stop them doing any logging. # However, don't disable children of named loggers, as that's # probably not what was intended by the user. for log in existing: logger = root.manager.loggerDict[log] if log in child_loggers: logger.level = logging.NOTSET logger.handlers = [] logger.propagate = True elif disable_existing: logger.disabled = True # And finally, do the root logger root = config.get('root', None) if root: try: self.configure_root(root) except StandardError as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) finally: logging._releaseLock() def configure_formatter(self, config): """Configure a formatter from a dictionary.""" if '()' in config: factory = config['()'] # for use in exception handler try: result = self.configure_custom(config) except TypeError as te: if "'format'" not in str(te): raise # Name of parameter changed from fmt to format. # Retry with old name. # This is so that code can be used with older Python versions #(e.g. by Django) config['fmt'] = config.pop('format') config['()'] = factory result = self.configure_custom(config) else: fmt = config.get('format', None) dfmt = config.get('datefmt', None) result = logging.Formatter(fmt, dfmt) return result def configure_filter(self, config): """Configure a filter from a dictionary.""" if '()' in config: result = self.configure_custom(config) else: name = config.get('name', '') result = logging.Filter(name) return result def add_filters(self, filterer, filters): """Add filters to a filterer from a list of names.""" for f in filters: try: filterer.addFilter(self.config['filters'][f]) except StandardError as e: raise ValueError('Unable to add filter %r: %s' % (f, e)) def configure_handler(self, config): """Configure a handler from a dictionary.""" formatter = config.pop('formatter', None) if formatter: try: formatter = self.config['formatters'][formatter] except StandardError as e: raise ValueError('Unable to set formatter ' '%r: %s' % (formatter, e)) level = config.pop('level', None) filters = config.pop('filters', None) if '()' in config: c = config.pop('()') if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: c = self.resolve(c) factory = c else: klass = self.resolve(config.pop('class')) # Special case for handler which refers to another handler if issubclass(klass, logging.handlers.MemoryHandler) and\ 'target' in config: try: config['target'] = self.config['handlers'][config['target']] except StandardError as e: raise ValueError('Unable to set target handler ' '%r: %s' % (config['target'], e)) elif issubclass(klass, logging.handlers.SMTPHandler) and\ 'mailhost' in config: config['mailhost'] = self.as_tuple(config['mailhost']) elif issubclass(klass, logging.handlers.SysLogHandler) and\ 'address' in config: config['address'] = self.as_tuple(config['address']) factory = klass kwargs = dict((k, config[k]) for k in config if valid_ident(k)) try: result = factory(**kwargs) except TypeError as te: if "'stream'" not in str(te): raise # The argument name changed from strm to stream # Retry with old name. # This is so that code can be used with older Python versions #(e.g. by Django) kwargs['strm'] = kwargs.pop('stream') result = factory(**kwargs) if formatter: result.setFormatter(formatter) if level is not None: result.setLevel(_checkLevel(level)) if filters: self.add_filters(result, filters) return result def add_handlers(self, logger, handlers): """Add handlers to a logger from a list of names.""" for h in handlers: try: logger.addHandler(self.config['handlers'][h]) except StandardError as e: raise ValueError('Unable to add handler %r: %s' % (h, e)) def common_logger_config(self, logger, config, incremental=False): """ Perform configuration which is common to root and non-root loggers. """ level = config.get('level', None) if level is not None: logger.setLevel(_checkLevel(level)) if not incremental: # Remove any existing handlers for h in logger.handlers[:]: logger.removeHandler(h) handlers = config.get('handlers', None) if handlers: self.add_handlers(logger, handlers) filters = config.get('filters', None) if filters: self.add_filters(logger, filters) def configure_logger(self, name, config, incremental=False): """Configure a non-root logger from a dictionary.""" logger = logging.getLogger(name) self.common_logger_config(logger, config, incremental) propagate = config.get('propagate', None) if propagate is not None: logger.propagate = propagate def configure_root(self, config, incremental=False): """Configure a root logger from a dictionary.""" root = logging.getLogger() self.common_logger_config(root, config, incremental) dictConfigClass = DictConfigurator def dictConfig(config): """Configure logging using a dictionary.""" dictConfigClass(config).configure()
hengyicai/OnlineAggregationUCAS
refs/heads/master
python/pyspark/traceback_utils.py
160
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import namedtuple import os import traceback CallSite = namedtuple("CallSite", "function file linenum") def first_spark_call(): """ Return a CallSite representing the first Spark call in the current call stack. """ tb = traceback.extract_stack() if len(tb) == 0: return None file, line, module, what = tb[len(tb) - 1] sparkpath = os.path.dirname(file) first_spark_frame = len(tb) - 1 for i in range(0, len(tb)): file, line, fun, what = tb[i] if file.startswith(sparkpath): first_spark_frame = i break if first_spark_frame == 0: file, line, fun, what = tb[0] return CallSite(function=fun, file=file, linenum=line) sfile, sline, sfun, swhat = tb[first_spark_frame] ufile, uline, ufun, uwhat = tb[first_spark_frame - 1] return CallSite(function=sfun, file=ufile, linenum=uline) class SCCallSiteSync(object): """ Helper for setting the spark context call site. Example usage: from pyspark.context import SCCallSiteSync with SCCallSiteSync(<relevant SparkContext>) as css: <a Spark call> """ _spark_stack_depth = 0 def __init__(self, sc): call_site = first_spark_call() if call_site is not None: self._call_site = "%s at %s:%s" % ( call_site.function, call_site.file, call_site.linenum) else: self._call_site = "Error! Could not extract traceback info" self._context = sc def __enter__(self): if SCCallSiteSync._spark_stack_depth == 0: self._context._jsc.setCallSite(self._call_site) SCCallSiteSync._spark_stack_depth += 1 def __exit__(self, type, value, tb): SCCallSiteSync._spark_stack_depth -= 1 if SCCallSiteSync._spark_stack_depth == 0: self._context._jsc.setCallSite(None)
JonatanAntoni/CMSIS_5
refs/heads/develop
CMSIS/DSP/PythonWrapper/config.py
3
CMSISDSP = 1 ROOT=".." config = CMSISDSP if config == CMSISDSP: extensionName = 'cmsisdsp' setupName = 'CMSISDSP' setupDescription = 'CMSIS-DSP Python API' cflags="-DCMSISDSP"
apache/allura
refs/heads/master
ForgeShortUrl/forgeshorturl/tests/__init__.py
409
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License.
sogelink/ansible
refs/heads/devel
lib/ansible/plugins/callback/__init__.py
16
# (c) 2012-2014, Michael DeHaan <michael.dehaan@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/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import difflib import json import sys import warnings from copy import deepcopy from ansible import constants as C from ansible.plugins import AnsiblePlugin from ansible.module_utils._text import to_text from ansible.utils.color import stringc from ansible.vars.manager import strip_internal_keys try: from __main__ import display as global_display except ImportError: from ansible.utils.display import Display global_display = Display() try: from __main__ import cli except ImportError: # using API w/o cli cli = False __all__ = ["CallbackBase"] class CallbackBase(AnsiblePlugin): ''' This is a base ansible callback class that does nothing. New callbacks should use this class as a base and override any callback methods they wish to execute custom actions. ''' def __init__(self, display=None, options=None): if display: self._display = display else: self._display = global_display if cli: self._options = cli.options else: self._options = None if self._display.verbosity >= 4: name = getattr(self, 'CALLBACK_NAME', 'unnamed') ctype = getattr(self, 'CALLBACK_TYPE', 'old') version = getattr(self, 'CALLBACK_VERSION', '1.0') self._display.vvvv('Loading callback plugin %s of type %s, v%s from %s' % (name, ctype, version, __file__)) self.disabled = False self._plugin_options = {} if options is not None: self.set_options(options) ''' helper for callbacks, so they don't all have to include deepcopy ''' _copy_result = deepcopy def set_options(self, options): self._plugin_options = options def _dump_results(self, result, indent=None, sort_keys=True, keep_invocation=False): if result.get('_ansible_no_log', False): return json.dumps(dict(censored="the output has been hidden due to the fact that 'no_log: true' was specified for this result")) if not indent and (result.get('_ansible_verbose_always') or self._display.verbosity > 2): indent = 4 # All result keys stating with _ansible_ are internal, so remove them from the result before we output anything. abridged_result = strip_internal_keys(result) # remove invocation unless specifically wanting it if not keep_invocation and self._display.verbosity < 3 and 'invocation' in result: del abridged_result['invocation'] # remove diff information from screen output if self._display.verbosity < 3 and 'diff' in result: del abridged_result['diff'] # remove exception from screen output if 'exception' in abridged_result: del abridged_result['exception'] return json.dumps(abridged_result, indent=indent, ensure_ascii=False, sort_keys=sort_keys) def _handle_warnings(self, res): ''' display warnings, if enabled and any exist in the result ''' if C.COMMAND_WARNINGS: if 'warnings' in res and res['warnings']: for warning in res['warnings']: self._display.warning(warning) del res['warnings'] if 'deprecations' in res and res['deprecations']: for warning in res['deprecations']: self._display.deprecated(**warning) del res['deprecations'] def _handle_exception(self, result): if 'exception' in result: msg = "An exception occurred during task execution. " if self._display.verbosity < 3: # extract just the actual error message from the exception text error = result['exception'].strip().split('\n')[-1] msg += "To see the full traceback, use -vvv. The error was: %s" % error else: msg = "The full traceback is:\n" + result['exception'] del result['exception'] self._display.display(msg, color=C.COLOR_ERROR) def _get_diff(self, difflist): if not isinstance(difflist, list): difflist = [difflist] ret = [] for diff in difflist: try: with warnings.catch_warnings(): warnings.simplefilter('ignore') if 'dst_binary' in diff: ret.append("diff skipped: destination file appears to be binary\n") if 'src_binary' in diff: ret.append("diff skipped: source file appears to be binary\n") if 'dst_larger' in diff: ret.append("diff skipped: destination file size is greater than %d\n" % diff['dst_larger']) if 'src_larger' in diff: ret.append("diff skipped: source file size is greater than %d\n" % diff['src_larger']) if 'before' in diff and 'after' in diff: # format complex structures into 'files' for x in ['before', 'after']: if isinstance(diff[x], dict): diff[x] = json.dumps(diff[x], sort_keys=True, indent=4, separators=(',', ': ')) + '\n' if 'before_header' in diff: before_header = "before: %s" % diff['before_header'] else: before_header = 'before' if 'after_header' in diff: after_header = "after: %s" % diff['after_header'] else: after_header = 'after' before_lines = to_text(diff['before']).splitlines(True) after_lines = to_text(diff['after']).splitlines(True) if before_lines and not before_lines[-1].endswith('\n'): before_lines[-1] += '\n\\ No newline at end of file\n' if after_lines and not after_lines[-1].endswith('\n'): after_lines[-1] += '\n\\ No newline at end of file\n' differ = difflib.unified_diff(before_lines, after_lines, fromfile=before_header, tofile=after_header, fromfiledate='', tofiledate='', n=C.DIFF_CONTEXT) difflines = list(differ) if len(difflines) >= 3 and sys.version_info[:2] == (2, 6): # difflib in Python 2.6 adds trailing spaces after # filenames in the -- before/++ after headers. difflines[0] = difflines[0].replace(' \n', '\n') difflines[1] = difflines[1].replace(' \n', '\n') # it also treats empty files differently difflines[2] = difflines[2].replace('-1,0', '-0,0').replace('+1,0', '+0,0') has_diff = False for line in difflines: has_diff = True if line.startswith('+'): line = stringc(line, C.COLOR_DIFF_ADD) elif line.startswith('-'): line = stringc(line, C.COLOR_DIFF_REMOVE) elif line.startswith('@@'): line = stringc(line, C.COLOR_DIFF_LINES) ret.append(line) if has_diff: ret.append('\n') if 'prepared' in diff: ret.append(to_text(diff['prepared'])) except UnicodeDecodeError: ret.append(">> the files are different, but the diff library cannot compare unicode strings\n\n") return u''.join(ret) def _get_item(self, result): if result.get('_ansible_no_log', False): item = "(censored due to no_log)" elif result.get('_ansible_item_label', False): item = result.get('_ansible_item_label') else: item = result.get('item', None) return item def _process_items(self, result): # just remove them as now they get handled by individual callbacks del result._result['results'] def _clean_results(self, result, task_name): if task_name in ['debug']: for remove_key in ('changed', 'invocation', 'failed', 'skipped'): if remove_key in result: del result[remove_key] def set_play_context(self, play_context): pass def on_any(self, *args, **kwargs): pass def runner_on_failed(self, host, res, ignore_errors=False): pass def runner_on_ok(self, host, res): pass def runner_on_skipped(self, host, item=None): pass def runner_on_unreachable(self, host, res): pass def runner_on_no_hosts(self): pass def runner_on_async_poll(self, host, res, jid, clock): pass def runner_on_async_ok(self, host, res, jid): pass def runner_on_async_failed(self, host, res, jid): pass def playbook_on_start(self): pass def playbook_on_notify(self, host, handler): pass def playbook_on_no_hosts_matched(self): pass def playbook_on_no_hosts_remaining(self): pass def playbook_on_task_start(self, name, is_conditional): pass def playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None): pass def playbook_on_setup(self): pass def playbook_on_import_for_host(self, host, imported_file): pass def playbook_on_not_import_for_host(self, host, missing_file): pass def playbook_on_play_start(self, name): pass def playbook_on_stats(self, stats): pass def on_file_diff(self, host, diff): pass # V2 METHODS, by default they call v1 counterparts if possible def v2_on_any(self, *args, **kwargs): self.on_any(args, kwargs) def v2_runner_on_failed(self, result, ignore_errors=False): host = result._host.get_name() self.runner_on_failed(host, result._result, ignore_errors) def v2_runner_on_ok(self, result): host = result._host.get_name() self.runner_on_ok(host, result._result) def v2_runner_on_skipped(self, result): if C.DISPLAY_SKIPPED_HOSTS: host = result._host.get_name() self.runner_on_skipped(host, self._get_item(getattr(result._result, 'results', {}))) def v2_runner_on_unreachable(self, result): host = result._host.get_name() self.runner_on_unreachable(host, result._result) def v2_runner_on_no_hosts(self, task): self.runner_on_no_hosts() def v2_runner_on_async_poll(self, result): host = result._host.get_name() jid = result._result.get('ansible_job_id') # FIXME, get real clock clock = 0 self.runner_on_async_poll(host, result._result, jid, clock) def v2_runner_on_async_ok(self, result): host = result._host.get_name() jid = result._result.get('ansible_job_id') self.runner_on_async_ok(host, result._result, jid) def v2_runner_on_async_failed(self, result): host = result._host.get_name() jid = result._result.get('ansible_job_id') self.runner_on_async_failed(host, result._result, jid) def v2_runner_on_file_diff(self, result, diff): pass # no v1 correspondence def v2_playbook_on_start(self, playbook): self.playbook_on_start() def v2_playbook_on_notify(self, result, handler): host = result._host.get_name() self.playbook_on_notify(host, handler) def v2_playbook_on_no_hosts_matched(self): self.playbook_on_no_hosts_matched() def v2_playbook_on_no_hosts_remaining(self): self.playbook_on_no_hosts_remaining() def v2_playbook_on_task_start(self, task, is_conditional): self.playbook_on_task_start(task.name, is_conditional) def v2_playbook_on_cleanup_task_start(self, task): pass # no v1 correspondence def v2_playbook_on_handler_task_start(self, task): pass # no v1 correspondence def v2_playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None): self.playbook_on_vars_prompt(varname, private, prompt, encrypt, confirm, salt_size, salt, default) def v2_playbook_on_setup(self): self.playbook_on_setup() def v2_playbook_on_import_for_host(self, result, imported_file): host = result._host.get_name() self.playbook_on_import_for_host(host, imported_file) def v2_playbook_on_not_import_for_host(self, result, missing_file): host = result._host.get_name() self.playbook_on_not_import_for_host(host, missing_file) def v2_playbook_on_play_start(self, play): self.playbook_on_play_start(play.name) def v2_playbook_on_stats(self, stats): self.playbook_on_stats(stats) def v2_on_file_diff(self, result): if 'diff' in result._result: host = result._host.get_name() self.on_file_diff(host, result._result['diff']) def v2_playbook_on_include(self, included_file): pass # no v1 correspondence def v2_runner_item_on_ok(self, result): pass def v2_runner_item_on_failed(self, result): pass def v2_runner_item_on_skipped(self, result): pass def v2_runner_retry(self, result): pass
jeromewu/bitcoin-abe-opennet
refs/heads/master
Abe/Chain/LtcScryptChain.py
28
# Copyright(C) 2014 by Abe developers. # 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/agpl.html>. from . import BaseChain class LtcScryptChain(BaseChain): """ A blockchain using Litecoin's scrypt algorithm to hash block headers. """ def block_header_hash(chain, header): import ltc_scrypt return ltc_scrypt.getPoWHash(header)
seanchen/taiga-back
refs/heads/master
tests/integration/test_searches.py
7
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014 Anler Hernández <hello@anler.me> # 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 pytest from django.core.urlresolvers import reverse from .. import factories as f from taiga.permissions.permissions import MEMBERS_PERMISSIONS from tests.utils import disconnect_signals, reconnect_signals pytestmark = pytest.mark.django_db def setup_module(module): disconnect_signals() def teardown_module(module): reconnect_signals() @pytest.fixture def searches_initial_data(): m = type("InitialData", (object,), {})() m.project1 = f.ProjectFactory.create() m.project2 = f.ProjectFactory.create() m.member1 = f.MembershipFactory(project=m.project1, role__project=m.project1, role__permissions=list(map(lambda x: x[0], MEMBERS_PERMISSIONS))) m.member2 = f.MembershipFactory(project=m.project1, role__project=m.project1, role__permissions=list(map(lambda x: x[0], MEMBERS_PERMISSIONS))) f.RoleFactory(project=m.project2) m.points1 = f.PointsFactory(project=m.project1, value=None) m.points2 = f.PointsFactory(project=m.project2, value=None) m.role_points1 = f.RolePointsFactory.create(role=m.project1.roles.all()[0], points=m.points1, user_story__project=m.project1) m.role_points2 = f.RolePointsFactory.create(role=m.project1.roles.all()[0], points=m.points1, user_story__project=m.project1, user_story__description="Back to the future") m.role_points3 = f.RolePointsFactory.create(role=m.project2.roles.all()[0], points=m.points2, user_story__project=m.project2) m.us1 = m.role_points1.user_story m.us2 = m.role_points2.user_story m.us3 = m.role_points3.user_story m.tsk1 = f.TaskFactory.create(project=m.project2) m.tsk2 = f.TaskFactory.create(project=m.project1) m.tsk3 = f.TaskFactory.create(project=m.project1, subject="Back to the future") m.iss1 = f.IssueFactory.create(project=m.project1, subject="Backend and Frontend") m.iss2 = f.IssueFactory.create(project=m.project2) m.iss3 = f.IssueFactory.create(project=m.project1) m.wiki1 = f.WikiPageFactory.create(project=m.project1) m.wiki2 = f.WikiPageFactory.create(project=m.project1, content="Frontend, future") m.wiki3 = f.WikiPageFactory.create(project=m.project2) return m def test_search_all_objects_in_my_project(client, searches_initial_data): data = searches_initial_data client.login(data.member1.user) response = client.get(reverse("search-list"), {"project": data.project1.id}) assert response.status_code == 200 assert response.data["count"] == 8 assert len(response.data["userstories"]) == 2 assert len(response.data["tasks"]) == 2 assert len(response.data["issues"]) == 2 assert len(response.data["wikipages"]) == 2 def test_search_all_objects_in_project_is_not_mine(client, searches_initial_data): data = searches_initial_data client.login(data.member1.user) response = client.get(reverse("search-list"), {"project": data.project2.id}) assert response.status_code == 200 assert response.data["count"] == 0 def test_search_text_query_in_my_project(client, searches_initial_data): data = searches_initial_data client.login(data.member1.user) response = client.get(reverse("search-list"), {"project": data.project1.id, "text": "future"}) assert response.status_code == 200 assert response.data["count"] == 3 assert len(response.data["userstories"]) == 1 assert len(response.data["tasks"]) == 1 assert len(response.data["issues"]) == 0 assert len(response.data["wikipages"]) == 1 response = client.get(reverse("search-list"), {"project": data.project1.id, "text": "back"}) assert response.status_code == 200 assert response.data["count"] == 2 assert len(response.data["userstories"]) == 1 assert len(response.data["tasks"]) == 1 assert len(response.data["issues"]) == 0 assert len(response.data["wikipages"]) == 0 def test_search_text_query_with_an_invalid_project_id(client, searches_initial_data): data = searches_initial_data client.login(data.member1.user) response = client.get(reverse("search-list"), {"project": "new", "text": "future"}) assert response.status_code == 404
KevinMidboe/statusHandler
refs/heads/master
flask/lib/python3.4/site-packages/setuptools/command/bdist_rpm.py
1049
import distutils.command.bdist_rpm as orig class bdist_rpm(orig.bdist_rpm): """ Override the default bdist_rpm behavior to do the following: 1. Run egg_info to ensure the name and version are properly calculated. 2. Always run 'install' using --single-version-externally-managed to disable eggs in RPM distributions. 3. Replace dash with underscore in the version numbers for better RPM compatibility. """ def run(self): # ensure distro name is up-to-date self.run_command('egg_info') orig.bdist_rpm.run(self) def _make_spec_file(self): version = self.distribution.get_version() rpmversion = version.replace('-', '_') spec = orig.bdist_rpm._make_spec_file(self) line23 = '%define version ' + version line24 = '%define version ' + rpmversion spec = [ line.replace( "Source0: %{name}-%{version}.tar", "Source0: %{name}-%{unmangled_version}.tar" ).replace( "setup.py install ", "setup.py install --single-version-externally-managed " ).replace( "%setup", "%setup -n %{name}-%{unmangled_version}" ).replace(line23, line24) for line in spec ] insert_loc = spec.index(line24) + 1 unmangled_version = "%define unmangled_version " + version spec.insert(insert_loc, unmangled_version) return spec
Zuckonit/retry
refs/heads/master
setup.py
1
from setuptools import setup, find_packages setup( name="retry", version="0.0.1", packages=find_packages(), author="Mocker", author_email="Zuckerwooo@gmail.com", )
gltn/stdm
refs/heads/master
stdm/third_party/FontTools/fontTools/ttLib/tables/TupleVariation.py
1
from fontTools.misc.py23 import * from fontTools.misc.fixedTools import ( fixedToFloat as fi2fl, floatToFixed as fl2fi, floatToFixedToStr as fl2str, strToFixedToFloat as str2fl, otRound, ) from fontTools.misc.textTools import safeEval import array import io import logging import struct import sys # https://www.microsoft.com/typography/otspec/otvarcommonformats.htm EMBEDDED_PEAK_TUPLE = 0x8000 INTERMEDIATE_REGION = 0x4000 PRIVATE_POINT_NUMBERS = 0x2000 DELTAS_ARE_ZERO = 0x80 DELTAS_ARE_WORDS = 0x40 DELTA_RUN_COUNT_MASK = 0x3f POINTS_ARE_WORDS = 0x80 POINT_RUN_COUNT_MASK = 0x7f TUPLES_SHARE_POINT_NUMBERS = 0x8000 TUPLE_COUNT_MASK = 0x0fff TUPLE_INDEX_MASK = 0x0fff log = logging.getLogger(__name__) class TupleVariation(object): def __init__(self, axes, coordinates): self.axes = axes.copy() self.coordinates = coordinates[:] def __repr__(self): axes = ",".join(sorted(["%s=%s" % (name, value) for (name, value) in self.axes.items()])) return "<TupleVariation %s %s>" % (axes, self.coordinates) def __eq__(self, other): return self.coordinates == other.coordinates and self.axes == other.axes def getUsedPoints(self): result = set() for i, point in enumerate(self.coordinates): if point is not None: result.add(i) return result def hasImpact(self): """Returns True if this TupleVariation has any visible impact. If the result is False, the TupleVariation can be omitted from the font without making any visible difference. """ return any(c is not None for c in self.coordinates) def toXML(self, writer, axisTags): writer.begintag("tuple") writer.newline() for axis in axisTags: value = self.axes.get(axis) if value is not None: minValue, value, maxValue = value defaultMinValue = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0 defaultMaxValue = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7 if minValue == defaultMinValue and maxValue == defaultMaxValue: writer.simpletag("coord", axis=axis, value=fl2str(value, 14)) else: attrs = [ ("axis", axis), ("min", fl2str(minValue, 14)), ("value", fl2str(value, 14)), ("max", fl2str(maxValue, 14)), ] writer.simpletag("coord", attrs) writer.newline() wrote_any_deltas = False for i, delta in enumerate(self.coordinates): if type(delta) == tuple and len(delta) == 2: writer.simpletag("delta", pt=i, x=delta[0], y=delta[1]) writer.newline() wrote_any_deltas = True elif type(delta) == int: writer.simpletag("delta", cvt=i, value=delta) writer.newline() wrote_any_deltas = True elif delta is not None: log.error("bad delta format") writer.comment("bad delta #%d" % i) writer.newline() wrote_any_deltas = True if not wrote_any_deltas: writer.comment("no deltas") writer.newline() writer.endtag("tuple") writer.newline() def fromXML(self, name, attrs, _content): if name == "coord": axis = attrs["axis"] value = str2fl(attrs["value"], 14) defaultMinValue = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0 defaultMaxValue = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7 minValue = str2fl(attrs.get("min", defaultMinValue), 14) maxValue = str2fl(attrs.get("max", defaultMaxValue), 14) self.axes[axis] = (minValue, value, maxValue) elif name == "delta": if "pt" in attrs: point = safeEval(attrs["pt"]) x = safeEval(attrs["x"]) y = safeEval(attrs["y"]) self.coordinates[point] = (x, y) elif "cvt" in attrs: cvt = safeEval(attrs["cvt"]) value = safeEval(attrs["value"]) self.coordinates[cvt] = value else: log.warning("bad delta format: %s" % ", ".join(sorted(attrs.keys()))) def compile(self, axisTags, sharedCoordIndices, sharedPoints): tupleData = [] assert all(tag in axisTags for tag in self.axes.keys()), ("Unknown axis tag found.", self.axes.keys(), axisTags) coord = self.compileCoord(axisTags) if coord in sharedCoordIndices: flags = sharedCoordIndices[coord] else: flags = EMBEDDED_PEAK_TUPLE tupleData.append(coord) intermediateCoord = self.compileIntermediateCoord(axisTags) if intermediateCoord is not None: flags |= INTERMEDIATE_REGION tupleData.append(intermediateCoord) points = self.getUsedPoints() if sharedPoints == points: # Only use the shared points if they are identical to the actually used points auxData = self.compileDeltas(sharedPoints) usesSharedPoints = True else: flags |= PRIVATE_POINT_NUMBERS numPointsInGlyph = len(self.coordinates) auxData = self.compilePoints(points, numPointsInGlyph) + self.compileDeltas(points) usesSharedPoints = False tupleData = struct.pack('>HH', len(auxData), flags) + bytesjoin(tupleData) return (tupleData, auxData, usesSharedPoints) def compileCoord(self, axisTags): result = [] for axis in axisTags: _minValue, value, _maxValue = self.axes.get(axis, (0.0, 0.0, 0.0)) result.append(struct.pack(">h", fl2fi(value, 14))) return bytesjoin(result) def compileIntermediateCoord(self, axisTags): needed = False for axis in axisTags: minValue, value, maxValue = self.axes.get(axis, (0.0, 0.0, 0.0)) defaultMinValue = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0 defaultMaxValue = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7 if (minValue != defaultMinValue) or (maxValue != defaultMaxValue): needed = True break if not needed: return None minCoords = [] maxCoords = [] for axis in axisTags: minValue, value, maxValue = self.axes.get(axis, (0.0, 0.0, 0.0)) minCoords.append(struct.pack(">h", fl2fi(minValue, 14))) maxCoords.append(struct.pack(">h", fl2fi(maxValue, 14))) return bytesjoin(minCoords + maxCoords) @staticmethod def decompileCoord_(axisTags, data, offset): coord = {} pos = offset for axis in axisTags: coord[axis] = fi2fl(struct.unpack(">h", data[pos:pos+2])[0], 14) pos += 2 return coord, pos @staticmethod def compilePoints(points, numPointsInGlyph): # If the set consists of all points in the glyph, it gets encoded with # a special encoding: a single zero byte. if len(points) == numPointsInGlyph: return b"\0" # In the 'gvar' table, the packing of point numbers is a little surprising. # It consists of multiple runs, each being a delta-encoded list of integers. # For example, the point set {17, 18, 19, 20, 21, 22, 23} gets encoded as # [6, 17, 1, 1, 1, 1, 1, 1]. The first value (6) is the run length minus 1. # There are two types of runs, with values being either 8 or 16 bit unsigned # integers. points = list(points) points.sort() numPoints = len(points) # The binary representation starts with the total number of points in the set, # encoded into one or two bytes depending on the value. if numPoints < 0x80: result = [bytechr(numPoints)] else: result = [bytechr((numPoints >> 8) | 0x80) + bytechr(numPoints & 0xff)] MAX_RUN_LENGTH = 127 pos = 0 lastValue = 0 while pos < numPoints: run = io.BytesIO() runLength = 0 useByteEncoding = None while pos < numPoints and runLength <= MAX_RUN_LENGTH: curValue = points[pos] delta = curValue - lastValue if useByteEncoding is None: useByteEncoding = 0 <= delta <= 0xff if useByteEncoding and (delta > 0xff or delta < 0): # we need to start a new run (which will not use byte encoding) break # TODO This never switches back to a byte-encoding from a short-encoding. # That's suboptimal. if useByteEncoding: run.write(bytechr(delta)) else: run.write(bytechr(delta >> 8)) run.write(bytechr(delta & 0xff)) lastValue = curValue pos += 1 runLength += 1 if useByteEncoding: runHeader = bytechr(runLength - 1) else: runHeader = bytechr((runLength - 1) | POINTS_ARE_WORDS) result.append(runHeader) result.append(run.getvalue()) return bytesjoin(result) @staticmethod def decompilePoints_(numPoints, data, offset, tableTag): """(numPoints, data, offset, tableTag) --> ([point1, point2, ...], newOffset)""" assert tableTag in ('cvar', 'gvar') pos = offset numPointsInData = byteord(data[pos]) pos += 1 if (numPointsInData & POINTS_ARE_WORDS) != 0: numPointsInData = (numPointsInData & POINT_RUN_COUNT_MASK) << 8 | byteord(data[pos]) pos += 1 if numPointsInData == 0: return (range(numPoints), pos) result = [] while len(result) < numPointsInData: runHeader = byteord(data[pos]) pos += 1 numPointsInRun = (runHeader & POINT_RUN_COUNT_MASK) + 1 point = 0 if (runHeader & POINTS_ARE_WORDS) != 0: points = array.array("H") pointsSize = numPointsInRun * 2 else: points = array.array("B") pointsSize = numPointsInRun points.frombytes(data[pos:pos+pointsSize]) if sys.byteorder != "big": points.byteswap() assert len(points) == numPointsInRun pos += pointsSize result.extend(points) # Convert relative to absolute absolute = [] current = 0 for delta in result: current += delta absolute.append(current) result = absolute del absolute badPoints = {str(p) for p in result if p < 0 or p >= numPoints} if badPoints: log.warning("point %s out of range in '%s' table" % (",".join(sorted(badPoints)), tableTag)) return (result, pos) def compileDeltas(self, points): deltaX = [] deltaY = [] for p in sorted(list(points)): c = self.coordinates[p] if type(c) is tuple and len(c) == 2: deltaX.append(c[0]) deltaY.append(c[1]) elif type(c) is int: deltaX.append(c) elif c is not None: raise TypeError("invalid type of delta: %s" % type(c)) return self.compileDeltaValues_(deltaX) + self.compileDeltaValues_(deltaY) @staticmethod def compileDeltaValues_(deltas): """[value1, value2, value3, ...] --> bytestring Emits a sequence of runs. Each run starts with a byte-sized header whose 6 least significant bits (header & 0x3F) indicate how many values are encoded in this run. The stored length is the actual length minus one; run lengths are thus in the range [1..64]. If the header byte has its most significant bit (0x80) set, all values in this run are zero, and no data follows. Otherwise, the header byte is followed by ((header & 0x3F) + 1) signed values. If (header & 0x40) is clear, the delta values are stored as signed bytes; if (header & 0x40) is set, the delta values are signed 16-bit integers. """ # Explaining the format because the 'gvar' spec is hard to understand. stream = io.BytesIO() pos = 0 while pos < len(deltas): value = deltas[pos] if value == 0: pos = TupleVariation.encodeDeltaRunAsZeroes_(deltas, pos, stream) elif value >= -128 and value <= 127: pos = TupleVariation.encodeDeltaRunAsBytes_(deltas, pos, stream) else: pos = TupleVariation.encodeDeltaRunAsWords_(deltas, pos, stream) return stream.getvalue() @staticmethod def encodeDeltaRunAsZeroes_(deltas, offset, stream): runLength = 0 pos = offset numDeltas = len(deltas) while pos < numDeltas and runLength < 64 and deltas[pos] == 0: pos += 1 runLength += 1 assert runLength >= 1 and runLength <= 64 stream.write(bytechr(DELTAS_ARE_ZERO | (runLength - 1))) return pos @staticmethod def encodeDeltaRunAsBytes_(deltas, offset, stream): runLength = 0 pos = offset numDeltas = len(deltas) while pos < numDeltas and runLength < 64: value = deltas[pos] if value < -128 or value > 127: break # Within a byte-encoded run of deltas, a single zero # is best stored literally as 0x00 value. However, # if are two or more zeroes in a sequence, it is # better to start a new run. For example, the sequence # of deltas [15, 15, 0, 15, 15] becomes 6 bytes # (04 0F 0F 00 0F 0F) when storing the zero value # literally, but 7 bytes (01 0F 0F 80 01 0F 0F) # when starting a new run. if value == 0 and pos+1 < numDeltas and deltas[pos+1] == 0: break pos += 1 runLength += 1 assert runLength >= 1 and runLength <= 64 stream.write(bytechr(runLength - 1)) for i in range(offset, pos): stream.write(struct.pack('b', otRound(deltas[i]))) return pos @staticmethod def encodeDeltaRunAsWords_(deltas, offset, stream): runLength = 0 pos = offset numDeltas = len(deltas) while pos < numDeltas and runLength < 64: value = deltas[pos] # Within a word-encoded run of deltas, it is easiest # to start a new run (with a different encoding) # whenever we encounter a zero value. For example, # the sequence [0x6666, 0, 0x7777] needs 7 bytes when # storing the zero literally (42 66 66 00 00 77 77), # and equally 7 bytes when starting a new run # (40 66 66 80 40 77 77). if value == 0: break # Within a word-encoded run of deltas, a single value # in the range (-128..127) should be encoded literally # because it is more compact. For example, the sequence # [0x6666, 2, 0x7777] becomes 7 bytes when storing # the value literally (42 66 66 00 02 77 77), but 8 bytes # when starting a new run (40 66 66 00 02 40 77 77). isByteEncodable = lambda value: value >= -128 and value <= 127 if isByteEncodable(value) and pos+1 < numDeltas and isByteEncodable(deltas[pos+1]): break pos += 1 runLength += 1 assert runLength >= 1 and runLength <= 64 stream.write(bytechr(DELTAS_ARE_WORDS | (runLength - 1))) for i in range(offset, pos): stream.write(struct.pack('>h', otRound(deltas[i]))) return pos @staticmethod def decompileDeltas_(numDeltas, data, offset): """(numDeltas, data, offset) --> ([delta, delta, ...], newOffset)""" result = [] pos = offset while len(result) < numDeltas: runHeader = byteord(data[pos]) pos += 1 numDeltasInRun = (runHeader & DELTA_RUN_COUNT_MASK) + 1 if (runHeader & DELTAS_ARE_ZERO) != 0: result.extend([0] * numDeltasInRun) else: if (runHeader & DELTAS_ARE_WORDS) != 0: deltas = array.array("h") deltasSize = numDeltasInRun * 2 else: deltas = array.array("b") deltasSize = numDeltasInRun deltas.frombytes(data[pos:pos+deltasSize]) if sys.byteorder != "big": deltas.byteswap() assert len(deltas) == numDeltasInRun pos += deltasSize result.extend(deltas) assert len(result) == numDeltas return (result, pos) @staticmethod def getTupleSize_(flags, axisCount): size = 4 if (flags & EMBEDDED_PEAK_TUPLE) != 0: size += axisCount * 2 if (flags & INTERMEDIATE_REGION) != 0: size += axisCount * 4 return size def getCoordWidth(self): """ Return 2 if coordinates are (x, y) as in gvar, 1 if single values as in cvar, or 0 if empty. """ firstDelta = next((c for c in self.coordinates if c is not None), None) if firstDelta is None: return 0 # empty or has no impact if type(firstDelta) in (int, float): return 1 if type(firstDelta) is tuple and len(firstDelta) == 2: return 2 raise TypeError( "invalid type of delta; expected (int or float) number, or " "Tuple[number, number]: %r" % firstDelta ) def scaleDeltas(self, scalar): if scalar == 1.0: return # no change coordWidth = self.getCoordWidth() self.coordinates = [ None if d is None else d * scalar if coordWidth == 1 else (d[0] * scalar, d[1] * scalar) for d in self.coordinates ] def roundDeltas(self): coordWidth = self.getCoordWidth() self.coordinates = [ None if d is None else otRound(d) if coordWidth == 1 else (otRound(d[0]), otRound(d[1])) for d in self.coordinates ] def calcInferredDeltas(self, origCoords, endPts): from fontTools.varLib.iup import iup_delta if self.getCoordWidth() == 1: raise TypeError( "Only 'gvar' TupleVariation can have inferred deltas" ) if None in self.coordinates: if len(self.coordinates) != len(origCoords): raise ValueError( "Expected len(origCoords) == %d; found %d" % (len(self.coordinates), len(origCoords)) ) self.coordinates = iup_delta(self.coordinates, origCoords, endPts) def optimize(self, origCoords, endPts, tolerance=0.5, isComposite=False): from fontTools.varLib.iup import iup_delta_optimize if None in self.coordinates: return # already optimized deltaOpt = iup_delta_optimize( self.coordinates, origCoords, endPts, tolerance=tolerance ) if None in deltaOpt: if isComposite and all(d is None for d in deltaOpt): # Fix for macOS composites # https://github.com/fonttools/fonttools/issues/1381 deltaOpt = [(0, 0)] + [None] * (len(deltaOpt) - 1) # Use "optimized" version only if smaller... varOpt = TupleVariation(self.axes, deltaOpt) # Shouldn't matter that this is different from fvar...? axisTags = sorted(self.axes.keys()) tupleData, auxData, _ = self.compile(axisTags, [], None) unoptimizedLength = len(tupleData) + len(auxData) tupleData, auxData, _ = varOpt.compile(axisTags, [], None) optimizedLength = len(tupleData) + len(auxData) if optimizedLength < unoptimizedLength: self.coordinates = varOpt.coordinates def __iadd__(self, other): if not isinstance(other, TupleVariation): return NotImplemented deltas1 = self.coordinates length = len(deltas1) deltas2 = other.coordinates if len(deltas2) != length: raise ValueError( "cannot sum TupleVariation deltas with different lengths" ) # 'None' values have different meanings in gvar vs cvar TupleVariations: # within the gvar, when deltas are not provided explicitly for some points, # they need to be inferred; whereas for the 'cvar' table, if deltas are not # provided for some CVT values, then no adjustments are made (i.e. None == 0). # Thus, we cannot sum deltas for gvar TupleVariations if they contain # inferred inferred deltas (the latter need to be computed first using # 'calcInferredDeltas' method), but we can treat 'None' values in cvar # deltas as if they are zeros. if self.getCoordWidth() == 2: for i, d2 in zip(range(length), deltas2): d1 = deltas1[i] try: deltas1[i] = (d1[0] + d2[0], d1[1] + d2[1]) except TypeError: raise ValueError( "cannot sum gvar deltas with inferred points" ) else: for i, d2 in zip(range(length), deltas2): d1 = deltas1[i] if d1 is not None and d2 is not None: deltas1[i] = d1 + d2 elif d1 is None and d2 is not None: deltas1[i] = d2 # elif d2 is None do nothing return self def decompileSharedTuples(axisTags, sharedTupleCount, data, offset): result = [] for _ in range(sharedTupleCount): t, offset = TupleVariation.decompileCoord_(axisTags, data, offset) result.append(t) return result def compileSharedTuples(axisTags, variations): coordCount = {} for var in variations: coord = var.compileCoord(axisTags) coordCount[coord] = coordCount.get(coord, 0) + 1 sharedCoords = [(count, coord) for (coord, count) in coordCount.items() if count > 1] sharedCoords.sort(reverse=True) MAX_NUM_SHARED_COORDS = TUPLE_INDEX_MASK + 1 sharedCoords = sharedCoords[:MAX_NUM_SHARED_COORDS] return [c[1] for c in sharedCoords] # Strip off counts. def compileTupleVariationStore(variations, pointCount, axisTags, sharedTupleIndices, useSharedPoints=True): variations = [v for v in variations if v.hasImpact()] if len(variations) == 0: return (0, b"", b"") # Each glyph variation tuples modifies a set of control points. To # indicate which exact points are getting modified, a single tuple # can either refer to a shared set of points, or the tuple can # supply its private point numbers. Because the impact of sharing # can be positive (no need for a private point list) or negative # (need to supply 0,0 deltas for unused points), it is not obvious # how to determine which tuples should take their points from the # shared pool versus have their own. Perhaps we should resort to # brute force, and try all combinations? However, if a glyph has n # variation tuples, we would need to try 2^n combinations (because # each tuple may or may not be part of the shared set). How many # variations tuples do glyphs have? # # Skia.ttf: {3: 1, 5: 11, 6: 41, 7: 62, 8: 387, 13: 1, 14: 3} # JamRegular.ttf: {3: 13, 4: 122, 5: 1, 7: 4, 8: 1, 9: 1, 10: 1} # BuffaloGalRegular.ttf: {1: 16, 2: 13, 4: 2, 5: 4, 6: 19, 7: 1, 8: 3, 9: 8} # (Reading example: In Skia.ttf, 41 glyphs have 6 variation tuples). # # Is this even worth optimizing? If we never use a shared point # list, the private lists will consume 112K for Skia, 5K for # BuffaloGalRegular, and 15K for JamRegular. If we always use a # shared point list, the shared lists will consume 16K for Skia, # 3K for BuffaloGalRegular, and 10K for JamRegular. However, in # the latter case the delta arrays will become larger, but I # haven't yet measured by how much. From gut feeling (which may be # wrong), the optimum is to share some but not all points; # however, then we would need to try all combinations. # # For the time being, we try two variants and then pick the better one: # (a) each tuple supplies its own private set of points; # (b) all tuples refer to a shared set of points, which consists of # "every control point in the glyph that has explicit deltas". usedPoints = set() for v in variations: usedPoints |= v.getUsedPoints() tuples = [] data = [] someTuplesSharePoints = False sharedPointVariation = None # To keep track of a variation that uses shared points for v in variations: privateTuple, privateData, _ = v.compile( axisTags, sharedTupleIndices, sharedPoints=None) sharedTuple, sharedData, usesSharedPoints = v.compile( axisTags, sharedTupleIndices, sharedPoints=usedPoints) if useSharedPoints and (len(sharedTuple) + len(sharedData)) < (len(privateTuple) + len(privateData)): tuples.append(sharedTuple) data.append(sharedData) someTuplesSharePoints |= usesSharedPoints sharedPointVariation = v else: tuples.append(privateTuple) data.append(privateData) if someTuplesSharePoints: # Use the last of the variations that share points for compiling the packed point data data = sharedPointVariation.compilePoints(usedPoints, len(sharedPointVariation.coordinates)) + bytesjoin(data) tupleVariationCount = TUPLES_SHARE_POINT_NUMBERS | len(tuples) else: data = bytesjoin(data) tupleVariationCount = len(tuples) tuples = bytesjoin(tuples) return tupleVariationCount, tuples, data def decompileTupleVariationStore(tableTag, axisTags, tupleVariationCount, pointCount, sharedTuples, data, pos, dataPos): numAxes = len(axisTags) result = [] if (tupleVariationCount & TUPLES_SHARE_POINT_NUMBERS) != 0: sharedPoints, dataPos = TupleVariation.decompilePoints_( pointCount, data, dataPos, tableTag) else: sharedPoints = [] for _ in range(tupleVariationCount & TUPLE_COUNT_MASK): dataSize, flags = struct.unpack(">HH", data[pos:pos+4]) tupleSize = TupleVariation.getTupleSize_(flags, numAxes) tupleData = data[pos : pos + tupleSize] pointDeltaData = data[dataPos : dataPos + dataSize] result.append(decompileTupleVariation_( pointCount, sharedTuples, sharedPoints, tableTag, axisTags, tupleData, pointDeltaData)) pos += tupleSize dataPos += dataSize return result def decompileTupleVariation_(pointCount, sharedTuples, sharedPoints, tableTag, axisTags, data, tupleData): assert tableTag in ("cvar", "gvar"), tableTag flags = struct.unpack(">H", data[2:4])[0] pos = 4 if (flags & EMBEDDED_PEAK_TUPLE) == 0: peak = sharedTuples[flags & TUPLE_INDEX_MASK] else: peak, pos = TupleVariation.decompileCoord_(axisTags, data, pos) if (flags & INTERMEDIATE_REGION) != 0: start, pos = TupleVariation.decompileCoord_(axisTags, data, pos) end, pos = TupleVariation.decompileCoord_(axisTags, data, pos) else: start, end = inferRegion_(peak) axes = {} for axis in axisTags: region = start[axis], peak[axis], end[axis] if region != (0.0, 0.0, 0.0): axes[axis] = region pos = 0 if (flags & PRIVATE_POINT_NUMBERS) != 0: points, pos = TupleVariation.decompilePoints_( pointCount, tupleData, pos, tableTag) else: points = sharedPoints deltas = [None] * pointCount if tableTag == "cvar": deltas_cvt, pos = TupleVariation.decompileDeltas_( len(points), tupleData, pos) for p, delta in zip(points, deltas_cvt): if 0 <= p < pointCount: deltas[p] = delta elif tableTag == "gvar": deltas_x, pos = TupleVariation.decompileDeltas_( len(points), tupleData, pos) deltas_y, pos = TupleVariation.decompileDeltas_( len(points), tupleData, pos) for p, x, y in zip(points, deltas_x, deltas_y): if 0 <= p < pointCount: deltas[p] = (x, y) return TupleVariation(axes, deltas) def inferRegion_(peak): """Infer start and end for a (non-intermediate) region This helper function computes the applicability region for variation tuples whose INTERMEDIATE_REGION flag is not set in the TupleVariationHeader structure. Variation tuples apply only to certain regions of the variation space; outside that region, the tuple has no effect. To make the binary encoding more compact, TupleVariationHeaders can omit the intermediateStartTuple and intermediateEndTuple fields. """ start, end = {}, {} for (axis, value) in peak.items(): start[axis] = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0 end[axis] = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7 return (start, end)
elingg/tensorflow
refs/heads/master
tensorflow/python/training/gradient_descent_test.py
7
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functional test for GradientDescent.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import embedding_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import resources from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import gradient_descent class GradientDescentOptimizerTest(test.TestCase): def testBasic(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.test_session(): var0 = variables.Variable([1.0, 2.0], dtype=dtype) var1 = variables.Variable([3.0, 4.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) sgd_op = gradient_descent.GradientDescentOptimizer(3.0).apply_gradients( zip([grads0, grads1], [var0, var1])) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval()) self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval()) # Run 1 step of sgd sgd_op.run() # Validate updated params self.assertAllCloseAccordingToType([1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval()) self.assertAllCloseAccordingToType([3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval()) def testBasicResourceVariable(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.test_session(): var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) sgd_op = gradient_descent.GradientDescentOptimizer(3.0).apply_gradients( zip([grads0, grads1], [var0, var1])) # TODO(apassos) calling initialize_resources on all resources here # doesn't work because the sessions and graph are reused across unit # tests and this would mean trying to reinitialize variables. Figure out # a long-term solution for this. resources.initialize_resources([var0, var1]).run() # Fetch params to validate initial values self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval()) self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval()) # Run 1 step of sgd sgd_op.run() # Validate updated params self.assertAllCloseAccordingToType([1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval()) self.assertAllCloseAccordingToType([3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval()) def testMinimizeResourceVariable(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.test_session(): var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype) var1 = resource_variable_ops.ResourceVariable([3.0], dtype=dtype) x = constant_op.constant([[4.0], [5.0]], dtype=dtype) pred = math_ops.matmul(var0, x) + var1 loss = pred * pred sgd_op = gradient_descent.GradientDescentOptimizer(1.0).minimize(loss) # TODO(apassos) calling initialize_resources on all resources here # doesn't work because the sessions and graph are reused across unit # tests and this would mean trying to reinitialize variables. Figure out # a long-term solution for this. resources.initialize_resources([var0, var1]).run() # Fetch params to validate initial values self.assertAllCloseAccordingToType([[1.0, 2.0]], var0.eval()) self.assertAllCloseAccordingToType([3.0], var1.eval()) # Run 1 step of sgd sgd_op.run() # Validate updated params np_pred = 1.0 * 4.0 + 2.0 * 5.0 + 3.0 np_grad = 2 * np_pred self.assertAllCloseAccordingToType( [[1.0 - np_grad * 4.0, 2.0 - np_grad * 5.0]], var0.eval()) self.assertAllCloseAccordingToType([3.0 - np_grad], var1.eval()) def testMinimizeSparseResourceVariable(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.test_session(): var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype) var1 = resource_variable_ops.ResourceVariable([3.0], dtype=dtype) x = constant_op.constant([[4.0], [5.0]], dtype=dtype) pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x) pred = math_ops.matmul(var0, x) + var1 loss = pred * pred sgd_op = gradient_descent.GradientDescentOptimizer(1.0).minimize(loss) # TODO(apassos) calling initialize_resources on all resources here # doesn't work because the sessions and graph are reused across unit # tests and this would mean trying to reinitialize variables. Figure out # a long-term solution for this. resources.initialize_resources([var0, var1]).run() # Fetch params to validate initial values self.assertAllCloseAccordingToType([[1.0, 2.0]], var0.eval()) self.assertAllCloseAccordingToType([3.0], var1.eval()) # Run 1 step of sgd sgd_op.run() # Validate updated params np_pred = 1.0 * 4.0 + 2.0 * 5.0 + 3.0 np_grad = 2 * np_pred self.assertAllCloseAccordingToType( [[1.0 - np_grad * 4.0, 2.0 - np_grad * 5.0]], var0.eval()) self.assertAllCloseAccordingToType([3.0 - np_grad], var1.eval()) def testTensorLearningRate(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.test_session(): var0 = variables.Variable([1.0, 2.0], dtype=dtype) var1 = variables.Variable([3.0, 4.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) lrate = constant_op.constant(3.0) sgd_op = gradient_descent.GradientDescentOptimizer( lrate).apply_gradients(zip([grads0, grads1], [var0, var1])) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval()) self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval()) # Run 1 step of sgd sgd_op.run() # Validate updated params self.assertAllCloseAccordingToType([1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval()) self.assertAllCloseAccordingToType([3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval()) def testGradWrtRef(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.test_session(): opt = gradient_descent.GradientDescentOptimizer(3.0) values = [1.0, 3.0] vars_ = [variables.Variable([v], dtype=dtype) for v in values] grads_and_vars = opt.compute_gradients(vars_[0] + vars_[1], vars_) variables.global_variables_initializer().run() for grad, _ in grads_and_vars: self.assertAllCloseAccordingToType([1.0], grad.eval()) def testWithGlobalStep(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.test_session(): global_step = variables.Variable(0, trainable=False) var0 = variables.Variable([1.0, 2.0], dtype=dtype) var1 = variables.Variable([3.0, 4.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) sgd_op = gradient_descent.GradientDescentOptimizer(3.0).apply_gradients( zip([grads0, grads1], [var0, var1]), global_step=global_step) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval()) self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval()) # Run 1 step of sgd sgd_op.run() # Validate updated params and global_step self.assertAllCloseAccordingToType([1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval()) self.assertAllCloseAccordingToType([3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval()) self.assertAllCloseAccordingToType(1, global_step.eval()) def testSparseBasic(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.test_session(): var0 = variables.Variable([[1.0], [2.0]], dtype=dtype) var1 = variables.Variable([[3.0], [4.0]], dtype=dtype) grads0 = ops.IndexedSlices( constant_op.constant( [0.1], shape=[1, 1], dtype=dtype), constant_op.constant([0]), constant_op.constant([2, 1])) grads1 = ops.IndexedSlices( constant_op.constant( [0.01], shape=[1, 1], dtype=dtype), constant_op.constant([1]), constant_op.constant([2, 1])) sgd_op = gradient_descent.GradientDescentOptimizer(3.0).apply_gradients( zip([grads0, grads1], [var0, var1])) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllCloseAccordingToType([[1.0], [2.0]], var0.eval()) self.assertAllCloseAccordingToType([[3.0], [4.0]], var1.eval()) # Run 1 step of sgd sgd_op.run() # Validate updated params self.assertAllCloseAccordingToType([[1.0 - 3.0 * 0.1], [2.0]], var0.eval()) self.assertAllCloseAccordingToType([[3.0], [4.0 - 3.0 * 0.01]], var1.eval()) if __name__ == "__main__": test.main()
Arakmar/Sick-Beard
refs/heads/development
lib/imdb/parser/http/searchKeywordParser.py
128
""" parser.http.searchKeywordParser module (imdb package). This module provides the HTMLSearchKeywordParser class (and the search_company_parser instance), used to parse the results of a search for a given keyword. E.g., when searching for the keyword "alabama", the parsed page would be: http://akas.imdb.com/find?s=kw;mx=20;q=alabama Copyright 2009 Davide Alberani <da@erlug.linux.it> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from utils import Extractor, Attribute, analyze_imdbid from imdb.utils import analyze_title, analyze_company_name from searchMovieParser import DOMHTMLSearchMovieParser, DOMBasicMovieParser class DOMBasicKeywordParser(DOMBasicMovieParser): """Simply get the name of a keyword. It's used by the DOMHTMLSearchKeywordParser class to return a result for a direct match (when a search on IMDb results in a single keyword, the web server sends directly the keyword page. """ # XXX: it's still to be tested! # I'm not even sure there can be a direct hit, searching for keywords. _titleFunct = lambda self, x: analyze_company_name(x or u'') class DOMHTMLSearchKeywordParser(DOMHTMLSearchMovieParser): """Parse the html page that the IMDb web server shows when the "new search system" is used, searching for keywords similar to the one given.""" _BaseParser = DOMBasicKeywordParser _notDirectHitTitle = '<title>imdb keyword' _titleBuilder = lambda self, x: x _linkPrefix = '/keyword/' _attrs = [Attribute(key='data', multi=True, path="./a[1]/text()" )] extractors = [Extractor(label='search', path="//td[3]/a[starts-with(@href, " \ "'/keyword/')]/..", attrs=_attrs)] def custom_analyze_title4kwd(title, yearNote, outline): """Return a dictionary with the needed info.""" title = title.strip() if not title: return {} if yearNote: yearNote = '%s)' % yearNote.split(' ')[0] title = title + ' ' + yearNote retDict = analyze_title(title) if outline: retDict['plot outline'] = outline return retDict class DOMHTMLSearchMovieKeywordParser(DOMHTMLSearchMovieParser): """Parse the html page that the IMDb web server shows when the "new search system" is used, searching for movies with the given keyword.""" _notDirectHitTitle = '<title>best' _attrs = [Attribute(key='data', multi=True, path={ 'link': "./a[1]/@href", 'info': "./a[1]//text()", 'ynote': "./span[@class='desc']/text()", 'outline': "./span[@class='outline']//text()" }, postprocess=lambda x: ( analyze_imdbid(x.get('link') or u''), custom_analyze_title4kwd(x.get('info') or u'', x.get('ynote') or u'', x.get('outline') or u'') ))] extractors = [Extractor(label='search', path="//td[3]/a[starts-with(@href, " \ "'/title/tt')]/..", attrs=_attrs)] _OBJECTS = { 'search_keyword_parser': ((DOMHTMLSearchKeywordParser,), {'kind': 'keyword', '_basic_parser': DOMBasicKeywordParser}), 'search_moviekeyword_parser': ((DOMHTMLSearchMovieKeywordParser,), None) }
drmrd/ansible
refs/heads/devel
lib/ansible/modules/monitoring/sensu_subscription.py
16
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Anders Ingemann <aim@secoya.dk> # 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: sensu_subscription short_description: Manage Sensu subscriptions version_added: 2.2 description: - Manage which I(sensu channels) a machine should subscribe to options: name: description: - The name of the channel required: true state: description: - Whether the machine should subscribe or unsubscribe from the channel choices: [ 'present', 'absent' ] required: false default: present path: description: - Path to the subscriptions json file required: false default: /etc/sensu/conf.d/subscriptions.json backup: description: - Create a backup file (if yes), including the timestamp information so you - can get the original file back if you somehow clobbered it incorrectly. type: bool required: false default: no requirements: [ ] author: Anders Ingemann ''' RETURN = ''' reasons: description: the reasons why the moule changed or did not change something returned: success type: list sample: ["channel subscription was absent and state is `present'"] ''' EXAMPLES = ''' # Subscribe to the nginx channel - name: subscribe to nginx checks sensu_subscription: name=nginx # Unsubscribe from the common checks channel - name: unsubscribe from common checks sensu_subscription: name=common state=absent ''' import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native def sensu_subscription(module, path, name, state='present', backup=False): changed = False reasons = [] try: import json except ImportError: import simplejson as json try: config = json.load(open(path)) except IOError as e: if e.errno is 2: # File not found, non-fatal if state == 'absent': reasons.append('file did not exist and state is `absent\'') return changed, reasons config = {} else: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) except ValueError: msg = '{path} contains invalid JSON'.format(path=path) module.fail_json(msg=msg) if 'client' not in config: if state == 'absent': reasons.append('`client\' did not exist and state is `absent\'') return changed, reasons config['client'] = {} changed = True reasons.append('`client\' did not exist') if 'subscriptions' not in config['client']: if state == 'absent': reasons.append('`client.subscriptions\' did not exist and state is `absent\'') return changed, reasons config['client']['subscriptions'] = [] changed = True reasons.append('`client.subscriptions\' did not exist') if name not in config['client']['subscriptions']: if state == 'absent': reasons.append('channel subscription was absent') return changed, reasons config['client']['subscriptions'].append(name) changed = True reasons.append('channel subscription was absent and state is `present\'') else: if state == 'absent': config['client']['subscriptions'].remove(name) changed = True reasons.append('channel subscription was present and state is `absent\'') if changed and not module.check_mode: if backup: module.backup_local(path) try: open(path, 'w').write(json.dumps(config, indent=2) + '\n') except IOError as e: module.fail_json(msg='Failed to write to file %s: %s' % (path, to_native(e)), exception=traceback.format_exc()) return changed, reasons def main(): arg_spec = {'name': {'type': 'str', 'required': True}, 'path': {'type': 'str', 'default': '/etc/sensu/conf.d/subscriptions.json'}, 'state': {'type': 'str', 'default': 'present', 'choices': ['present', 'absent']}, 'backup': {'type': 'bool', 'default': 'no'}, } module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=True) path = module.params['path'] name = module.params['name'] state = module.params['state'] backup = module.params['backup'] changed, reasons = sensu_subscription(module, path, name, state, backup) module.exit_json(path=path, name=name, changed=changed, msg='OK', reasons=reasons) if __name__ == '__main__': main()
calcutec/flask-burtonblog
refs/heads/master
app/models.py
1
from hashlib import md5 from werkzeug.security import generate_password_hash, check_password_hash import re from app import db from flask import url_for, g from flask.ext.login import UserMixin from sqlalchemy import desc import json import datetime json.JSONEncoder.default = lambda self, obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else None) followers = db.Table( 'followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id')) ) class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) type = db.Column(db.Integer) firstname = db.Column(db.String(100)) lastname = db.Column(db.String(100)) nickname = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) pwdhash = db.Column(db.String(100)) posts = db.relationship('Post', backref='author', lazy='dynamic') comments = db.relationship('Comment', backref='author', lazy='dynamic', order_by=desc('Comment.created_at')) about_me = db.Column(db.String(140)) photo = db.Column(db.String(240)) last_seen = db.Column(db.DateTime, default=datetime.datetime.utcnow) followed = db.relationship('User', secondary=followers, primaryjoin=(followers.c.follower_id == id), secondaryjoin=(followers.c.followed_id == id), backref=db.backref('followers', lazy='dynamic'), lazy='dynamic') def __init__(self, nickname, email, password=None, firstname=None, lastname=None, photo=None): self.nickname = self.make_unique_nickname(self.make_valid_nickname(nickname)) self.email = email.lower() self.photo = photo # self.followers = followers.query.all() if password is not None: self.set_password(password) if firstname is not None: self.firstname = firstname.title() if lastname is not None: self.lastname = lastname.title() def json_view(self): is_following = None main_user = False if g.user.is_authenticated(): is_following = g.user.is_following(self) if g.user.id == self.id: main_user = True return {'id': self.id, 'type': self.type, 'firstName': self.firstname, 'lastName': self.lastname, 'nickname': self.nickname, 'about_me': self.about_me, 'last_seen': self.last_seen, 'photo': self.photo, 'followers': self.followers.count(), 'followed': self.followed.count(), 'is_following': is_following, 'main_user': main_user} def set_password(self, password): self.pwdhash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.pwdhash, password) @staticmethod def make_valid_nickname(nickname): return re.sub('[^a-zA-Z0-9_\.]', '', nickname) @staticmethod def make_unique_nickname(nickname): if User.query.filter_by(nickname=nickname).first() is None: return nickname new_nickname = nickname version = 2 while True: new_nickname = nickname + str(version) if User.query.filter_by(nickname=new_nickname).first() is None: break version += 1 return new_nickname def is_authenticated(self): return True def is_superuser(self): if self.type == 1: return True else: return False def is_active(self): return True def is_anonymous(self): return False def get_id(self): try: return unicode(self.id) # python 2 except NameError: return str(self.id) # python 3 def avatar(self, size): return 'http://www.gravatar.com/avatar/%s?d=mm&s=%d' % \ (md5(self.email.encode('utf-8')).hexdigest(), size) def follow(self, user): if not self.is_following(user): self.followed.append(user) return self def unfollow(self, user): if self.is_following(user): self.followed.remove(user) return self def is_following(self, user): return self.followed.filter( followers.c.followed_id == user.id).count() > 0 @staticmethod def all_posts(): return Post.query.order_by(Post.timestamp.desc()) @staticmethod def all_poems(): return Post.query.filter(Post.writing_type == 'poem').order_by(Post.timestamp.desc()) @staticmethod def all_op_eds(): return Post.query.filter(Post.writing_type == 'op-ed').order_by(Post.timestamp.desc()) def followed_posts(self): return Post.query.join( followers, (followers.c.followed_id == Post.user_id)).filter( followers.c.follower_id == self.id).order_by( Post.timestamp.desc()) def __repr__(self): # pragma: no cover return '<User %r>' % self.nickname post_upvotes = db.Table('post_upvotes', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('post_id', db.Integer, db.ForeignKey('post.id'))) class Post(db.Model): __searchable__ = ['body'] __tablename__ = 'post' id = db.Column(db.Integer, primary_key=True) header = db.Column(db.String(140)) body = db.Column(db.Text()) timestamp = db.Column(db.DateTime, default=datetime.datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) writing_type = db.Column(db.String(32), default="writing-type") category = db.Column(db.String(32)) photo = db.Column(db.String(240)) comments = db.relationship('Comment', backref='original_post', lazy='dynamic', order_by=desc('Comment.created_at')) stats = db.relationship('ExifStats', uselist=False, backref='original_post', lazy='joined') slug = db.Column(db.String(255)) votes = db.Column(db.Integer, default=1) def __init__(self, **kwargs): super(Post, self).__init__(**kwargs) @property def all_comments(self): return self.comments.all() def get_voter_ids(self): """ return ids of users who voted this post up """ select = post_upvotes.select(post_upvotes.c.post_id == self.id) rs = db.engine.execute(select) ids = rs.fetchall() # list of tuples return ids def has_voted(self, user_id): """ did the user vote already """ select_votes = post_upvotes.select( db.and_( post_upvotes.c.user_id == user_id, post_upvotes.c.post_id == self.id ) ) rs = db.engine.execute(select_votes) return False if rs.rowcount == 0 else True def vote(self, user_id): """ allow a user to vote on a post. if we have voted already (and they are clicking again), this means that they are trying to unvote the post, return status of the vote for that user """ already_voted = self.has_voted(user_id) vote_status = None if not already_voted: # vote up the post db.engine.execute( post_upvotes.insert(), user_id=user_id, post_id=self.id ) if self.votes is None: self.votes = 1 self.votes += 1 vote_status = True else: # unvote the post db.engine.execute( post_upvotes.delete( db.and_( post_upvotes.c.user_id == user_id, post_upvotes.c.post_id == self.id ) ) ) self.votes -= 1 vote_status = False db.session.commit() # for the vote count return vote_status def json_view(self): has_voted = None exifdata = None if g.user.is_authenticated(): has_voted = self.has_voted(g.user.id) if self.stats: exifdata = self.stats.json_view() comments = self.comments.order_by('created_at').all() return {'id': self.id, 'author': self.user_id, 'header': self.header, 'body': self.body, 'photo': self.photo, 'category': self.category, 'nickname': self.author.nickname, 'timestamp': self.timestamp, 'has_voted': has_voted, 'votes': self.votes, 'comments': [i.json_view() for i in comments], 'exifData': exifdata} def get_absolute_url(self): return url_for('post', kwargs={"slug": self.slug}) def __repr__(self): # pragma: no cover return '<Post %r>' % self.body class ExifStats(db.Model): __tablename__ = 'exifstats' id = db.Column(db.Integer, primary_key=True) post_id = db.Column(db.Integer, db.ForeignKey('post.id')) Make = db.Column(db.String(80)) Model = db.Column(db.String(80)) DateTime = db.Column(db.DateTime) DateTimeOriginal = db.Column(db.DateTime) ShutterSpeedValue = db.Column(db.String(80)) FNumber = db.Column(db.String(16)) ExposureProgram = db.Column(db.String(80)) PhotographicSensitivity = db.Column(db.String(80)) FocalLength = db.Column(db.String(80)) FocalLengthIn35mmFilm = db.Column(db.String(80)) LensModel = db.Column(db.String(80)) Sharpness = db.Column(db.String(80)) PixelXDimension = db.Column(db.String(80)) PixelYDimension = db.Column(db.String(80)) Orientation = db.Column(db.String(80)) def json_view(self): return {'id': self.id, 'post_id': self.post_id, 'Make': self.Make, 'Model': self.Model, 'DateTime': self.DateTime, 'DateTimeOriginal': self.DateTimeOriginal, 'ShutterSpeedValue': self.ShutterSpeedValue,'FNumber': self.FNumber, 'ExposureProgram': self.ExposureProgram, 'PhotographicSensitivity': self.PhotographicSensitivity, 'FocalLength': self.FocalLength, 'FocalLengthIn35mmFilm': self.FocalLengthIn35mmFilm, 'LensModel': self.LensModel, 'Sharpness': self.Sharpness, 'PixelXDimension': self.PixelXDimension, 'PixelYDimension': self.PixelYDimension, 'Orientation': self.Orientation} class Comment(db.Model): __tablename__ = 'comment' id = db.Column(db.Integer, primary_key=True) comment = db.Column(db.String(500)) post_id = db.Column(db.Integer, db.ForeignKey('post.id')) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) created_at = db.Column(db.DateTime) def __repr__(self): # pragma: no cover return '<Comment %r>' % self.comment def json_view(self): comment_author = User.query.get(self.user_id) author = { 'nickname': comment_author.nickname, 'photo': comment_author.photo } return {'id': self.id, 'comment': self.comment, 'post_id': self.post_id, 'user_id': self.user_id, 'author': author, 'created_at': self.created_at}
gormanb/mtools
refs/heads/master
mtools/util/grouping.py
8
from mtools.util import OrderedDict import re class Grouping(object): def __init__(self, iterable=None, group_by=None): self.groups = {} self.group_by = group_by if iterable: for item in iterable: self.add(item, group_by) def add(self, item, group_by=None): """ General purpose class to group items by certain criteria. """ key = None if not group_by: group_by = self.group_by if group_by: # if group_by is a function, use it with item as argument if hasattr(group_by, '__call__'): key = group_by(item) # if the item has attribute of group_by as string, use that as key elif isinstance(group_by, str) and hasattr(item, group_by): key = getattr(item, group_by) else: key = None # try to match str(item) with regular expression if isinstance(group_by, str): match = re.search(group_by, str(item)) if match: if len(match.groups()) > 0: key = match.group(1) else: key = match.group() self.groups.setdefault(key, list()).append(item) def __getitem__(self, key): return self.groups[key] def __iter__(self): for key in self.groups: yield key def __len__(self): return len(self.groups) def keys(self): return self.groups.keys() def values(self): return self.groups.values() def items(self): return self.groups.items() def regroup(self, group_by=None): if not group_by: group_by = self.group_by groups = self.groups self.groups = {} for g in groups: for item in groups[g]: self.add(item, group_by) def move_items(self, from_group, to_group): """ will take all elements from the from_group and add it to the to_group. """ if from_group not in self.keys() or len(self.groups[from_group]) == 0: return self.groups.setdefault(to_group, list()).extend(self.groups.get(from_group, list())) if from_group in self.groups: del self.groups[from_group] def sort_by_size(self, group_limit=None, discard_others=False, others_label='others'): """ sorts the groups by the number of elements they contain, descending. Also has option to limit the number of groups. If this option is chosen, the remaining elements are placed into another group with the name specified with others_label. if discard_others is True, the others group is removed instead. """ # sort groups by number of elements self.groups = OrderedDict( sorted(self.groups.iteritems(), key=lambda x: len(x[1]), reverse=True) ) # if group-limit is provided, combine remaining groups if group_limit != None: # now group together all groups that did not make the limit if not discard_others: group_keys = self.groups.keys()[ group_limit-1: ] self.groups.setdefault(others_label, list()) else: group_keys = self.groups.keys()[ group_limit: ] # only go to second last (-1), since the 'others' group is now last for g in group_keys: if not discard_others: self.groups[others_label].extend(self.groups[g]) del self.groups[g] # remove if empty if others_label in self.groups and len(self.groups[others_label]) == 0: del self.groups[others_label] # remove others group regardless of limit if requested if discard_others and others_label in self.groups: del self.groups[others_label] if __name__ == '__main__': # Example items = [1, 4, 3, 5, 7, 8, 6, 7, 9, 8, 6, 4, 2, 3, 3, 0] grouping = Grouping(items, r'[3, 4, 5, 6, 7]') grouping.sort_by_size(group_limit=1, discard_others=True) # grouping.move_items('no match', 'foo') grouping.regroup(lambda x: 'even' if x % 2 == 0 else 'odd') for g in grouping: print g, grouping[g]
juggernaut/pyrollbar
refs/heads/master
rollbar/test/test_loghandler.py
2
""" Tests for the RollbarHandler logging handler """ import copy import logging import mock import urllib import sys import rollbar from rollbar.logger import RollbarHandler from . import BaseTest _test_access_token = 'aaaabbbbccccddddeeeeffff00001111' _test_environment = 'test' _default_settings = copy.deepcopy(rollbar.SETTINGS) class LogHandlerTest(BaseTest): def setUp(self): rollbar._initialized = False rollbar.SETTINGS = copy.deepcopy(_default_settings) def _create_logger(self): logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) rollbar_handler = RollbarHandler(_test_access_token, _test_environment) rollbar_handler.setLevel(logging.WARNING) logger.addHandler(rollbar_handler) return logger @mock.patch('rollbar.send_payload') def test_message_stays_unformatted(self, send_payload): logger = self._create_logger() logger.warning("Hello %d %s", 1, 'world') payload = send_payload.call_args[0][0] self.assertEqual(payload['data']['body']['message']['body'], "Hello %d %s") self.assertEqual(payload['data']['body']['message']['args'], (1, 'world')) self.assertEqual(payload['data']['body']['message']['record']['name'], __name__) def test_request_is_get_from_log_record_if_present(self): logger = self._create_logger() # Request objects vary depending on python frameworks or packages. # Using a dictionary for this test is enough. request = {"fake": "request", "for": "testing purporse"} # No need to test request parsing and payload sent, # just need to be sure that proper rollbar function is called # with passed request as argument. with mock.patch("rollbar.report_message") as report_message_mock: logger.warning("Warning message", extra={"request": request}) self.assertEquals(report_message_mock.call_args[1]["request"], request) # Python 2.6 doesnt support extra param in logger.exception. if not sys.version_info[:2] == (2, 6): with mock.patch("rollbar.report_exc_info") as report_exc_info: logger.exception("Exception message", extra={"request": request}) self.assertEquals(report_exc_info.call_args[1]["request"], request)
dayutianfei/impala-Q
refs/heads/master
common/function-registry/gen_builtins_catalog.py
8
#!/usr/bin/env python # Copyright 2012 Cloudera 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. # This script generates the FE calls to populate the builtins. # To add a builtin, add an entry to impala_functions.py. import sys import os from string import Template import impala_functions java_registry_preamble = '\ // Copyright 2012 Cloudera Inc.\n\ // \n\ // Licensed under the Apache License, Version 2.0 (the "License");\n\ // you may not use this file except in compliance with the License.\n\ // You may obtain a copy of the License at\n\ // \n\ // http://www.apache.org/licenses/LICENSE-2.0\n\ // \n\ // Unless required by applicable law or agreed to in writing, software\n\ // distributed under the License is distributed on an "AS IS" BASIS,\n\ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\ // See the License for the specific language governing permissions and\n\ // limitations under the License.\n\ \n\ // This is a generated file, DO NOT EDIT.\n\ // To add new functions, see the generator at\n\ // common/function-registry/gen_builtins_catalog.py or the function list at\n\ // common/function-registry/impala_functions.py.\n\ \n\ package com.cloudera.impala.builtins;\n\ \n\ import com.cloudera.impala.catalog.Type;\n\ import com.cloudera.impala.catalog.Db;\n\ \n\ public class ScalarBuiltins { \n\ public static void initBuiltins(Db db) { \ \n' java_registry_epilogue = '\ }\n\ }\n' FE_PATH = os.path.expandvars( "$IMPALA_HOME/fe/generated-sources/gen-java/com/cloudera/impala/builtins/") # This contains all the metadata to describe all the builtins. # Each meta data entry is itself a map to store all the meta data # - fn_name, ret_type, args, symbol, sql_names meta_data_entries = [] # Read in the function and add it to the meta_data_entries map def add_function(fn_meta_data): entry = {} entry["sql_names"] = fn_meta_data[0] entry["ret_type"] = fn_meta_data[1] entry["args"] = fn_meta_data[2] entry["symbol"] = fn_meta_data[3] if len(fn_meta_data) >= 5: entry["prepare"] = fn_meta_data[4] if len(fn_meta_data) >= 6: entry["close"] = fn_meta_data[5] meta_data_entries.append(entry) def generate_fe_entry(entry, name): java_output = "" java_output += "\"" + name + "\"" java_output += ", \"" + entry["symbol"] + "\"" if 'prepare' in entry: java_output += ', "%s"' % entry["prepare"] if 'close' in entry: java_output += ', "%s"' % entry["close"] else: java_output += ', null' # Check the last entry for varargs indicator. if entry["args"] and entry["args"][-1] == "...": entry["args"].pop() java_output += ", true" else: java_output += ", false" java_output += ", Type." + entry["ret_type"] for arg in entry["args"]: java_output += ", Type." + arg return java_output # Generates the FE builtins init file that registers all the builtins. def generate_fe_registry_init(filename): java_registry_file = open(filename, "w") java_registry_file.write(java_registry_preamble) for entry in meta_data_entries: for name in entry["sql_names"]: java_output = generate_fe_entry(entry, name) java_registry_file.write(" db.addScalarBuiltin(%s);\n" % java_output) java_registry_file.write("\n") java_registry_file.write(java_registry_epilogue) java_registry_file.close() # Read the function metadata inputs for function in impala_functions.functions: assert 4 <= len(function) <= 6, \ "Invalid function entry in impala_functions.py:\n\t" + repr(function) add_function(function) if not os.path.exists(FE_PATH): os.makedirs(FE_PATH) generate_fe_registry_init(FE_PATH + "ScalarBuiltins.java")
ivanlmj/Android-DNSSL
refs/heads/master
Flask/lib/python2.7/site-packages/pip/_vendor/html5lib/tokenizer.py
1710
from __future__ import absolute_import, division, unicode_literals try: chr = unichr # flake8: noqa except NameError: pass from collections import deque from .constants import spaceCharacters from .constants import entities from .constants import asciiLetters, asciiUpper2Lower from .constants import digits, hexDigits, EOF from .constants import tokenTypes, tagTokenTypes from .constants import replacementCharacters from .inputstream import HTMLInputStream from .trie import Trie entitiesTrie = Trie(entities) class HTMLTokenizer(object): """ This class takes care of tokenizing HTML. * self.currentToken Holds the token that is currently being processed. * self.state Holds a reference to the method to be invoked... XXX * self.stream Points to HTMLInputStream object. """ def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True, lowercaseElementName=True, lowercaseAttrName=True, parser=None): self.stream = HTMLInputStream(stream, encoding, parseMeta, useChardet) self.parser = parser # Perform case conversions? self.lowercaseElementName = lowercaseElementName self.lowercaseAttrName = lowercaseAttrName # Setup the initial tokenizer state self.escapeFlag = False self.lastFourChars = [] self.state = self.dataState self.escape = False # The current token being created self.currentToken = None super(HTMLTokenizer, self).__init__() def __iter__(self): """ This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested. """ self.tokenQueue = deque([]) # Start processing. When EOF is reached self.state will return False # instead of True and the loop will terminate. while self.state(): while self.stream.errors: yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)} while self.tokenQueue: yield self.tokenQueue.popleft() def consumeNumberEntity(self, isHex): """This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked. """ allowed = digits radix = 10 if isHex: allowed = hexDigits radix = 16 charStack = [] # Consume all the characters that are in range while making sure we # don't hit an EOF. c = self.stream.char() while c in allowed and c is not EOF: charStack.append(c) c = self.stream.char() # Convert the set of characters consumed to an int. charAsInt = int("".join(charStack), radix) # Certain characters get replaced with others if charAsInt in replacementCharacters: char = replacementCharacters[charAsInt] self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) elif ((0xD800 <= charAsInt <= 0xDFFF) or (charAsInt > 0x10FFFF)): char = "\uFFFD" self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) else: # Should speed up this check somehow (e.g. move the set to a constant) if ((0x0001 <= charAsInt <= 0x0008) or (0x000E <= charAsInt <= 0x001F) or (0x007F <= charAsInt <= 0x009F) or (0xFDD0 <= charAsInt <= 0xFDEF) or charAsInt in frozenset([0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, 0x10FFFF])): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "illegal-codepoint-for-numeric-entity", "datavars": {"charAsInt": charAsInt}}) try: # Try/except needed as UCS-2 Python builds' unichar only works # within the BMP. char = chr(charAsInt) except ValueError: v = charAsInt - 0x10000 char = chr(0xD800 | (v >> 10)) + chr(0xDC00 | (v & 0x3FF)) # Discard the ; if present. Otherwise, put it back on the queue and # invoke parseError on parser. if c != ";": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "numeric-entity-without-semicolon"}) self.stream.unget(c) return char def consumeEntity(self, allowedChar=None, fromAttribute=False): # Initialise to the default output for when no entity is matched output = "&" charStack = [self.stream.char()] if (charStack[0] in spaceCharacters or charStack[0] in (EOF, "<", "&") or (allowedChar is not None and allowedChar == charStack[0])): self.stream.unget(charStack[0]) elif charStack[0] == "#": # Read the next character to see if it's hex or decimal hex = False charStack.append(self.stream.char()) if charStack[-1] in ("x", "X"): hex = True charStack.append(self.stream.char()) # charStack[-1] should be the first digit if (hex and charStack[-1] in hexDigits) \ or (not hex and charStack[-1] in digits): # At least one digit found, so consume the whole number self.stream.unget(charStack[-1]) output = self.consumeNumberEntity(hex) else: # No digits found self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-numeric-entity"}) self.stream.unget(charStack.pop()) output = "&" + "".join(charStack) else: # At this point in the process might have named entity. Entities # are stored in the global variable "entities". # # Consume characters and compare to these to a substring of the # entity names in the list until the substring no longer matches. while (charStack[-1] is not EOF): if not entitiesTrie.has_keys_with_prefix("".join(charStack)): break charStack.append(self.stream.char()) # At this point we have a string that starts with some characters # that may match an entity # Try to find the longest entity the string will match to take care # of &noti for instance. try: entityName = entitiesTrie.longest_prefix("".join(charStack[:-1])) entityLength = len(entityName) except KeyError: entityName = None if entityName is not None: if entityName[-1] != ";": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "named-entity-without-semicolon"}) if (entityName[-1] != ";" and fromAttribute and (charStack[entityLength] in asciiLetters or charStack[entityLength] in digits or charStack[entityLength] == "=")): self.stream.unget(charStack.pop()) output = "&" + "".join(charStack) else: output = entities[entityName] self.stream.unget(charStack.pop()) output += "".join(charStack[entityLength:]) else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-named-entity"}) self.stream.unget(charStack.pop()) output = "&" + "".join(charStack) if fromAttribute: self.currentToken["data"][-1][1] += output else: if output in spaceCharacters: tokenType = "SpaceCharacters" else: tokenType = "Characters" self.tokenQueue.append({"type": tokenTypes[tokenType], "data": output}) def processEntityInAttribute(self, allowedChar): """This method replaces the need for "entityInAttributeValueState". """ self.consumeEntity(allowedChar=allowedChar, fromAttribute=True) def emitCurrentToken(self): """This method is a generic handler for emitting the tags. It also sets the state to "data" because that's what's needed after a token has been emitted. """ token = self.currentToken # Add token to the queue to be yielded if (token["type"] in tagTokenTypes): if self.lowercaseElementName: token["name"] = token["name"].translate(asciiUpper2Lower) if token["type"] == tokenTypes["EndTag"]: if token["data"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "attributes-in-end-tag"}) if token["selfClosing"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "self-closing-flag-on-end-tag"}) self.tokenQueue.append(token) self.state = self.dataState # Below are the various tokenizer states worked out. def dataState(self): data = self.stream.char() if data == "&": self.state = self.entityDataState elif data == "<": self.state = self.tagOpenState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\u0000"}) elif data is EOF: # Tokenization ends. return False elif data in spaceCharacters: # Directly after emitting a token you switch back to the "data # state". At that point spaceCharacters are important so they are # emitted separately. self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data": data + self.stream.charsUntil(spaceCharacters, True)}) # No need to update lastFourChars here, since the first space will # have already been appended to lastFourChars and will have broken # any <!-- or --> sequences else: chars = self.stream.charsUntil(("&", "<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def entityDataState(self): self.consumeEntity() self.state = self.dataState return True def rcdataState(self): data = self.stream.char() if data == "&": self.state = self.characterReferenceInRcdata elif data == "<": self.state = self.rcdataLessThanSignState elif data == EOF: # Tokenization ends. return False elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data in spaceCharacters: # Directly after emitting a token you switch back to the "data # state". At that point spaceCharacters are important so they are # emitted separately. self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data": data + self.stream.charsUntil(spaceCharacters, True)}) # No need to update lastFourChars here, since the first space will # have already been appended to lastFourChars and will have broken # any <!-- or --> sequences else: chars = self.stream.charsUntil(("&", "<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def characterReferenceInRcdata(self): self.consumeEntity() self.state = self.rcdataState return True def rawtextState(self): data = self.stream.char() if data == "<": self.state = self.rawtextLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: # Tokenization ends. return False else: chars = self.stream.charsUntil(("<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def scriptDataState(self): data = self.stream.char() if data == "<": self.state = self.scriptDataLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: # Tokenization ends. return False else: chars = self.stream.charsUntil(("<", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def plaintextState(self): data = self.stream.char() if data == EOF: # Tokenization ends. return False elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + self.stream.charsUntil("\u0000")}) return True def tagOpenState(self): data = self.stream.char() if data == "!": self.state = self.markupDeclarationOpenState elif data == "/": self.state = self.closeTagOpenState elif data in asciiLetters: self.currentToken = {"type": tokenTypes["StartTag"], "name": data, "data": [], "selfClosing": False, "selfClosingAcknowledged": False} self.state = self.tagNameState elif data == ">": # XXX In theory it could be something besides a tag name. But # do we really care? self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-tag-name-but-got-right-bracket"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<>"}) self.state = self.dataState elif data == "?": # XXX In theory it could be something besides a tag name. But # do we really care? self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-tag-name-but-got-question-mark"}) self.stream.unget(data) self.state = self.bogusCommentState else: # XXX self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-tag-name"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.dataState return True def closeTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.currentToken = {"type": tokenTypes["EndTag"], "name": data, "data": [], "selfClosing": False} self.state = self.tagNameState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-closing-tag-but-got-right-bracket"}) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-closing-tag-but-got-eof"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.state = self.dataState else: # XXX data can be _'_... self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-closing-tag-but-got-char", "datavars": {"data": data}}) self.stream.unget(data) self.state = self.bogusCommentState return True def tagNameState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeAttributeNameState elif data == ">": self.emitCurrentToken() elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-tag-name"}) self.state = self.dataState elif data == "/": self.state = self.selfClosingStartTagState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["name"] += "\uFFFD" else: self.currentToken["name"] += data # (Don't use charsUntil here, because tag names are # very short and it's faster to not do anything fancy) return True def rcdataLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.rcdataEndTagOpenState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.rcdataState return True def rcdataEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.rcdataEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.rcdataState return True def rcdataEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.rcdataState return True def rawtextLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.rawtextEndTagOpenState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.rawtextState return True def rawtextEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.rawtextEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.rawtextState return True def rawtextEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.rawtextState return True def scriptDataLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.scriptDataEndTagOpenState elif data == "!": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<!"}) self.state = self.scriptDataEscapeStartState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.scriptDataEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEscapeStartState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapeStartDashState else: self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEscapeStartDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapedDashDashState else: self.stream.unget(data) self.state = self.scriptDataState return True def scriptDataEscapedState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapedDashState elif data == "<": self.state = self.scriptDataEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: self.state = self.dataState else: chars = self.stream.charsUntil(("<", "-", "\u0000")) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data + chars}) return True def scriptDataEscapedDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataEscapedDashDashState elif data == "<": self.state = self.scriptDataEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataEscapedState elif data == EOF: self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataEscapedState return True def scriptDataEscapedDashDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) elif data == "<": self.state = self.scriptDataEscapedLessThanSignState elif data == ">": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"}) self.state = self.scriptDataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataEscapedState elif data == EOF: self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataEscapedState return True def scriptDataEscapedLessThanSignState(self): data = self.stream.char() if data == "/": self.temporaryBuffer = "" self.state = self.scriptDataEscapedEndTagOpenState elif data in asciiLetters: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<" + data}) self.temporaryBuffer = data self.state = self.scriptDataDoubleEscapeStartState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataEscapedEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer = data self.state = self.scriptDataEscapedEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataEscapedEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataDoubleEscapeStartState(self): data = self.stream.char() if data in (spaceCharacters | frozenset(("/", ">"))): self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) if self.temporaryBuffer.lower() == "script": self.state = self.scriptDataDoubleEscapedState else: self.state = self.scriptDataEscapedState elif data in asciiLetters: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.temporaryBuffer += data else: self.stream.unget(data) self.state = self.scriptDataEscapedState return True def scriptDataDoubleEscapedState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataDoubleEscapedDashState elif data == "<": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.state = self.scriptDataDoubleEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-script-in-script"}) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) return True def scriptDataDoubleEscapedDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) self.state = self.scriptDataDoubleEscapedDashDashState elif data == "<": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.state = self.scriptDataDoubleEscapedLessThanSignState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataDoubleEscapedState elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-script-in-script"}) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataDoubleEscapedState return True def scriptDataDoubleEscapedDashDashState(self): data = self.stream.char() if data == "-": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"}) elif data == "<": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"}) self.state = self.scriptDataDoubleEscapedLessThanSignState elif data == ">": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"}) self.state = self.scriptDataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "\uFFFD"}) self.state = self.scriptDataDoubleEscapedState elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-script-in-script"}) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.scriptDataDoubleEscapedState return True def scriptDataDoubleEscapedLessThanSignState(self): data = self.stream.char() if data == "/": self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "/"}) self.temporaryBuffer = "" self.state = self.scriptDataDoubleEscapeEndState else: self.stream.unget(data) self.state = self.scriptDataDoubleEscapedState return True def scriptDataDoubleEscapeEndState(self): data = self.stream.char() if data in (spaceCharacters | frozenset(("/", ">"))): self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) if self.temporaryBuffer.lower() == "script": self.state = self.scriptDataEscapedState else: self.state = self.scriptDataDoubleEscapedState elif data in asciiLetters: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.temporaryBuffer += data else: self.stream.unget(data) self.state = self.scriptDataDoubleEscapedState return True def beforeAttributeNameState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data in asciiLetters: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data == ">": self.emitCurrentToken() elif data == "/": self.state = self.selfClosingStartTagState elif data in ("'", '"', "=", "<"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-character-in-attribute-name"}) self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"].append(["\uFFFD", ""]) self.state = self.attributeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-name-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState return True def attributeNameState(self): data = self.stream.char() leavingThisState = True emitToken = False if data == "=": self.state = self.beforeAttributeValueState elif data in asciiLetters: self.currentToken["data"][-1][0] += data +\ self.stream.charsUntil(asciiLetters, True) leavingThisState = False elif data == ">": # XXX If we emit here the attributes are converted to a dict # without being checked and when the code below runs we error # because data is a dict not a list emitToken = True elif data in spaceCharacters: self.state = self.afterAttributeNameState elif data == "/": self.state = self.selfClosingStartTagState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][0] += "\uFFFD" leavingThisState = False elif data in ("'", '"', "<"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-character-in-attribute-name"}) self.currentToken["data"][-1][0] += data leavingThisState = False elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-name"}) self.state = self.dataState else: self.currentToken["data"][-1][0] += data leavingThisState = False if leavingThisState: # Attributes are not dropped at this stage. That happens when the # start tag token is emitted so values can still be safely appended # to attributes, but we do want to report the parse error in time. if self.lowercaseAttrName: self.currentToken["data"][-1][0] = ( self.currentToken["data"][-1][0].translate(asciiUpper2Lower)) for name, value in self.currentToken["data"][:-1]: if self.currentToken["data"][-1][0] == name: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "duplicate-attribute"}) break # XXX Fix for above XXX if emitToken: self.emitCurrentToken() return True def afterAttributeNameState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data == "=": self.state = self.beforeAttributeValueState elif data == ">": self.emitCurrentToken() elif data in asciiLetters: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data == "/": self.state = self.selfClosingStartTagState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"].append(["\uFFFD", ""]) self.state = self.attributeNameState elif data in ("'", '"', "<"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-character-after-attribute-name"}) self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-end-of-tag-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"].append([data, ""]) self.state = self.attributeNameState return True def beforeAttributeValueState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data == "\"": self.state = self.attributeValueDoubleQuotedState elif data == "&": self.state = self.attributeValueUnQuotedState self.stream.unget(data) elif data == "'": self.state = self.attributeValueSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-value-but-got-right-bracket"}) self.emitCurrentToken() elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" self.state = self.attributeValueUnQuotedState elif data in ("=", "<", "`"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "equals-in-unquoted-attribute-value"}) self.currentToken["data"][-1][1] += data self.state = self.attributeValueUnQuotedState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-value-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data self.state = self.attributeValueUnQuotedState return True def attributeValueDoubleQuotedState(self): data = self.stream.char() if data == "\"": self.state = self.afterAttributeValueState elif data == "&": self.processEntityInAttribute('"') elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-value-double-quote"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data +\ self.stream.charsUntil(("\"", "&", "\u0000")) return True def attributeValueSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterAttributeValueState elif data == "&": self.processEntityInAttribute("'") elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-value-single-quote"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data +\ self.stream.charsUntil(("'", "&", "\u0000")) return True def attributeValueUnQuotedState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeAttributeNameState elif data == "&": self.processEntityInAttribute(">") elif data == ">": self.emitCurrentToken() elif data in ('"', "'", "=", "<", "`"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-character-in-unquoted-attribute-value"}) self.currentToken["data"][-1][1] += data elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-attribute-value-no-quotes"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data + self.stream.charsUntil( frozenset(("&", ">", '"', "'", "=", "<", "`", "\u0000")) | spaceCharacters) return True def afterAttributeValueState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeAttributeNameState elif data == ">": self.emitCurrentToken() elif data == "/": self.state = self.selfClosingStartTagState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-EOF-after-attribute-value"}) self.stream.unget(data) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-character-after-attribute-value"}) self.stream.unget(data) self.state = self.beforeAttributeNameState return True def selfClosingStartTagState(self): data = self.stream.char() if data == ">": self.currentToken["selfClosing"] = True self.emitCurrentToken() elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-EOF-after-solidus-in-tag"}) self.stream.unget(data) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-character-after-solidus-in-tag"}) self.stream.unget(data) self.state = self.beforeAttributeNameState return True def bogusCommentState(self): # Make a new comment token and give it as value all the characters # until the first > or EOF (charsUntil checks for EOF automatically) # and emit it. data = self.stream.charsUntil(">") data = data.replace("\u0000", "\uFFFD") self.tokenQueue.append( {"type": tokenTypes["Comment"], "data": data}) # Eat the character directly after the bogus comment which is either a # ">" or an EOF. self.stream.char() self.state = self.dataState return True def markupDeclarationOpenState(self): charStack = [self.stream.char()] if charStack[-1] == "-": charStack.append(self.stream.char()) if charStack[-1] == "-": self.currentToken = {"type": tokenTypes["Comment"], "data": ""} self.state = self.commentStartState return True elif charStack[-1] in ('d', 'D'): matched = True for expected in (('o', 'O'), ('c', 'C'), ('t', 'T'), ('y', 'Y'), ('p', 'P'), ('e', 'E')): charStack.append(self.stream.char()) if charStack[-1] not in expected: matched = False break if matched: self.currentToken = {"type": tokenTypes["Doctype"], "name": "", "publicId": None, "systemId": None, "correct": True} self.state = self.doctypeState return True elif (charStack[-1] == "[" and self.parser is not None and self.parser.tree.openElements and self.parser.tree.openElements[-1].namespace != self.parser.tree.defaultNamespace): matched = True for expected in ["C", "D", "A", "T", "A", "["]: charStack.append(self.stream.char()) if charStack[-1] != expected: matched = False break if matched: self.state = self.cdataSectionState return True self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-dashes-or-doctype"}) while charStack: self.stream.unget(charStack.pop()) self.state = self.bogusCommentState return True def commentStartState(self): data = self.stream.char() if data == "-": self.state = self.commentStartDashState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "incorrect-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += data self.state = self.commentState return True def commentStartDashState(self): data = self.stream.char() if data == "-": self.state = self.commentEndState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "-\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "incorrect-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += "-" + data self.state = self.commentState return True def commentState(self): data = self.stream.char() if data == "-": self.state = self.commentEndDashState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "\uFFFD" elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += data + \ self.stream.charsUntil(("-", "\u0000")) return True def commentEndDashState(self): data = self.stream.char() if data == "-": self.state = self.commentEndState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "-\uFFFD" self.state = self.commentState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment-end-dash"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += "-" + data self.state = self.commentState return True def commentEndState(self): data = self.stream.char() if data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "--\uFFFD" self.state = self.commentState elif data == "!": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-bang-after-double-dash-in-comment"}) self.state = self.commentEndBangState elif data == "-": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-dash-after-double-dash-in-comment"}) self.currentToken["data"] += data elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment-double-dash"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: # XXX self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-comment"}) self.currentToken["data"] += "--" + data self.state = self.commentState return True def commentEndBangState(self): data = self.stream.char() if data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "-": self.currentToken["data"] += "--!" self.state = self.commentEndDashState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"] += "--!\uFFFD" self.state = self.commentState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-comment-end-bang-state"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["data"] += "--!" + data self.state = self.commentState return True def doctypeState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeDoctypeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-doctype-name-but-got-eof"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "need-space-after-doctype"}) self.stream.unget(data) self.state = self.beforeDoctypeNameState return True def beforeDoctypeNameState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-doctype-name-but-got-right-bracket"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["name"] = "\uFFFD" self.state = self.doctypeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-doctype-name-but-got-eof"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["name"] = data self.state = self.doctypeNameState return True def doctypeNameState(self): data = self.stream.char() if data in spaceCharacters: self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) self.state = self.afterDoctypeNameState elif data == ">": self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["name"] += "\uFFFD" self.state = self.doctypeNameState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype-name"}) self.currentToken["correct"] = False self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["name"] += data return True def afterDoctypeNameState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.currentToken["correct"] = False self.stream.unget(data) self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: if data in ("p", "P"): matched = True for expected in (("u", "U"), ("b", "B"), ("l", "L"), ("i", "I"), ("c", "C")): data = self.stream.char() if data not in expected: matched = False break if matched: self.state = self.afterDoctypePublicKeywordState return True elif data in ("s", "S"): matched = True for expected in (("y", "Y"), ("s", "S"), ("t", "T"), ("e", "E"), ("m", "M")): data = self.stream.char() if data not in expected: matched = False break if matched: self.state = self.afterDoctypeSystemKeywordState return True # All the characters read before the current 'data' will be # [a-zA-Z], so they're garbage in the bogus doctype and can be # discarded; only the latest character might be '>' or EOF # and needs to be ungetted self.stream.unget(data) self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-space-or-right-bracket-in-doctype", "datavars": {"data": data}}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def afterDoctypePublicKeywordState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeDoctypePublicIdentifierState elif data in ("'", '"'): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.stream.unget(data) self.state = self.beforeDoctypePublicIdentifierState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.stream.unget(data) self.state = self.beforeDoctypePublicIdentifierState return True def beforeDoctypePublicIdentifierState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == "\"": self.currentToken["publicId"] = "" self.state = self.doctypePublicIdentifierDoubleQuotedState elif data == "'": self.currentToken["publicId"] = "" self.state = self.doctypePublicIdentifierSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def doctypePublicIdentifierDoubleQuotedState(self): data = self.stream.char() if data == "\"": self.state = self.afterDoctypePublicIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["publicId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["publicId"] += data return True def doctypePublicIdentifierSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterDoctypePublicIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["publicId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["publicId"] += data return True def afterDoctypePublicIdentifierState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.betweenDoctypePublicAndSystemIdentifiersState elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == '"': self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierDoubleQuotedState elif data == "'": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierSingleQuotedState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def betweenDoctypePublicAndSystemIdentifiersState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data == '"': self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierDoubleQuotedState elif data == "'": self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierSingleQuotedState elif data == EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def afterDoctypeSystemKeywordState(self): data = self.stream.char() if data in spaceCharacters: self.state = self.beforeDoctypeSystemIdentifierState elif data in ("'", '"'): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.stream.unget(data) self.state = self.beforeDoctypeSystemIdentifierState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.stream.unget(data) self.state = self.beforeDoctypeSystemIdentifierState return True def beforeDoctypeSystemIdentifierState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == "\"": self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierDoubleQuotedState elif data == "'": self.currentToken["systemId"] = "" self.state = self.doctypeSystemIdentifierSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.currentToken["correct"] = False self.state = self.bogusDoctypeState return True def doctypeSystemIdentifierDoubleQuotedState(self): data = self.stream.char() if data == "\"": self.state = self.afterDoctypeSystemIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["systemId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["systemId"] += data return True def doctypeSystemIdentifierSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterDoctypeSystemIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["systemId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["systemId"] += data return True def afterDoctypeSystemIdentifierState(self): data = self.stream.char() if data in spaceCharacters: pass elif data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-char-in-doctype"}) self.state = self.bogusDoctypeState return True def bogusDoctypeState(self): data = self.stream.char() if data == ">": self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: # XXX EMIT self.stream.unget(data) self.tokenQueue.append(self.currentToken) self.state = self.dataState else: pass return True def cdataSectionState(self): data = [] while True: data.append(self.stream.charsUntil("]")) data.append(self.stream.charsUntil(">")) char = self.stream.char() if char == EOF: break else: assert char == ">" if data[-1][-2:] == "]]": data[-1] = data[-1][:-2] break else: data.append(char) data = "".join(data) # Deal with null here rather than in the parser nullCount = data.count("\u0000") if nullCount > 0: for i in range(nullCount): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) data = data.replace("\u0000", "\uFFFD") if data: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data}) self.state = self.dataState return True
kyroskoh/phantomjs
refs/heads/master
src/qt/qtbase/src/3rdparty/freetype/src/tools/chktrcmp.py
381
#!/usr/bin/env python # # Check trace components in FreeType 2 source. # Author: suzuki toshiya, 2009 # # This code is explicitly into the public domain. import sys import os import re SRC_FILE_LIST = [] USED_COMPONENT = {} KNOWN_COMPONENT = {} SRC_FILE_DIRS = [ "src" ] TRACE_DEF_FILES = [ "include/freetype/internal/fttrace.h" ] # -------------------------------------------------------------- # Parse command line options # for i in range( 1, len( sys.argv ) ): if sys.argv[i].startswith( "--help" ): print "Usage: %s [option]" % sys.argv[0] print "Search used-but-defined and defined-but-not-used trace_XXX macros" print "" print " --help:" print " Show this help" print "" print " --src-dirs=dir1:dir2:..." print " Specify the directories of C source files to be checked" print " Default is %s" % ":".join( SRC_FILE_DIRS ) print "" print " --def-files=file1:file2:..." print " Specify the header files including FT_TRACE_DEF()" print " Default is %s" % ":".join( TRACE_DEF_FILES ) print "" exit(0) if sys.argv[i].startswith( "--src-dirs=" ): SRC_FILE_DIRS = sys.argv[i].replace( "--src-dirs=", "", 1 ).split( ":" ) elif sys.argv[i].startswith( "--def-files=" ): TRACE_DEF_FILES = sys.argv[i].replace( "--def-files=", "", 1 ).split( ":" ) # -------------------------------------------------------------- # Scan C source and header files using trace macros. # c_pathname_pat = re.compile( '^.*\.[ch]$', re.IGNORECASE ) trace_use_pat = re.compile( '^[ \t]*#define[ \t]+FT_COMPONENT[ \t]+trace_' ) for d in SRC_FILE_DIRS: for ( p, dlst, flst ) in os.walk( d ): for f in flst: if c_pathname_pat.match( f ) != None: src_pathname = os.path.join( p, f ) line_num = 0 for src_line in open( src_pathname, 'r' ): line_num = line_num + 1 src_line = src_line.strip() if trace_use_pat.match( src_line ) != None: component_name = trace_use_pat.sub( '', src_line ) if component_name in USED_COMPONENT: USED_COMPONENT[component_name].append( "%s:%d" % ( src_pathname, line_num ) ) else: USED_COMPONENT[component_name] = [ "%s:%d" % ( src_pathname, line_num ) ] # -------------------------------------------------------------- # Scan header file(s) defining trace macros. # trace_def_pat_opn = re.compile( '^.*FT_TRACE_DEF[ \t]*\([ \t]*' ) trace_def_pat_cls = re.compile( '[ \t\)].*$' ) for f in TRACE_DEF_FILES: line_num = 0 for hdr_line in open( f, 'r' ): line_num = line_num + 1 hdr_line = hdr_line.strip() if trace_def_pat_opn.match( hdr_line ) != None: component_name = trace_def_pat_opn.sub( '', hdr_line ) component_name = trace_def_pat_cls.sub( '', component_name ) if component_name in KNOWN_COMPONENT: print "trace component %s is defined twice, see %s and fttrace.h:%d" % \ ( component_name, KNOWN_COMPONENT[component_name], line_num ) else: KNOWN_COMPONENT[component_name] = "%s:%d" % \ ( os.path.basename( f ), line_num ) # -------------------------------------------------------------- # Compare the used and defined trace macros. # print "# Trace component used in the implementations but not defined in fttrace.h." cmpnt = USED_COMPONENT.keys() cmpnt.sort() for c in cmpnt: if c not in KNOWN_COMPONENT: print "Trace component %s (used in %s) is not defined." % ( c, ", ".join( USED_COMPONENT[c] ) ) print "# Trace component is defined but not used in the implementations." cmpnt = KNOWN_COMPONENT.keys() cmpnt.sort() for c in cmpnt: if c not in USED_COMPONENT: if c != "any": print "Trace component %s (defined in %s) is not used." % ( c, KNOWN_COMPONENT[c] )
dharmabumstead/ansible
refs/heads/devel
lib/ansible/module_utils/mysql.py
114
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # Copyright (c), Jonathan Mainguy <jon@soh.re>, 2015 # Most of this was originally added by Sven Schliesing @muffl0n in the mysql_user.py module # 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. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os try: import MySQLdb mysqldb_found = True except ImportError: mysqldb_found = False def mysql_connect(module, login_user=None, login_password=None, config_file='', ssl_cert=None, ssl_key=None, ssl_ca=None, db=None, cursor_class=None, connect_timeout=30): config = {} if ssl_ca is not None or ssl_key is not None or ssl_cert is not None: config['ssl'] = {} if module.params['login_unix_socket']: config['unix_socket'] = module.params['login_unix_socket'] else: config['host'] = module.params['login_host'] config['port'] = module.params['login_port'] if os.path.exists(config_file): config['read_default_file'] = config_file # If login_user or login_password are given, they should override the # config file if login_user is not None: config['user'] = login_user if login_password is not None: config['passwd'] = login_password if ssl_cert is not None: config['ssl']['cert'] = ssl_cert if ssl_key is not None: config['ssl']['key'] = ssl_key if ssl_ca is not None: config['ssl']['ca'] = ssl_ca if db is not None: config['db'] = db if connect_timeout is not None: config['connect_timeout'] = connect_timeout db_connection = MySQLdb.connect(**config) if cursor_class is not None: return db_connection.cursor(cursorclass=MySQLdb.cursors.DictCursor) else: return db_connection.cursor()
samabhi/pstHealth
refs/heads/master
venv/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/inject_meta_charset.py
1730
from __future__ import absolute_import, division, unicode_literals from . import _base class Filter(_base.Filter): def __init__(self, source, encoding): _base.Filter.__init__(self, source) self.encoding = encoding def __iter__(self): state = "pre_head" meta_found = (self.encoding is None) pending = [] for token in _base.Filter.__iter__(self): type = token["type"] if type == "StartTag": if token["name"].lower() == "head": state = "in_head" elif type == "EmptyTag": if token["name"].lower() == "meta": # replace charset with actual encoding has_http_equiv_content_type = False for (namespace, name), value in token["data"].items(): if namespace is not None: continue elif name.lower() == 'charset': token["data"][(namespace, name)] = self.encoding meta_found = True break elif name == 'http-equiv' and value.lower() == 'content-type': has_http_equiv_content_type = True else: if has_http_equiv_content_type and (None, "content") in token["data"]: token["data"][(None, "content")] = 'text/html; charset=%s' % self.encoding meta_found = True elif token["name"].lower() == "head" and not meta_found: # insert meta into empty head yield {"type": "StartTag", "name": "head", "data": token["data"]} yield {"type": "EmptyTag", "name": "meta", "data": {(None, "charset"): self.encoding}} yield {"type": "EndTag", "name": "head"} meta_found = True continue elif type == "EndTag": if token["name"].lower() == "head" and pending: # insert meta into head (if necessary) and flush pending queue yield pending.pop(0) if not meta_found: yield {"type": "EmptyTag", "name": "meta", "data": {(None, "charset"): self.encoding}} while pending: yield pending.pop(0) meta_found = True state = "post_head" if state == "in_head": pending.append(token) else: yield token
littlezz/pyspider
refs/heads/master
pyspider/fetcher/cookie_utils.py
69
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<roy@binux.me> # http://binux.me # Created on 2014-12-14 09:07:11 from requests.cookies import MockRequest class MockResponse(object): def __init__(self, headers): self._headers = headers def info(self): return self def getheaders(self, name): """make cookie python 2 version use this method to get cookie list""" return self._headers.get_list(name) def get_all(self, name, default=[]): """make cookie python 3 version use this instead of getheaders""" return self._headers.get_list(name) or default def extract_cookies_to_jar(jar, request, response): req = MockRequest(request) res = MockResponse(response) jar.extract_cookies(res, req)
Strassengezwitscher/Strassengezwitscher
refs/heads/develop
crowdgezwitscher/events/views.py
1
from django.contrib.auth.mixins import PermissionRequiredMixin from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import DeleteView from django.urls import reverse_lazy from extra_views import CreateWithInlinesView, UpdateWithInlinesView from events.models import Event from events.forms import EventForm, AttachmentFormSet class EventListView(PermissionRequiredMixin, ListView): permission_required = 'events.view_event' model = Event template_name = 'events/list.html' context_object_name = 'events' ordering = '-date' class EventDetail(PermissionRequiredMixin, DetailView): permission_required = 'events.view_event' model = Event template_name = 'events/detail.html' context_object_name = 'event' class EventCreate(PermissionRequiredMixin, CreateWithInlinesView): permission_required = 'events.add_event' model = Event inlines = [AttachmentFormSet] template_name = 'events/form.html' form_class = EventForm class EventUpdate(PermissionRequiredMixin, UpdateWithInlinesView): permission_required = 'events.change_event' model = Event inlines = [AttachmentFormSet] template_name = 'events/form.html' form_class = EventForm class EventDelete(PermissionRequiredMixin, DeleteView): permission_required = 'events.delete_event' model = Event template_name = 'events/delete.html' success_url = reverse_lazy('events:list') context_object_name = 'event'
tal-nino/shinken
refs/heads/master
test/test_complex_hostgroups.py
18
#!/usr/bin/env python # Copyright (C) 2009-2014: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # # This file is part of Shinken. # # Shinken 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. # # Shinken 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 Shinken. If not, see <http://www.gnu.org/licenses/>. # # This file is used to test reading and processing of config files # from shinken_test import * class TestComplexHostgroups(ShinkenTest): def setUp(self): self.setup_with_file('etc/shinken_complex_hostgroups.cfg') def get_svc(self): return self.sched.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0") def find_service(self, name, desc): return self.sched.services.find_srv_by_name_and_hostname(name, desc) def find_host(self, name): return self.sched.hosts.find_by_name(name) def find_hostgroup(self, name): return self.sched.hostgroups.find_by_name(name) def dump_hosts(self, svc): for h in svc.host_name: print h # check if service exist in hst, but NOT in others def srv_define_only_on(self, desc, hsts): r = True # first hsts for h in hsts: svc = self.find_service(h.host_name, desc) if svc is None: print "Error: the host %s is missing service %s!!" % (h.host_name, desc) r = False for h in self.sched.hosts: if h not in hsts: svc = self.find_service(h.host_name, desc) if svc is not None: print "Error: the host %s got the service %s!!" % (h.host_name, desc) r = False return r def test_complex_hostgroups(self): print self.sched.services.items svc = self.get_svc() print "Service", svc #print self.conf.hostgroups # All our hosts test_linux_web_prod_0 = self.find_host('test_linux_web_prod_0') test_linux_web_qual_0 = self.find_host('test_linux_web_qual_0') test_win_web_prod_0 = self.find_host('test_win_web_prod_0') test_win_web_qual_0 = self.find_host('test_win_web_qual_0') test_linux_file_prod_0 = self.find_host('test_linux_file_prod_0') hg_linux = self.find_hostgroup('linux') hg_web = self.find_hostgroup('web') hg_win = self.find_hostgroup('win') hg_file = self.find_hostgroup('file') print "HG Linux", hg_linux for h in hg_linux: print "H", h.get_name() self.assertIn(test_linux_web_prod_0, hg_linux.members) self.assertNotIn(test_linux_web_prod_0, hg_file.members) # First the service define for linux only svc = self.find_service('test_linux_web_prod_0', 'linux_0') print "Service Linux only", svc.get_dbg_name() r = self.srv_define_only_on('linux_0', [test_linux_web_prod_0, test_linux_web_qual_0, test_linux_file_prod_0]) self.assertEqual(True, r) print "Service Linux,web" r = self.srv_define_only_on('linux_web_0', [test_linux_web_prod_0, test_linux_web_qual_0, test_linux_file_prod_0, test_win_web_prod_0, test_win_web_qual_0]) self.assertEqual(True, r) ### Now the real complex things :) print "Service Linux&web" r = self.srv_define_only_on('linux_AND_web_0', [test_linux_web_prod_0, test_linux_web_qual_0]) self.assertEqual(True, r) print "Service Linux|web" r = self.srv_define_only_on('linux_OR_web_0', [test_linux_web_prod_0, test_linux_web_qual_0, test_win_web_prod_0, test_win_web_qual_0, test_linux_file_prod_0]) self.assertEqual(True, r) print "(linux|web),file" r = self.srv_define_only_on('linux_OR_web_PAR_file0', [test_linux_web_prod_0, test_linux_web_qual_0, test_win_web_prod_0, test_win_web_qual_0, test_linux_file_prod_0, test_linux_file_prod_0]) self.assertEqual(True, r) print "(linux|web)&prod" r = self.srv_define_only_on('linux_OR_web_PAR_AND_prod0', [test_linux_web_prod_0, test_win_web_prod_0, test_linux_file_prod_0]) self.assertEqual(True, r) print "(linux|web)&(*&!prod)" r = self.srv_define_only_on('linux_OR_web_PAR_AND_NOT_prod0', [test_linux_web_qual_0, test_win_web_qual_0]) self.assertEqual(True, r) print "Special minus problem" r = self.srv_define_only_on('name-with-minus-in-it', [test_linux_web_prod_0]) self.assertEqual(True, r) print "(linux|web)&prod AND not test_linux_file_prod_0" r = self.srv_define_only_on('linux_OR_web_PAR_AND_prod0_AND_NOT_test_linux_file_prod_0', [test_linux_web_prod_0, test_win_web_prod_0]) self.assertEqual(True, r) print "win&((linux|web)&prod) AND not test_linux_file_prod_0" r = self.srv_define_only_on('WINDOWS_AND_linux_OR_web_PAR_AND_prod0_AND_NOT_test_linux_file_prod_0', [test_win_web_prod_0]) self.assertEqual(True, r) if __name__ == '__main__': unittest.main()
CSC301H-Fall2013/JuakStore
refs/heads/master
site-packages/tests/regressiontests/admin_scripts/complex_app/models/bar.py
153
from __future__ import absolute_import from django.db import models from ..admin import foo class Bar(models.Model): name = models.CharField(max_length=5) class Meta: app_label = 'complex_app'
rpavlik/lyx-lucid-backport
refs/heads/master
lib/scripts/lyxpreview_tools.py
1
#! /usr/bin/env python # file lyxpreview_tools.py # This file is part of LyX, the document processor. # Licence details can be found in the file COPYING. # author Angus Leeming # Full author contact details are available in file CREDITS # and with much help testing the code under Windows from # Paul A. Rubin, rubin@msu.edu. # A repository of the following functions, used by the lyxpreview2xyz scripts. # copyfileobj, error, find_exe, find_exe_or_terminate, make_texcolor, mkstemp, # run_command, warning import os, re, string, sys, tempfile use_win32_modules = 0 if os.name == "nt": use_win32_modules = 1 try: import pywintypes import win32con import win32event import win32file import win32pipe import win32process import win32security import winerror except: sys.stderr.write("Consider installing the PyWin extension modules "\ "if you're irritated by windows appearing briefly.\n") use_win32_modules = 0 def warning(message): sys.stderr.write(message + '\n') def error(message): sys.stderr.write(message + '\n') sys.exit(1) def make_texcolor(hexcolor, graphics): # Test that the input string contains 6 hexadecimal chars. hexcolor_re = re.compile("^[0-9a-fA-F]{6}$") if not hexcolor_re.match(hexcolor): error("Cannot convert color '%s'" % hexcolor) red = float(string.atoi(hexcolor[0:2], 16)) / 255.0 green = float(string.atoi(hexcolor[2:4], 16)) / 255.0 blue = float(string.atoi(hexcolor[4:6], 16)) / 255.0 if graphics: return "%f,%f,%f" % (red, green, blue) else: return "rgb %f %f %f" % (red, green, blue) def find_exe(candidates, path): extlist = [''] if "PATHEXT" in os.environ: extlist = extlist + os.environ["PATHEXT"].split(os.pathsep) for prog in candidates: for directory in path: for ext in extlist: full_path = os.path.join(directory, prog + ext) if os.access(full_path, os.X_OK): # The thing is in the PATH already (or we wouldn't # have found it). Return just the basename to avoid # problems when the path to the executable contains # spaces. return os.path.basename(full_path) return None def find_exe_or_terminate(candidates, path): exe = find_exe(candidates, path) if exe == None: error("Unable to find executable from '%s'" % string.join(candidates)) return exe def run_command_popen(cmd): handle = os.popen(cmd, 'r') cmd_stdout = handle.read() cmd_status = handle.close() return cmd_status, cmd_stdout def run_command_win32(cmd): sa = win32security.SECURITY_ATTRIBUTES() sa.bInheritHandle = True stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0) si = win32process.STARTUPINFO() si.dwFlags = (win32process.STARTF_USESTDHANDLES | win32process.STARTF_USESHOWWINDOW) si.wShowWindow = win32con.SW_HIDE si.hStdOutput = stdout_w process, thread, pid, tid = \ win32process.CreateProcess(None, cmd, None, None, True, 0, None, None, si) if process == None: return -1, "" # Must close the write handle in this process, or ReadFile will hang. stdout_w.Close() # Read the pipe until we get an error (including ERROR_BROKEN_PIPE, # which is okay because it happens when child process ends). data = "" error = 0 while 1: try: hr, buffer = win32file.ReadFile(stdout_r, 4096) if hr != winerror.ERROR_IO_PENDING: data = data + buffer except pywintypes.error, e: if e.args[0] != winerror.ERROR_BROKEN_PIPE: error = 1 break if error: return -2, "" # Everything is okay --- the called process has closed the pipe. # For safety, check that the process ended, then pick up its exit code. win32event.WaitForSingleObject(process, win32event.INFINITE) if win32process.GetExitCodeProcess(process): return -3, "" return None, data def run_command(cmd): if use_win32_modules: return run_command_win32(cmd) else: return run_command_popen(cmd) def get_version_info(): version_re = re.compile("([0-9])\.([0-9])") match = version_re.match(sys.version) if match == None: error("Unable to extract version info from 'sys.version'") return string.atoi(match.group(1)), string.atoi(match.group(2)) def copyfileobj(fsrc, fdst, rewind=0, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" if rewind: fsrc.flush() fsrc.seek(0) while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf) class TempFile: """clone of tempfile.TemporaryFile to use with python < 2.0.""" # Cache the unlinker so we don't get spurious errors at shutdown # when the module-level "os" is None'd out. Note that this must # be referenced as self.unlink, because the name TempFile # may also get None'd out before __del__ is called. unlink = os.unlink def __init__(self): self.filename = tempfile.mktemp() self.file = open(self.filename,"w+b") self.close_called = 0 def close(self): if not self.close_called: self.close_called = 1 self.file.close() self.unlink(self.filename) def __del__(self): self.close() def read(self, size = -1): return self.file.read(size) def write(self, line): return self.file.write(line) def seek(self, offset): return self.file.seek(offset) def flush(self): return self.file.flush() def mkstemp(): """create a secure temporary file and return its object-like file""" major, minor = get_version_info() if major >= 2 and minor >= 0: return tempfile.TemporaryFile() else: return TempFile() def write_metrics_info(metrics_info, metrics_file): metrics = open(metrics_file, 'w') for metric in metrics_info: metrics.write("Snippet %s %f\n" % metric) metrics.close() # Reads a .tex files and create an identical file but only with # pages whose index is in pages_to_keep def filter_pages(source_path, destination_path, pages_to_keep): source_file = open(source_path, "r") destination_file = open(destination_path, "w") page_index = 0 skip_page = False for line in source_file: # We found a new page if line.startswith("\\begin{preview}"): page_index += 1 # If the page index isn't in pages_to_keep we don't copy it skip_page = page_index not in pages_to_keep if not skip_page: destination_file.write(line) # End of a page, we reset the skip_page bool if line.startswith("\\end{preview}"): skip_page = False destination_file.close() source_file.close() # Joins two metrics list, that is a list of tuple (page_index, metric) # new_page_indexes contains the original page number of the pages in new_metrics # e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting # original_bitmap and destination_bitmap are file name models used to rename the new files # e.g. image_new%d.png and image_%d.png def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap): legacy_index = 0 for (index, metric) in new_metrics: # If the file exists we rename it if os.path.isfile(original_bitmap % (index)): os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1]) # Extract the original page index index = new_page_indexes[index-1] # Goes through the array until the end is reached or the correct index is found while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index: legacy_index += 1 # Add or update the metric for this page if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index: original_metrics[legacy_index] = (index, metric) else: original_metrics.insert(legacy_index, (index, metric))
AppNearMe/micronfcboard-python
refs/heads/master
micronfcboard/interface/interface.py
3
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2013 ARM Limited 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. """ class Interface(object): def __init__(self): self.vid = 0 self.pid = 0 self.vendor_name = "" self.product_name = "" return def init(self): return def write(self, data): return def read(self, size = -1, timeout = -1): return def getInfo(self): return self.vendor_name + " " + \ self.product_name + " (" + \ str(hex(self.vid)) + ", " + \ str(hex(self.pid)) + ")" def close(self): return
r0x0r/pywebview
refs/heads/master
tests/run.py
1
import os import pytest if __name__ == '__main__': pytest.main(['-s'])