repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
yinquan529/platform-external-chromium_org
chrome/test/pyautolib/chrome_driver_factory.py
79
2664
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Factory that creates ChromeDriver instances for pyauto.""" import os import random import tempfile import pyauto_paths from selenium import webdriver from selenium.webdriver.chrome import service class ChromeDriverFactory(object): """"Factory that creates ChromeDriver instances for pyauto. Starts a single ChromeDriver server when necessary. Users should call 'Stop' when no longer using the factory. """ def __init__(self, port=0): """Initialize ChromeDriverFactory. Args: port: The port for WebDriver to use; by default the service will select a free port. """ self._chromedriver_port = port self._chromedriver_server = None def NewChromeDriver(self, pyauto): """Creates a new remote WebDriver instance. This instance will connect to a new automation provider of an already running Chrome. Args: pyauto: pyauto.PyUITest instance Returns: selenium.webdriver.remote.webdriver.WebDriver instance. """ if pyauto.IsChromeOS(): os.putenv('DISPLAY', ':0.0') os.putenv('XAUTHORITY', '/home/chronos/.Xauthority') self._StartServerIfNecessary() channel_id = 'testing' + hex(random.getrandbits(20 * 4))[2:-1] if not pyauto.IsWin(): channel_id = os.path.join(tempfile.gettempdir(), channel_id) pyauto.CreateNewAutomationProvider(channel_id) return webdriver.Remote(self._chromedriver_server.service_url, {'chrome.channel': channel_id, 'chrome.noWebsiteTestingDefaults': True}) def _StartServerIfNecessary(self): """Starts the ChromeDriver server, if not already started.""" if self._chromedriver_server is None: exe = pyauto_paths.GetChromeDriverExe() assert exe, 'Cannot find chromedriver exe. Did you build it?' self._chromedriver_server = service.Service(exe, self._chromedriver_port) self._chromedriver_server.start() def Stop(self): """Stops the ChromeDriver server, if running.""" if self._chromedriver_server is not None: self._chromedriver_server.stop() self._chromedriver_server = None def GetPort(self): """Gets the port ChromeDriver is set to use. Returns: The port all ChromeDriver instances returned from NewChromeDriver() will be listening on. A return value of 0 indicates the ChromeDriver service will select a free port. """ return self._chromedriver_port def __del__(self): self.Stop()
bsd-3-clause
JacobJacob/pyew
vstruct/defs/macho/const.py
26
12741
# Fat Defines... FAT_MAGIC = 0xcafebabe FAT_CIGAM = 0xbebafeca #NXSwapLong(FAT_MAGIC) MH_MAGIC = 0xfeedface # the mach magic number MH_CIGAM = 0xcefaedfe # NXSwapInt(MH_MAGIC) MH_MAGIC_64 = 0xfeedfacf # the 64-bit mach magic number MH_CIGAM_64 = 0xcffaedfe # NXSwapInt(MH_MAGIC_64) MH_OBJECT = 0x1 # relocatable object file MH_EXECUTE = 0x2 # demand paged executable file MH_FVMLIB = 0x3 # fixed VM shared library file MH_CORE = 0x4 # core file MH_PRELOAD = 0x5 # preloaded executable file MH_DYLIB = 0x6 # dynamically bound shared library MH_DYLINKER = 0x7 # dynamic link editor MH_BUNDLE = 0x8 # dynamically bound bundle file MH_DYLIB_STUB = 0x9 # shared library stub for static MH_DSYM = 0xa # companion file with only debug MH_NOUNDEFS = 0x1 # the object file has no undefinedreferences MH_INCRLINK = 0x2 # the object file is the output of anincremental link against a base fileand can't be link edited again MH_DYLDLINK = 0x4 # the object file is input for thedynamic linker and can't be staticlylink edited again MH_BINDATLOAD = 0x8 # the object file's undefinedreferences are bound by the dynamiclinker when loaded. MH_PREBOUND = 0x10 # the file has its dynamic undefinedreferences prebound. MH_SPLIT_SEGS = 0x20 # the file has its read-only andread-write segments split MH_LAZY_INIT = 0x40 # the shared library init routine isto be run lazily via catching memoryfaults to its writeable segments(obsolete) MH_TWOLEVEL = 0x80 # the image is using two-level namespace bindings MH_FORCE_FLAT = 0x100 # the executable is forcing all imagesto use flat name space bindings MH_NOMULTIDEFS = 0x200 # this umbrella guarantees no multipledefintions of symbols in itssub-images so the two-level namespacehints can always be used. MH_NOFIXPREBINDING = 0x400 # do not have dyld notify theprebinding agent about thisexecutable MH_PREBINDABLE = 0x800 # the binary is not prebound but canhave its prebinding redone. only usedwhen MH_PREBOUND is not set. MH_ALLMODSBOUND = 0x1000 # this binary binds toall two-level namespace modules ofits dependent libraries. only usedwhen MH_PREBINDABLE and MH_TWOLEVELare both set. MH_CANONICAL = 0x4000 # the binary has been canonicalizedvia the unprebind operation MH_WEAK_DEFINES = 0x8000 # the final linked image containsexternal weak symbols MH_BINDS_TO_WEAK = 0x10000 # the final linked image usesweak symbols MH_ROOT_SAFE = 0x40000 # When this bit is set, the binarydeclares it is safe for use inprocesses with uid zero MH_SETUID_SAFE = 0x80000 # When this bit is set, the binarydeclares it is safe for use inprocesses when issetugid() is true MH_NO_REEXPORTED_DYLIBS = 0x100000 # When this bit is set on a dylib,the static linker does not need toexamine dependent dylibs to seeif any are re-exported MH_PIE = 0x200000 # When this bit is set, the OS willload the main executable at arandom address. Only used inMH_EXECUTE filetypes. # Constants for the cmd field of all load commands, the type LC_REQ_DYLD = 0x80000000 # When this bit is set, the OS willload the main executable at arandom address. Only used inMH_EXECUTE filetypes. LC_SEGMENT = 0x1 # segment of this file to be mapped LC_SYMTAB = 0x2 # link-edit stab symbol table info LC_SYMSEG = 0x3 # link-edit gdb symbol table info (obsolete) LC_THREAD = 0x4 # thread LC_UNIXTHREAD = 0x5 # unix thread (includes a stack) LC_LOADFVMLIB = 0x6 # load a specified fixed VM shared library LC_IDFVMLIB = 0x7 # fixed VM shared library identification LC_IDENT = 0x8 # object identification info (obsolete) LC_FVMFILE = 0x9 # fixed VM file inclusion (internal use) LC_PREPAGE = 0xa # prepage command (internal use) LC_DYSYMTAB = 0xb # dynamic link-edit symbol table info LC_LOAD_DYLIB = 0xc # load a dynamically linked shared library LC_ID_DYLIB = 0xd # dynamically linked shared lib ident LC_LOAD_DYLINKER = 0xe # load a dynamic linker LC_ID_DYLINKER = 0xf # dynamic linker identification LC_PREBOUND_DYLIB = 0x10 # modules prebound for a dynamically LC_ROUTINES = 0x11 # image routines LC_SUB_FRAMEWORK = 0x12 # sub framework LC_SUB_UMBRELLA = 0x13 # sub umbrella LC_SUB_CLIENT = 0x14 # sub client LC_SUB_LIBRARY = 0x15 # sub library LC_TWOLEVEL_HINTS = 0x16 # two-level namespace lookup hints LC_PREBIND_CKSUM = 0x17 # prebind checksum LC_SEGMENT_64 = 0x19 # 64-bit segment of this file to bemapped LC_ROUTINES_64 = 0x1a # 64-bit image routines LC_UUID = 0x1b # the uuid LC_CODE_SIGNATURE = 0x1d # local of code signature LC_SEGMENT_SPLIT_INFO = 0x1e # local of info to split segments LC_LAZY_LOAD_DYLIB = 0x20 # delay load of dylib until first use LC_ENCRYPTION_INFO = 0x21 # encrypted segment information LC_DYLD_INFO = 0x22 # compressed dyld information SG_HIGHVM = 0x1 # the file contents for this segment is forthe high part of the VM space, the low partis zero filled (for stacks in core files) SG_FVMLIB = 0x2 # this segment is the VM that is allocated bya fixed VM library, for overlap checking inthe link editor SG_NORELOC = 0x4 # this segment has nothing that was relocatedin it and nothing relocated to it, that isit maybe safely replaced without relocation SG_PROTECTED_VERSION_1 = 0x8 # This segment is protected. If thesegment starts at file offset 0, thefirst page of the segment is notprotected. All other pages of thesegment are protected. SECTION_TYPE = 0x000000ff # 256 section types SECTION_ATTRIBUTES = 0xffffff00 # 24 section attributes S_REGULAR = 0x0 # regular section S_ZEROFILL = 0x1 # zero fill on demand section S_CSTRING_LITERALS = 0x2 # section with only literal C strings S_4BYTE_LITERALS = 0x3 # section with only 4 byte literals S_8BYTE_LITERALS = 0x4 # section with only 8 byte literals S_LITERAL_POINTERS = 0x5 # section with only pointers to S_NON_LAZY_SYMBOL_POINTERS = 0x6 # section with only non-lazysymbol pointers S_LAZY_SYMBOL_POINTERS = 0x7 # section with only lazy symbolpointers S_SYMBOL_STUBS = 0x8 # section with only symbolstubs, byte size of stub inthe reserved2 field S_MOD_INIT_FUNC_POINTERS = 0x9 # section with only functionpointers for initialization S_MOD_TERM_FUNC_POINTERS = 0xa # section with only functionpointers for termination S_COALESCED = 0xb # section contains symbols thatare to be coalesced S_GB_ZEROFILL = 0xc # zero fill on demand section(that can be larger than 4gigabytes) S_INTERPOSING = 0xd # section with only pairs offunction pointers forinterposing S_16BYTE_LITERALS = 0xe # section with only 16 byteliterals S_DTRACE_DOF = 0xf # section containsDTrace Object Format S_LAZY_DYLIB_SYMBOL_POINTERS = 0x10 # section with only lazysymbol pointers to lazyloaded dylibs SECTION_ATTRIBUTES_USR = 0xff000000 # User setable attributes S_ATTR_PURE_INSTRUCTIONS = 0x80000000 # section contains only truemachine instructions S_ATTR_NO_TOC = 0x40000000 # section contains coalescedsymbols that are not to bein a ranlib table ofcontents S_ATTR_STRIP_STATIC_SYMS = 0x20000000 # ok to strip static symbolsin this section in fileswith the MH_DYLDLINK flag S_ATTR_NO_DEAD_STRIP = 0x10000000 # no dead stripping S_ATTR_LIVE_SUPPORT = 0x08000000 # blocks are live if theyreference live blocks S_ATTR_SELF_MODIFYING_CODE = 0x04000000 # Used with i386 code stubswritten on by dyld S_ATTR_DEBUG = 0x02000000 # a debug section SECTION_ATTRIBUTES_SYS = 0x00ffff00 # system setable attributes S_ATTR_SOME_INSTRUCTIONS = 0x00000400 # section contains somemachine instructions S_ATTR_EXT_RELOC = 0x00000200 # section has externalrelocation entries S_ATTR_LOC_RELOC = 0x00000100 # section has localrelocation entries INDIRECT_SYMBOL_LOCAL = 0x80000000 # section has localrelocation entries INDIRECT_SYMBOL_ABS = 0x40000000 # section has localrelocation entries CPU_TYPE_ANY = -1 CPU_TYPE_VAX = 1 CPU_TYPE_MC680 = 6 CPU_TYPE_X86 = 7 CPU_TYPE_X86_64 = 0x01000007 CPU_TYPE_MIPS = 8 CPU_TYPE_MC98000 = 10 CPU_TYPE_HPPA = 11 CPU_TYPE_ARM = 12 CPU_TYPE_MC88000 = 13 CPU_TYPE_SPARC = 14 CPU_TYPE_I860 = 15 CPU_TYPE_ALPHA = 16 CPU_TYPE_POWERPC = 18 #CPU_TYPE_POWERPC64 (CPU_TYPE_POWERPC | CPU_ARCH_ABI64) mach_cpu_names = { CPU_TYPE_VAX : 'vax', CPU_TYPE_MC680 : 'mc680', CPU_TYPE_X86 : 'i386', CPU_TYPE_X86_64 : 'amd64', CPU_TYPE_MIPS : 'mips', CPU_TYPE_MC98000 : 'mc98000', CPU_TYPE_HPPA : 'hppa', CPU_TYPE_ARM : 'arm', CPU_TYPE_MC88000 : 'mc88000', CPU_TYPE_SPARC : 'sparc', CPU_TYPE_I860 : 'i860', CPU_TYPE_ALPHA : 'alpha', CPU_TYPE_POWERPC : 'powerpc', } # Symbol types N_GSYM = 0x20 # global symbol: name,,NO_SECT,type,0 N_FNAME = 0x22 # procedure name (f77 kludge): name,,NO_SECT,0,0 N_FUN = 0x24 # procedure: name,,n_sect,linenumber,address N_STSYM = 0x26 # static symbol: name,,n_sect,type,address N_LCSYM = 0x28 # .lcomm symbol: name,,n_sect,type,address N_BNSYM = 0x2e # begin nsect sym: 0,,n_sect,0,address N_PC = 0x30 # global pascal symbol: name,,NO_SECT,subtype,line N_OPT = 0x3c # emitted with gcc2_compile and in gcc source N_RSYM = 0x40 # register sym: name,,NO_SECT,type,register N_SLINE = 0x44 # src line: 0,,n_sect,linenumber,address N_ENSYM = 0x4e # end nsect sym: 0,,n_sect,0,address N_SSYM = 0x60 # struct elt: name,,NO_SECT,type,struct_offset N_SO = 0x64 # source file name: name,,n_sect,0,address N_LSYM = 0x80 # local sym: name,,NO_SECT,type,offset N_BINCL = 0x82 # include file beginning: name,,NO_SECT,0,sum N_SOL = 0x84 # #included file name: name,,n_sect,0,address N_PARAMS = 0x86 # compiler parameters: name,,NO_SECT,0,0 N_VERSION = 0x88 # compiler version: name,,NO_SECT,0,0 N_OLEVEL = 0x8A # compiler -O level: name,,NO_SECT,0,0 N_PSYM = 0xA0 # parameter: name,,NO_SECT,type,offset N_EINCL = 0xA2 # include file end: name,,NO_SECT,0,0 N_ENTRY = 0xA4 # alternate entry: name,,n_sect,linenumber,address N_LBRAC = 0xC0 # left bracket: 0,,NO_SECT,nesting level,address N_EXCL = 0xC2 # deleted include file: name,,NO_SECT,0,sum N_RBRAC = 0xE0 # right bracket: 0,,NO_SECT,nesting level,address N_BCOMM = 0xE2 # begin common: name,,NO_SECT,0,0 N_ECOMM = 0xE4 # end common: name,,n_sect,0,0 N_ECOML = 0xE8 # end common (local name): 0,,n_sect,0,address N_LENG = 0xFE # second stab entry with length information # The n_type field really contains four fields: # unsigned char N_STAB:3, # N_PEXT:1, # N_TYPE:3, # N_EXT:1; N_STAB = 0xe0 # if any of these bits set, a symbolic debugging entry N_PEXT = 0x10 # private external symbol bit N_TYPE = 0x0e # mask for the type bits N_EXT = 0x01 # external symbol bit, set for external symbols # Values for N_TYPE bits of the n_type field. N_UNDF = 0x0 # undefined, n_sect == NO_SECT N_ABS = 0x2 # absolute, n_sect == NO_SECT N_SECT = 0xe # defined in section number n_sect N_PBUD = 0xc # prebound undefined (defined in a dylib) N_INDR = 0xa # indirect
gpl-2.0
google-research/federated
gans/training_loops_test.py
1
6687
# Copyright 2018, Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from absl.testing import parameterized import tensorflow as tf import tensorflow_privacy from gans import gan_losses from gans import gan_training_tf_fns from gans import one_dim_gan from gans import tff_gans from gans import training_loops def _get_train_generator_and_discriminator_fns(): gan_loss_fns = gan_losses.get_gan_loss_fns('wasserstein') train_generator_fn = gan_training_tf_fns.create_train_generator_fn( gan_loss_fns, tf.keras.optimizers.Adam()) train_discriminator_fn = gan_training_tf_fns.create_train_discriminator_fn( gan_loss_fns, tf.keras.optimizers.Adam()) return train_generator_fn, train_discriminator_fn def _get_dp_average_query(): return tensorflow_privacy.NormalizedQuery( tensorflow_privacy.QuantileAdaptiveClipSumQuery( initial_l2_norm_clip=100.0, noise_multiplier=0.3, target_unclipped_quantile=3, learning_rate=0.1, clipped_count_stddev=0.0, expected_num_records=10), denominator=10.0) class TrainingLoopsTest(tf.test.TestCase, parameterized.TestCase): def test_simple_training(self): train_generator_fn, train_discriminator_fn = ( _get_train_generator_and_discriminator_fns()) server_state, _ = training_loops.simple_training_loop( generator_model_fn=one_dim_gan.create_generator, discriminator_model_fn=one_dim_gan.create_discriminator, real_data_fn=one_dim_gan.create_real_data, gen_inputs_fn=one_dim_gan.create_generator_inputs, train_generator_fn=train_generator_fn, train_discriminator_fn=train_discriminator_fn, total_rounds=2, client_disc_train_steps=2, server_gen_train_steps=3, rounds_per_eval=10) self.assertDictEqual( self.evaluate(server_state.counters), { 'num_rounds': 2, 'num_generator_train_examples': 2 * 3 * one_dim_gan.BATCH_SIZE, 'num_discriminator_train_examples': 2 * 2 * one_dim_gan.BATCH_SIZE }) @parameterized.named_parameters(('no_dp_and_checkpoint', None, True), ('dp', _get_dp_average_query(), False)) def test_tff_training_loop(self, dp_average_query, checkpoint): if checkpoint: root_checkpoint_dir = os.path.join(self.get_temp_dir(), 'checkpoints') else: root_checkpoint_dir = None train_generator_fn, train_discriminator_fn = ( _get_train_generator_and_discriminator_fns()) gan = tff_gans.GanFnsAndTypes( generator_model_fn=one_dim_gan.create_generator, discriminator_model_fn=one_dim_gan.create_discriminator, dummy_gen_input=next(iter(one_dim_gan.create_generator_inputs())), dummy_real_data=next(iter(one_dim_gan.create_real_data())), train_generator_fn=train_generator_fn, train_discriminator_fn=train_discriminator_fn, server_disc_update_optimizer_fn=lambda: tf.keras.optimizers.SGD(lr=1.0), train_discriminator_dp_average_query=dp_average_query) gen_inputs = one_dim_gan.create_generator_inputs() real_data = one_dim_gan.create_real_data() client_disc_train_steps = 2 server_gen_train_steps = 3 server_gen_inputs = iter(gen_inputs.window(server_gen_train_steps)) client_gen_inputs = iter(gen_inputs.window(client_disc_train_steps)) client_real_data = iter(real_data.window(client_disc_train_steps)) def server_gen_inputs_fn(_): return next(server_gen_inputs) num_clients = 2 def client_datasets_fn(_): return [(next(client_gen_inputs), next(client_real_data)) for _ in range(num_clients)] server_state, _ = training_loops.federated_training_loop( gan, server_gen_inputs_fn=server_gen_inputs_fn, client_datasets_fn=client_datasets_fn, total_rounds=2, rounds_per_checkpoint=1, root_checkpoint_dir=root_checkpoint_dir) self.assertDictEqual( server_state.counters, { 'num_rounds': 2, 'num_generator_train_examples': 2 * 3 * one_dim_gan.BATCH_SIZE, 'num_discriminator_train_examples': (2 * 2 * one_dim_gan.BATCH_SIZE * num_clients) }) if checkpoint: # TODO(b/141112101): We shouldn't need to re-create the gan, should be # able to reuse the instance from above. See comment inside tff_gans.py. train_generator_fn, train_discriminator_fn = ( _get_train_generator_and_discriminator_fns()) gan = tff_gans.GanFnsAndTypes( generator_model_fn=one_dim_gan.create_generator, discriminator_model_fn=one_dim_gan.create_discriminator, dummy_gen_input=next(iter(one_dim_gan.create_generator_inputs())), dummy_real_data=next(iter(one_dim_gan.create_real_data())), train_generator_fn=train_generator_fn, train_discriminator_fn=train_discriminator_fn, server_disc_update_optimizer_fn=lambda: tf.keras.optimizers.SGD(lr=1.0 ), train_discriminator_dp_average_query=dp_average_query) # Train one more round, which should resume from the checkpoint. server_state, _ = training_loops.federated_training_loop( gan, server_gen_inputs_fn=server_gen_inputs_fn, client_datasets_fn=client_datasets_fn, total_rounds=3, rounds_per_checkpoint=1, root_checkpoint_dir=root_checkpoint_dir) # Note: It would be better to return something from # federated_training_loop indicating the number of rounds trained in this # invocation, so we could verify the checkpoint was read. self.assertDictEqual( server_state.counters, { 'num_rounds': 3, 'num_generator_train_examples': 3 * 3 * one_dim_gan.BATCH_SIZE, 'num_discriminator_train_examples': (3 * 2 * one_dim_gan.BATCH_SIZE * num_clients) }) if __name__ == '__main__': tf.test.main()
apache-2.0
devincoughlin/swift
utils/gyb_syntax_support/AttributeNodes.py
2
8969
from Child import Child from Node import Node # noqa: I201 ATTRIBUTE_NODES = [ # token-list -> token? token-list? Node('TokenList', kind='SyntaxCollection', element='Token'), # token-list -> token token-list? Node('NonEmptyTokenList', kind='SyntaxCollection', element='Token', omit_when_empty=True), Node('CustomAttribute', kind='Syntax', description=''' A custom `@` attribute. ''', children=[ Child('AtSignToken', kind='AtSignToken', description='The `@` sign.'), Child('AttributeName', kind='Type', classification='Attribute', description='The name of the attribute.'), Child('LeftParen', kind='LeftParenToken', is_optional=True), Child('ArgumentList', kind='TupleExprElementList', collection_element_name='Argument', is_optional=True), Child('RightParen', kind='RightParenToken', is_optional=True), ]), # attribute -> '@' identifier '('? # ( identifier # | string-literal # | integer-literal # | availability-spec-list # | specialize-attr-spec-list # | implements-attr-arguments # | named-attribute-string-argument # )? ')'? Node('Attribute', kind='Syntax', description=''' An `@` attribute. ''', children=[ Child('AtSignToken', kind='AtSignToken', description='The `@` sign.'), Child('AttributeName', kind='Token', classification='Attribute', description='The name of the attribute.'), Child('LeftParen', kind='LeftParenToken', is_optional=True, description=''' If the attribute takes arguments, the opening parenthesis. '''), Child('Argument', kind='Syntax', is_optional=True, node_choices=[ Child('Identifier', kind='IdentifierToken'), Child('String', kind='StringLiteralToken'), Child('Integer', kind='IntegerLiteralToken'), Child('Availability', kind='AvailabilitySpecList'), Child('SpecializeArguments', kind='SpecializeAttributeSpecList'), Child('ObjCName', kind='ObjCSelector'), Child('ImplementsArguments', kind='ImplementsAttributeArguments'), Child('NamedAttributeString', kind='NamedAttributeStringArgument'), ], description=''' The arguments of the attribute. In case the attribute \ takes multiple arguments, they are gather in the \ appropriate takes first. '''), Child('RightParen', kind='RightParenToken', is_optional=True, description=''' If the attribute takes arguments, the closing parenthesis. '''), # TokenList to gather remaining tokens of invalid attributes # FIXME: Remove this recovery option entirely Child('TokenList', kind='TokenList', collection_element_name='Token', is_optional=True), ]), # attribute-list -> attribute attribute-list? Node('AttributeList', kind='SyntaxCollection', omit_when_empty=True, element='Syntax', element_name='Attribute', element_choices=[ 'Attribute', 'CustomAttribute', ]), # The argument of '@_specialize(...)' # specialize-attr-spec-list -> labeled-specialize-entry # specialize-spec-attr-list? # | generic-where-clause # specialize-spec-attr-list? Node('SpecializeAttributeSpecList', kind='SyntaxCollection', description=''' A collection of arguments for the `@_specialize` attribute ''', element='Syntax', element_name='SpecializeAttribute', element_choices=[ 'LabeledSpecializeEntry', 'GenericWhereClause', ]), # Representation of e.g. 'exported: true,' # labeled-specialize-entry -> identifier ':' token ','? Node('LabeledSpecializeEntry', kind='Syntax', description=''' A labeled argument for the `@_specialize` attribute like \ `exported: true` ''', traits=['WithTrailingComma'], children=[ Child('Label', kind='IdentifierToken', description='The label of the argument'), Child('Colon', kind='ColonToken', description='The colon separating the label and the value'), Child('Value', kind='Token', description='The value for this argument'), Child('TrailingComma', kind='CommaToken', is_optional=True, description=''' A trailing comma if this argument is followed by another one '''), ]), # The argument of '@_dynamic_replacement(for:)' or '@_private(sourceFile:)' # named-attribute-string-arg -> 'name': string-literal Node('NamedAttributeStringArgument', kind='Syntax', description=''' The argument for the `@_dynamic_replacement` or `@_private` \ attribute of the form `for: "function()"` or `sourceFile: \ "Src.swift"` ''', children=[ Child('NameTok', kind='Token', description='The label of the argument'), Child('Colon', kind='ColonToken', description='The colon separating the label and the value'), Child('StringOrDeclname', kind='Syntax', node_choices=[ Child('String', kind='StringLiteralToken'), Child('Declname', kind='DeclName'), ]), ]), Node('DeclName', kind='Syntax', children=[ Child('DeclBaseName', kind='Syntax', description=''' The base name of the protocol\'s requirement. ''', node_choices=[ Child('Identifier', kind='IdentifierToken'), Child('Operator', kind='PrefixOperatorToken'), ]), Child('DeclNameArguments', kind='DeclNameArguments', is_optional=True, description=''' The argument labels of the protocol\'s requirement if it \ is a function requirement. '''), ]), # The argument of '@_implements(...)' # implements-attr-arguments -> simple-type-identifier ',' # (identifier | operator) decl-name-arguments Node('ImplementsAttributeArguments', kind='Syntax', description=''' The arguments for the `@_implements` attribute of the form \ `Type, methodName(arg1Label:arg2Label:)` ''', children=[ Child('Type', kind='SimpleTypeIdentifier', description=''' The type for which the method with this attribute \ implements a requirement. '''), Child('Comma', kind='CommaToken', description=''' The comma separating the type and method name '''), Child('DeclBaseName', kind='Syntax', description=''' The base name of the protocol\'s requirement. ''', node_choices=[ Child('Identifier', kind='IdentifierToken'), Child('Operator', kind='PrefixOperatorToken'), ]), Child('DeclNameArguments', kind='DeclNameArguments', is_optional=True, description=''' The argument labels of the protocol\'s requirement if it \ is a function requirement. '''), ]), # objc-selector-piece -> identifier? ':'? Node('ObjCSelectorPiece', kind='Syntax', description=''' A piece of an Objective-C selector. Either consisiting of just an \ identifier for a nullary selector, an identifier and a colon for a \ labeled argument or just a colon for an unlabeled argument ''', children=[ Child('Name', kind='IdentifierToken', is_optional=True), Child('Colon', kind='ColonToken', is_optional=True), ]), # objc-selector -> objc-selector-piece objc-selector? Node('ObjCSelector', kind='SyntaxCollection', element='ObjCSelectorPiece') ]
apache-2.0
cernops/oz
oz/Mageia.py
5
4964
# Copyright (C) 2013 Chris Lalancette <clalancette@gmail.com> # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; # version 2.1 of the License. # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """ Mageia installation """ import shutil import os import re import oz.Guest import oz.ozutil import oz.OzException class MageiaGuest(oz.Guest.CDGuest): """ Class for Mageia 4 installation. """ def __init__(self, tdl, config, auto, output_disk, netdev, diskbus, macaddress): oz.Guest.CDGuest.__init__(self, tdl, config, auto, output_disk, netdev, None, None, diskbus, True, False, macaddress) self.mageia_arch = self.tdl.arch if self.mageia_arch == "i386": self.mageia_arch = "i586" self.output_floppy = os.path.join(self.output_dir, self.tdl.name + "-" + self.tdl.installtype + "-oz.img") def _modify_iso(self): """ Method to make the boot ISO auto-boot with appropriate parameters. """ self.log.debug("Modifying ISO") self.log.debug("Copying cfg file to floppy image") outname = os.path.join(self.iso_contents, "auto_inst.cfg") if self.default_auto_file(): def _cfg_sub(line): """ Method that is called back from oz.ozutil.copy_modify_file() to modify preseed files as appropriate for Mageia. """ if re.search("'password' =>", line): return " 'password' => '" + self.rootpw + "',\n" else: return line oz.ozutil.copy_modify_file(self.auto, outname, _cfg_sub) else: shutil.copy(self.auto, outname) oz.ozutil.subprocess_check_output(["/sbin/mkfs.msdos", "-C", self.output_floppy, "1440"]) oz.ozutil.subprocess_check_output(["mcopy", "-n", "-o", "-i", self.output_floppy, outname, "::AUTO_INST.CFG"]) self.log.debug("Modifying isolinux.cfg") isolinuxcfg = os.path.join(self.iso_contents, "isolinux", "isolinux.cfg") with open(isolinuxcfg, 'w') as f: f.write("""\ default customiso timeout 1 prompt 0 label customiso kernel alt0/vmlinuz append initrd=alt0/all.rdz ramdisk_size=128000 root=/dev/ram3 acpi=ht vga=788 automatic=method:cdrom kickstart=floppy """) def _generate_new_iso(self): """ Method to create a new ISO based on the modified CD/DVD. """ self.log.info("Generating new ISO") isolinuxdir = "" if self.tdl.update in ["4"]: isolinuxdir = self.mageia_arch isolinuxbin = os.path.join(isolinuxdir, "isolinux/isolinux.bin") isolinuxboot = os.path.join(isolinuxdir, "isolinux/boot.cat") oz.ozutil.subprocess_check_output(["genisoimage", "-r", "-V", "Custom", "-J", "-l", "-no-emul-boot", "-b", isolinuxbin, "-c", isolinuxboot, "-boot-load-size", "4", "-cache-inodes", "-boot-info-table", "-v", "-o", self.output_iso, self.iso_contents], printfn=self.log.debug) def install(self, timeout=None, force=False): fddev = self._InstallDev("floppy", self.output_floppy, "fda") return self._do_install(timeout, force, 0, None, None, None, [fddev]) def cleanup_install(self): try: os.unlink(self.output_floppy) except: pass return oz.Guest.CDGuest.cleanup_install(self) def get_class(tdl, config, auto, output_disk=None, netdev=None, diskbus=None, macaddress=None): """ Factory method for Mageia installs. """ if tdl.update in ["4"]: return MageiaGuest(tdl, config, auto, output_disk, netdev, diskbus, macaddress) def get_supported_string(): """ Return supported versions as a string. """ return "Mageia: 4"
lgpl-2.1
technologiescollege/s2a_fr
s2a/Python/Lib/distutils/ccompiler.py
80
46633
"""distutils.ccompiler Contains CCompiler, an abstract base class that defines the interface for the Distutils compiler abstraction model.""" __revision__ = "$Id$" import sys import os import re from distutils.errors import (CompileError, LinkError, UnknownFileError, DistutilsPlatformError, DistutilsModuleError) from distutils.spawn import spawn from distutils.file_util import move_file from distutils.dir_util import mkpath from distutils.dep_util import newer_group from distutils.util import split_quoted, execute from distutils import log # following import is for backward compatibility from distutils.sysconfig import customize_compiler class CCompiler: """Abstract base class to define the interface that must be implemented by real compiler classes. Also has some utility methods used by several compiler classes. The basic idea behind a compiler abstraction class is that each instance can be used for all the compile/link steps in building a single project. Thus, attributes common to all of those compile and link steps -- include directories, macros to define, libraries to link against, etc. -- are attributes of the compiler instance. To allow for variability in how individual files are treated, most of those attributes may be varied on a per-compilation or per-link basis. """ # 'compiler_type' is a class attribute that identifies this class. It # keeps code that wants to know what kind of compiler it's dealing with # from having to import all possible compiler classes just to do an # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type' # should really, really be one of the keys of the 'compiler_class' # dictionary (see below -- used by the 'new_compiler()' factory # function) -- authors of new compiler interface classes are # responsible for updating 'compiler_class'! compiler_type = None # XXX things not handled by this compiler abstraction model: # * client can't provide additional options for a compiler, # e.g. warning, optimization, debugging flags. Perhaps this # should be the domain of concrete compiler abstraction classes # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base # class should have methods for the common ones. # * can't completely override the include or library searchg # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2". # I'm not sure how widely supported this is even by Unix # compilers, much less on other platforms. And I'm even less # sure how useful it is; maybe for cross-compiling, but # support for that is a ways off. (And anyways, cross # compilers probably have a dedicated binary with the # right paths compiled in. I hope.) # * can't do really freaky things with the library list/library # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against # different versions of libfoo.a in different locations. I # think this is useless without the ability to null out the # library search path anyways. # Subclasses that rely on the standard filename generation methods # implemented below should override these; see the comment near # those methods ('object_filenames()' et. al.) for details: src_extensions = None # list of strings obj_extension = None # string static_lib_extension = None shared_lib_extension = None # string static_lib_format = None # format string shared_lib_format = None # prob. same as static_lib_format exe_extension = None # string # Default language settings. language_map is used to detect a source # file or Extension target language, checking source filenames. # language_order is used to detect the language precedence, when deciding # what language to use when mixing source types. For example, if some # extension has two files with ".c" extension, and one with ".cpp", it # is still linked as c++. language_map = {".c" : "c", ".cc" : "c++", ".cpp" : "c++", ".cxx" : "c++", ".m" : "objc", } language_order = ["c++", "objc", "c"] def __init__ (self, verbose=0, dry_run=0, force=0): self.dry_run = dry_run self.force = force self.verbose = verbose # 'output_dir': a common output directory for object, library, # shared object, and shared library files self.output_dir = None # 'macros': a list of macro definitions (or undefinitions). A # macro definition is a 2-tuple (name, value), where the value is # either a string or None (no explicit value). A macro # undefinition is a 1-tuple (name,). self.macros = [] # 'include_dirs': a list of directories to search for include files self.include_dirs = [] # 'libraries': a list of libraries to include in any link # (library names, not filenames: eg. "foo" not "libfoo.a") self.libraries = [] # 'library_dirs': a list of directories to search for libraries self.library_dirs = [] # 'runtime_library_dirs': a list of directories to search for # shared libraries/objects at runtime self.runtime_library_dirs = [] # 'objects': a list of object files (or similar, such as explicitly # named library files) to include on any link self.objects = [] for key in self.executables.keys(): self.set_executable(key, self.executables[key]) def set_executables(self, **args): """Define the executables (and options for them) that will be run to perform the various stages of compilation. The exact set of executables that may be specified here depends on the compiler class (via the 'executables' class attribute), but most will have: compiler the C/C++ compiler linker_so linker used to create shared objects and libraries linker_exe linker used to create binary executables archiver static library creator On platforms with a command-line (Unix, DOS/Windows), each of these is a string that will be split into executable name and (optional) list of arguments. (Splitting the string is done similarly to how Unix shells operate: words are delimited by spaces, but quotes and backslashes can override this. See 'distutils.util.split_quoted()'.) """ # Note that some CCompiler implementation classes will define class # attributes 'cpp', 'cc', etc. with hard-coded executable names; # this is appropriate when a compiler class is for exactly one # compiler/OS combination (eg. MSVCCompiler). Other compiler # classes (UnixCCompiler, in particular) are driven by information # discovered at run-time, since there are many different ways to do # basically the same things with Unix C compilers. for key in args.keys(): if key not in self.executables: raise ValueError, \ "unknown executable '%s' for class %s" % \ (key, self.__class__.__name__) self.set_executable(key, args[key]) def set_executable(self, key, value): if isinstance(value, str): setattr(self, key, split_quoted(value)) else: setattr(self, key, value) def _find_macro(self, name): i = 0 for defn in self.macros: if defn[0] == name: return i i = i + 1 return None def _check_macro_definitions(self, definitions): """Ensures that every element of 'definitions' is a valid macro definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do nothing if all definitions are OK, raise TypeError otherwise. """ for defn in definitions: if not (isinstance(defn, tuple) and (len (defn) == 1 or (len (defn) == 2 and (isinstance(defn[1], str) or defn[1] is None))) and isinstance(defn[0], str)): raise TypeError, \ ("invalid macro definition '%s': " % defn) + \ "must be tuple (string,), (string, string), or " + \ "(string, None)" # -- Bookkeeping methods ------------------------------------------- def define_macro(self, name, value=None): """Define a preprocessor macro for all compilations driven by this compiler object. The optional parameter 'value' should be a string; if it is not supplied, then the macro will be defined without an explicit value and the exact outcome depends on the compiler used (XXX true? does ANSI say anything about this?) """ # Delete from the list of macro definitions/undefinitions if # already there (so that this one will take precedence). i = self._find_macro (name) if i is not None: del self.macros[i] defn = (name, value) self.macros.append (defn) def undefine_macro(self, name): """Undefine a preprocessor macro for all compilations driven by this compiler object. If the same macro is defined by 'define_macro()' and undefined by 'undefine_macro()' the last call takes precedence (including multiple redefinitions or undefinitions). If the macro is redefined/undefined on a per-compilation basis (ie. in the call to 'compile()'), then that takes precedence. """ # Delete from the list of macro definitions/undefinitions if # already there (so that this one will take precedence). i = self._find_macro (name) if i is not None: del self.macros[i] undefn = (name,) self.macros.append (undefn) def add_include_dir(self, dir): """Add 'dir' to the list of directories that will be searched for header files. The compiler is instructed to search directories in the order in which they are supplied by successive calls to 'add_include_dir()'. """ self.include_dirs.append (dir) def set_include_dirs(self, dirs): """Set the list of directories that will be searched to 'dirs' (a list of strings). Overrides any preceding calls to 'add_include_dir()'; subsequence calls to 'add_include_dir()' add to the list passed to 'set_include_dirs()'. This does not affect any list of standard include directories that the compiler may search by default. """ self.include_dirs = dirs[:] def add_library(self, libname): """Add 'libname' to the list of libraries that will be included in all links driven by this compiler object. Note that 'libname' should *not* be the name of a file containing a library, but the name of the library itself: the actual filename will be inferred by the linker, the compiler, or the compiler class (depending on the platform). The linker will be instructed to link against libraries in the order they were supplied to 'add_library()' and/or 'set_libraries()'. It is perfectly valid to duplicate library names; the linker will be instructed to link against libraries as many times as they are mentioned. """ self.libraries.append (libname) def set_libraries(self, libnames): """Set the list of libraries to be included in all links driven by this compiler object to 'libnames' (a list of strings). This does not affect any standard system libraries that the linker may include by default. """ self.libraries = libnames[:] def add_library_dir(self, dir): """Add 'dir' to the list of directories that will be searched for libraries specified to 'add_library()' and 'set_libraries()'. The linker will be instructed to search for libraries in the order they are supplied to 'add_library_dir()' and/or 'set_library_dirs()'. """ self.library_dirs.append(dir) def set_library_dirs(self, dirs): """Set the list of library search directories to 'dirs' (a list of strings). This does not affect any standard library search path that the linker may search by default. """ self.library_dirs = dirs[:] def add_runtime_library_dir(self, dir): """Add 'dir' to the list of directories that will be searched for shared libraries at runtime. """ self.runtime_library_dirs.append(dir) def set_runtime_library_dirs(self, dirs): """Set the list of directories to search for shared libraries at runtime to 'dirs' (a list of strings). This does not affect any standard search path that the runtime linker may search by default. """ self.runtime_library_dirs = dirs[:] def add_link_object(self, object): """Add 'object' to the list of object files (or analogues, such as explicitly named library files or the output of "resource compilers") to be included in every link driven by this compiler object. """ self.objects.append(object) def set_link_objects(self, objects): """Set the list of object files (or analogues) to be included in every link to 'objects'. This does not affect any standard object files that the linker may include by default (such as system libraries). """ self.objects = objects[:] # -- Private utility methods -------------------------------------- # (here for the convenience of subclasses) # Helper method to prep compiler in subclass compile() methods def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra): """Process arguments and decide which source files to compile.""" if outdir is None: outdir = self.output_dir elif not isinstance(outdir, str): raise TypeError, "'output_dir' must be a string or None" if macros is None: macros = self.macros elif isinstance(macros, list): macros = macros + (self.macros or []) else: raise TypeError, "'macros' (if supplied) must be a list of tuples" if incdirs is None: incdirs = self.include_dirs elif isinstance(incdirs, (list, tuple)): incdirs = list(incdirs) + (self.include_dirs or []) else: raise TypeError, \ "'include_dirs' (if supplied) must be a list of strings" if extra is None: extra = [] # Get the list of expected output (object) files objects = self.object_filenames(sources, strip_dir=0, output_dir=outdir) assert len(objects) == len(sources) pp_opts = gen_preprocess_options(macros, incdirs) build = {} for i in range(len(sources)): src = sources[i] obj = objects[i] ext = os.path.splitext(src)[1] self.mkpath(os.path.dirname(obj)) build[obj] = (src, ext) return macros, objects, extra, pp_opts, build def _get_cc_args(self, pp_opts, debug, before): # works for unixccompiler, emxccompiler, cygwinccompiler cc_args = pp_opts + ['-c'] if debug: cc_args[:0] = ['-g'] if before: cc_args[:0] = before return cc_args def _fix_compile_args(self, output_dir, macros, include_dirs): """Typecheck and fix-up some of the arguments to the 'compile()' method, and return fixed-up values. Specifically: if 'output_dir' is None, replaces it with 'self.output_dir'; ensures that 'macros' is a list, and augments it with 'self.macros'; ensures that 'include_dirs' is a list, and augments it with 'self.include_dirs'. Guarantees that the returned values are of the correct type, i.e. for 'output_dir' either string or None, and for 'macros' and 'include_dirs' either list or None. """ if output_dir is None: output_dir = self.output_dir elif not isinstance(output_dir, str): raise TypeError, "'output_dir' must be a string or None" if macros is None: macros = self.macros elif isinstance(macros, list): macros = macros + (self.macros or []) else: raise TypeError, "'macros' (if supplied) must be a list of tuples" if include_dirs is None: include_dirs = self.include_dirs elif isinstance(include_dirs, (list, tuple)): include_dirs = list (include_dirs) + (self.include_dirs or []) else: raise TypeError, \ "'include_dirs' (if supplied) must be a list of strings" return output_dir, macros, include_dirs def _fix_object_args(self, objects, output_dir): """Typecheck and fix up some arguments supplied to various methods. Specifically: ensure that 'objects' is a list; if output_dir is None, replace with self.output_dir. Return fixed versions of 'objects' and 'output_dir'. """ if not isinstance(objects, (list, tuple)): raise TypeError, \ "'objects' must be a list or tuple of strings" objects = list (objects) if output_dir is None: output_dir = self.output_dir elif not isinstance(output_dir, str): raise TypeError, "'output_dir' must be a string or None" return (objects, output_dir) def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs): """Typecheck and fix up some of the arguments supplied to the 'link_*' methods. Specifically: ensure that all arguments are lists, and augment them with their permanent versions (eg. 'self.libraries' augments 'libraries'). Return a tuple with fixed versions of all arguments. """ if libraries is None: libraries = self.libraries elif isinstance(libraries, (list, tuple)): libraries = list (libraries) + (self.libraries or []) else: raise TypeError, \ "'libraries' (if supplied) must be a list of strings" if library_dirs is None: library_dirs = self.library_dirs elif isinstance(library_dirs, (list, tuple)): library_dirs = list (library_dirs) + (self.library_dirs or []) else: raise TypeError, \ "'library_dirs' (if supplied) must be a list of strings" if runtime_library_dirs is None: runtime_library_dirs = self.runtime_library_dirs elif isinstance(runtime_library_dirs, (list, tuple)): runtime_library_dirs = (list (runtime_library_dirs) + (self.runtime_library_dirs or [])) else: raise TypeError, \ "'runtime_library_dirs' (if supplied) " + \ "must be a list of strings" return (libraries, library_dirs, runtime_library_dirs) def _need_link(self, objects, output_file): """Return true if we need to relink the files listed in 'objects' to recreate 'output_file'. """ if self.force: return 1 else: if self.dry_run: newer = newer_group (objects, output_file, missing='newer') else: newer = newer_group (objects, output_file) return newer def detect_language(self, sources): """Detect the language of a given file, or list of files. Uses language_map, and language_order to do the job. """ if not isinstance(sources, list): sources = [sources] lang = None index = len(self.language_order) for source in sources: base, ext = os.path.splitext(source) extlang = self.language_map.get(ext) try: extindex = self.language_order.index(extlang) if extindex < index: lang = extlang index = extindex except ValueError: pass return lang # -- Worker methods ------------------------------------------------ # (must be implemented by subclasses) def preprocess(self, source, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None): """Preprocess a single C/C++ source file, named in 'source'. Output will be written to file named 'output_file', or stdout if 'output_file' not supplied. 'macros' is a list of macro definitions as for 'compile()', which will augment the macros set with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a list of directory names that will be added to the default list. Raises PreprocessError on failure. """ pass def compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): """Compile one or more source files. 'sources' must be a list of filenames, most likely C/C++ files, but in reality anything that can be handled by a particular compiler and compiler class (eg. MSVCCompiler can handle resource files in 'sources'). Return a list of object filenames, one per source filename in 'sources'. Depending on the implementation, not all source files will necessarily be compiled, but all corresponding object filenames will be returned. If 'output_dir' is given, object files will be put under it, while retaining their original path component. That is, "foo/bar.c" normally compiles to "foo/bar.o" (for a Unix implementation); if 'output_dir' is "build", then it would compile to "build/foo/bar.o". 'macros', if given, must be a list of macro definitions. A macro definition is either a (name, value) 2-tuple or a (name,) 1-tuple. The former defines a macro; if the value is None, the macro is defined without an explicit value. The 1-tuple case undefines a macro. Later definitions/redefinitions/ undefinitions take precedence. 'include_dirs', if given, must be a list of strings, the directories to add to the default include file search path for this compilation only. 'debug' is a boolean; if true, the compiler will be instructed to output debug symbols in (or alongside) the object file(s). 'extra_preargs' and 'extra_postargs' are implementation- dependent. On platforms that have the notion of a command-line (e.g. Unix, DOS/Windows), they are most likely lists of strings: extra command-line arguments to prepand/append to the compiler command line. On other platforms, consult the implementation class documentation. In any event, they are intended as an escape hatch for those occasions when the abstract compiler framework doesn't cut the mustard. 'depends', if given, is a list of filenames that all targets depend on. If a source file is older than any file in depends, then the source file will be recompiled. This supports dependency tracking, but only at a coarse granularity. Raises CompileError on failure. """ # A concrete compiler class can either override this method # entirely or implement _compile(). macros, objects, extra_postargs, pp_opts, build = \ self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) for obj in objects: try: src, ext = build[obj] except KeyError: continue self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) # Return *all* object filenames, not just the ones we just built. return objects def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile 'src' to product 'obj'.""" # A concrete compiler class that does not override compile() # should implement _compile(). pass def create_static_lib(self, objects, output_libname, output_dir=None, debug=0, target_lang=None): """Link a bunch of stuff together to create a static library file. The "bunch of stuff" consists of the list of object files supplied as 'objects', the extra object files supplied to 'add_link_object()' and/or 'set_link_objects()', the libraries supplied to 'add_library()' and/or 'set_libraries()', and the libraries supplied as 'libraries' (if any). 'output_libname' should be a library name, not a filename; the filename will be inferred from the library name. 'output_dir' is the directory where the library file will be put. 'debug' is a boolean; if true, debugging information will be included in the library (note that on most platforms, it is the compile step where this matters: the 'debug' flag is included here just for consistency). 'target_lang' is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages. Raises LibError on failure. """ pass # values for target_desc parameter in link() SHARED_OBJECT = "shared_object" SHARED_LIBRARY = "shared_library" EXECUTABLE = "executable" def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): """Link a bunch of stuff together to create an executable or shared library file. The "bunch of stuff" consists of the list of object files supplied as 'objects'. 'output_filename' should be a filename. If 'output_dir' is supplied, 'output_filename' is relative to it (i.e. 'output_filename' can provide directory components if needed). 'libraries' is a list of libraries to link against. These are library names, not filenames, since they're translated into filenames in a platform-specific way (eg. "foo" becomes "libfoo.a" on Unix and "foo.lib" on DOS/Windows). However, they can include a directory component, which means the linker will look in that specific directory rather than searching all the normal locations. 'library_dirs', if supplied, should be a list of directories to search for libraries that were specified as bare library names (ie. no directory component). These are on top of the system default and those supplied to 'add_library_dir()' and/or 'set_library_dirs()'. 'runtime_library_dirs' is a list of directories that will be embedded into the shared library and used to search for other shared libraries that *it* depends on at run-time. (This may only be relevant on Unix.) 'export_symbols' is a list of symbols that the shared library will export. (This appears to be relevant only on Windows.) 'debug' is as for 'compile()' and 'create_static_lib()', with the slight distinction that it actually matters on most platforms (as opposed to 'create_static_lib()', which includes a 'debug' flag mostly for form's sake). 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except of course that they supply command-line arguments for the particular linker being used). 'target_lang' is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages. Raises LinkError on failure. """ raise NotImplementedError # Old 'link_*()' methods, rewritten to use the new 'link()' method. def link_shared_lib(self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): self.link(CCompiler.SHARED_LIBRARY, objects, self.library_filename(output_libname, lib_type='shared'), output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols, debug, extra_preargs, extra_postargs, build_temp, target_lang) def link_shared_object(self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): self.link(CCompiler.SHARED_OBJECT, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols, debug, extra_preargs, extra_postargs, build_temp, target_lang) def link_executable(self, objects, output_progname, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, target_lang=None): self.link(CCompiler.EXECUTABLE, objects, self.executable_filename(output_progname), output_dir, libraries, library_dirs, runtime_library_dirs, None, debug, extra_preargs, extra_postargs, None, target_lang) # -- Miscellaneous methods ----------------------------------------- # These are all used by the 'gen_lib_options() function; there is # no appropriate default implementation so subclasses should # implement all of these. def library_dir_option(self, dir): """Return the compiler option to add 'dir' to the list of directories searched for libraries. """ raise NotImplementedError def runtime_library_dir_option(self, dir): """Return the compiler option to add 'dir' to the list of directories searched for runtime libraries. """ raise NotImplementedError def library_option(self, lib): """Return the compiler option to add 'dir' to the list of libraries linked into the shared library or executable. """ raise NotImplementedError def has_function(self, funcname, includes=None, include_dirs=None, libraries=None, library_dirs=None): """Return a boolean indicating whether funcname is supported on the current platform. The optional arguments can be used to augment the compilation environment. """ # this can't be included at module scope because it tries to # import math which might not be available at that point - maybe # the necessary logic should just be inlined? import tempfile if includes is None: includes = [] if include_dirs is None: include_dirs = [] if libraries is None: libraries = [] if library_dirs is None: library_dirs = [] fd, fname = tempfile.mkstemp(".c", funcname, text=True) f = os.fdopen(fd, "w") try: for incl in includes: f.write("""#include "%s"\n""" % incl) f.write("""\ main (int argc, char **argv) { %s(); } """ % funcname) finally: f.close() try: objects = self.compile([fname], include_dirs=include_dirs) except CompileError: return False try: self.link_executable(objects, "a.out", libraries=libraries, library_dirs=library_dirs) except (LinkError, TypeError): return False return True def find_library_file (self, dirs, lib, debug=0): """Search the specified list of directories for a static or shared library file 'lib' and return the full path to that file. If 'debug' true, look for a debugging version (if that makes sense on the current platform). Return None if 'lib' wasn't found in any of the specified directories. """ raise NotImplementedError # -- Filename generation methods ----------------------------------- # The default implementation of the filename generating methods are # prejudiced towards the Unix/DOS/Windows view of the world: # * object files are named by replacing the source file extension # (eg. .c/.cpp -> .o/.obj) # * library files (shared or static) are named by plugging the # library name and extension into a format string, eg. # "lib%s.%s" % (lib_name, ".a") for Unix static libraries # * executables are named by appending an extension (possibly # empty) to the program name: eg. progname + ".exe" for # Windows # # To reduce redundant code, these methods expect to find # several attributes in the current object (presumably defined # as class attributes): # * src_extensions - # list of C/C++ source file extensions, eg. ['.c', '.cpp'] # * obj_extension - # object file extension, eg. '.o' or '.obj' # * static_lib_extension - # extension for static library files, eg. '.a' or '.lib' # * shared_lib_extension - # extension for shared library/object files, eg. '.so', '.dll' # * static_lib_format - # format string for generating static library filenames, # eg. 'lib%s.%s' or '%s.%s' # * shared_lib_format # format string for generating shared library filenames # (probably same as static_lib_format, since the extension # is one of the intended parameters to the format string) # * exe_extension - # extension for executable files, eg. '' or '.exe' def object_filenames(self, source_filenames, strip_dir=0, output_dir=''): if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: base, ext = os.path.splitext(src_name) base = os.path.splitdrive(base)[1] # Chop off the drive base = base[os.path.isabs(base):] # If abs, chop off leading / if ext not in self.src_extensions: raise UnknownFileError, \ "unknown file type '%s' (from '%s')" % (ext, src_name) if strip_dir: base = os.path.basename(base) obj_names.append(os.path.join(output_dir, base + self.obj_extension)) return obj_names def shared_object_filename(self, basename, strip_dir=0, output_dir=''): assert output_dir is not None if strip_dir: basename = os.path.basename (basename) return os.path.join(output_dir, basename + self.shared_lib_extension) def executable_filename(self, basename, strip_dir=0, output_dir=''): assert output_dir is not None if strip_dir: basename = os.path.basename (basename) return os.path.join(output_dir, basename + (self.exe_extension or '')) def library_filename(self, libname, lib_type='static', # or 'shared' strip_dir=0, output_dir=''): assert output_dir is not None if lib_type not in ("static", "shared", "dylib"): raise ValueError, "'lib_type' must be \"static\", \"shared\" or \"dylib\"" fmt = getattr(self, lib_type + "_lib_format") ext = getattr(self, lib_type + "_lib_extension") dir, base = os.path.split (libname) filename = fmt % (base, ext) if strip_dir: dir = '' return os.path.join(output_dir, dir, filename) # -- Utility methods ----------------------------------------------- def announce(self, msg, level=1): log.debug(msg) def debug_print(self, msg): from distutils.debug import DEBUG if DEBUG: print msg def warn(self, msg): sys.stderr.write("warning: %s\n" % msg) def execute(self, func, args, msg=None, level=1): execute(func, args, msg, self.dry_run) def spawn(self, cmd): spawn(cmd, dry_run=self.dry_run) def move_file(self, src, dst): return move_file(src, dst, dry_run=self.dry_run) def mkpath(self, name, mode=0777): mkpath(name, mode, dry_run=self.dry_run) # class CCompiler # Map a sys.platform/os.name ('posix', 'nt') to the default compiler # type for that platform. Keys are interpreted as re match # patterns. Order is important; platform mappings are preferred over # OS names. _default_compilers = ( # Platform string mappings # on a cygwin built python we can use gcc like an ordinary UNIXish # compiler ('cygwin.*', 'unix'), ('os2emx', 'emx'), # OS name mappings ('posix', 'unix'), ('nt', 'msvc'), ) def get_default_compiler(osname=None, platform=None): """ Determine the default compiler to use for the given platform. osname should be one of the standard Python OS names (i.e. the ones returned by os.name) and platform the common value returned by sys.platform for the platform in question. The default values are os.name and sys.platform in case the parameters are not given. """ if osname is None: osname = os.name if platform is None: platform = sys.platform for pattern, compiler in _default_compilers: if re.match(pattern, platform) is not None or \ re.match(pattern, osname) is not None: return compiler # Default to Unix compiler return 'unix' # Map compiler types to (module_name, class_name) pairs -- ie. where to # find the code that implements an interface to this compiler. (The module # is assumed to be in the 'distutils' package.) compiler_class = { 'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"), 'msvc': ('msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"), 'cygwin': ('cygwinccompiler', 'CygwinCCompiler', "Cygwin port of GNU C Compiler for Win32"), 'mingw32': ('cygwinccompiler', 'Mingw32CCompiler', "Mingw32 port of GNU C Compiler for Win32"), 'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"), 'emx': ('emxccompiler', 'EMXCCompiler', "EMX port of GNU C Compiler for OS/2"), } def show_compilers(): """Print list of available compilers (used by the "--help-compiler" options to "build", "build_ext", "build_clib"). """ # XXX this "knows" that the compiler option it's describing is # "--compiler", which just happens to be the case for the three # commands that use it. from distutils.fancy_getopt import FancyGetopt compilers = [] for compiler in compiler_class.keys(): compilers.append(("compiler="+compiler, None, compiler_class[compiler][2])) compilers.sort() pretty_printer = FancyGetopt(compilers) pretty_printer.print_help("List of available compilers:") def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0): """Generate an instance of some CCompiler subclass for the supplied platform/compiler combination. 'plat' defaults to 'os.name' (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler for that platform. Currently only 'posix' and 'nt' are supported, and the default compilers are "traditional Unix interface" (UnixCCompiler class) and Visual C++ (MSVCCompiler class). Note that it's perfectly possible to ask for a Unix compiler object under Windows, and a Microsoft compiler object under Unix -- if you supply a value for 'compiler', 'plat' is ignored. """ if plat is None: plat = os.name try: if compiler is None: compiler = get_default_compiler(plat) (module_name, class_name, long_description) = compiler_class[compiler] except KeyError: msg = "don't know how to compile C/C++ code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler" % compiler raise DistutilsPlatformError, msg try: module_name = "distutils." + module_name __import__ (module_name) module = sys.modules[module_name] klass = vars(module)[class_name] except ImportError: raise DistutilsModuleError, \ "can't compile C/C++ code: unable to load module '%s'" % \ module_name except KeyError: raise DistutilsModuleError, \ ("can't compile C/C++ code: unable to find class '%s' " + "in module '%s'") % (class_name, module_name) # XXX The None is necessary to preserve backwards compatibility # with classes that expect verbose to be the first positional # argument. return klass(None, dry_run, force) def gen_preprocess_options(macros, include_dirs): """Generate C pre-processor options (-D, -U, -I) as used by at least two types of compilers: the typical Unix compiler and Visual C++. 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,) means undefine (-U) macro 'name', and (name,value) means define (-D) macro 'name' to 'value'. 'include_dirs' is just a list of directory names to be added to the header file search path (-I). Returns a list of command-line options suitable for either Unix compilers or Visual C++. """ # XXX it would be nice (mainly aesthetic, and so we don't generate # stupid-looking command lines) to go over 'macros' and eliminate # redundant definitions/undefinitions (ie. ensure that only the # latest mention of a particular macro winds up on the command # line). I don't think it's essential, though, since most (all?) # Unix C compilers only pay attention to the latest -D or -U # mention of a macro on their command line. Similar situation for # 'include_dirs'. I'm punting on both for now. Anyways, weeding out # redundancies like this should probably be the province of # CCompiler, since the data structures used are inherited from it # and therefore common to all CCompiler classes. pp_opts = [] for macro in macros: if not (isinstance(macro, tuple) and 1 <= len (macro) <= 2): raise TypeError, \ ("bad macro definition '%s': " + "each element of 'macros' list must be a 1- or 2-tuple") % \ macro if len (macro) == 1: # undefine this macro pp_opts.append ("-U%s" % macro[0]) elif len (macro) == 2: if macro[1] is None: # define with no explicit value pp_opts.append ("-D%s" % macro[0]) else: # XXX *don't* need to be clever about quoting the # macro value here, because we're going to avoid the # shell at all costs when we spawn the command! pp_opts.append ("-D%s=%s" % macro) for dir in include_dirs: pp_opts.append ("-I%s" % dir) return pp_opts def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries): """Generate linker options for searching library directories and linking with specific libraries. 'libraries' and 'library_dirs' are, respectively, lists of library names (not filenames!) and search directories. Returns a list of command-line options suitable for use with some compiler (depending on the two format strings passed in). """ lib_opts = [] for dir in library_dirs: lib_opts.append(compiler.library_dir_option(dir)) for dir in runtime_library_dirs: opt = compiler.runtime_library_dir_option(dir) if isinstance(opt, list): lib_opts.extend(opt) else: lib_opts.append(opt) # XXX it's important that we *not* remove redundant library mentions! # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to # resolve all symbols. I just hope we never have to say "-lfoo obj.o # -lbar" to get things to work -- that's certainly a possibility, but a # pretty nasty way to arrange your C code. for lib in libraries: lib_dir, lib_name = os.path.split(lib) if lib_dir != '': lib_file = compiler.find_library_file([lib_dir], lib_name) if lib_file is not None: lib_opts.append(lib_file) else: compiler.warn("no library file corresponding to " "'%s' found (skipping)" % lib) else: lib_opts.append(compiler.library_option(lib)) return lib_opts
gpl-3.0
jseabold/statsmodels
examples/python/quantile_regression.py
5
4049
# coding: utf-8 # DO NOT EDIT # Autogenerated from the notebook quantile_regression.ipynb. # Edit the notebook and then sync the output with this file. # # flake8: noqa # DO NOT EDIT # # Quantile regression # # This example page shows how to use ``statsmodels``' ``QuantReg`` class # to replicate parts of the analysis published in # # * Koenker, Roger and Kevin F. Hallock. "Quantile Regressioin". Journal # of Economic Perspectives, Volume 15, Number 4, Fall 2001, Pages 143–156 # # We are interested in the relationship between income and expenditures on # food for a sample of working class Belgian households in 1857 (the Engel # data). # # ## Setup # # We first need to load some modules and to retrieve the data. # Conveniently, the Engel dataset is shipped with ``statsmodels``. import numpy as np import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as smf import matplotlib.pyplot as plt data = sm.datasets.engel.load_pandas().data data.head() # ## Least Absolute Deviation # # The LAD model is a special case of quantile regression where q=0.5 mod = smf.quantreg('foodexp ~ income', data) res = mod.fit(q=.5) print(res.summary()) # ## Visualizing the results # # We estimate the quantile regression model for many quantiles between .05 # and .95, and compare best fit line from each of these models to Ordinary # Least Squares results. # ### Prepare data for plotting # # For convenience, we place the quantile regression results in a Pandas # DataFrame, and the OLS results in a dictionary. quantiles = np.arange(.05, .96, .1) def fit_model(q): res = mod.fit(q=q) return [q, res.params['Intercept'], res.params['income'] ] + res.conf_int().loc['income'].tolist() models = [fit_model(x) for x in quantiles] models = pd.DataFrame(models, columns=['q', 'a', 'b', 'lb', 'ub']) ols = smf.ols('foodexp ~ income', data).fit() ols_ci = ols.conf_int().loc['income'].tolist() ols = dict( a=ols.params['Intercept'], b=ols.params['income'], lb=ols_ci[0], ub=ols_ci[1]) print(models) print(ols) # ### First plot # # This plot compares best fit lines for 10 quantile regression models to # the least squares fit. As Koenker and Hallock (2001) point out, we see # that: # # 1. Food expenditure increases with income # 2. The *dispersion* of food expenditure increases with income # 3. The least squares estimates fit low income observations quite poorly # (i.e. the OLS line passes over most low income households) x = np.arange(data.income.min(), data.income.max(), 50) get_y = lambda a, b: a + b * x fig, ax = plt.subplots(figsize=(8, 6)) for i in range(models.shape[0]): y = get_y(models.a[i], models.b[i]) ax.plot(x, y, linestyle='dotted', color='grey') y = get_y(ols['a'], ols['b']) ax.plot(x, y, color='red', label='OLS') ax.scatter(data.income, data.foodexp, alpha=.2) ax.set_xlim((240, 3000)) ax.set_ylim((240, 2000)) legend = ax.legend() ax.set_xlabel('Income', fontsize=16) ax.set_ylabel( 'Food expenditure', fontsize=16) # ### Second plot # # The dotted black lines form 95% point-wise confidence band around 10 # quantile regression estimates (solid black line). The red lines represent # OLS regression results along with their 95% confidence interval. # # In most cases, the quantile regression point estimates lie outside the # OLS confidence interval, which suggests that the effect of income on food # expenditure may not be constant across the distribution. n = models.shape[0] p1 = plt.plot(models.q, models.b, color='black', label='Quantile Reg.') p2 = plt.plot(models.q, models.ub, linestyle='dotted', color='black') p3 = plt.plot(models.q, models.lb, linestyle='dotted', color='black') p4 = plt.plot(models.q, [ols['b']] * n, color='red', label='OLS') p5 = plt.plot(models.q, [ols['lb']] * n, linestyle='dotted', color='red') p6 = plt.plot(models.q, [ols['ub']] * n, linestyle='dotted', color='red') plt.ylabel(r'$\beta_{income}$') plt.xlabel('Quantiles of the conditional food expenditure distribution') plt.legend() plt.show()
bsd-3-clause
pambot/SMSQuery
lib/jinja/nodes.py
7
17574
# -*- coding: utf-8 -*- """ jinja.nodes ~~~~~~~~~~~ This module implements additional nodes derived from the ast base node. It also provides some node tree helper functions like `in_lineno` and `get_nodes` used by the parser and translator in order to normalize python and jinja nodes. :copyright: 2007 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from itertools import chain from copy import copy def get_nodes(nodetype, tree, exclude_root=True): """ Get all nodes from nodetype in the tree excluding the node passed if `exclude_root` is `True` (default). """ if exclude_root: todo = tree.get_child_nodes() else: todo = [tree] while todo: node = todo.pop() if node.__class__ is nodetype: yield node todo.extend(node.get_child_nodes()) class NotPossible(NotImplementedError): """ If a given node cannot do something. """ class Node(object): """ Jinja node. """ def __init__(self, lineno=None, filename=None): self.lineno = lineno self.filename = filename def get_items(self): return [] def get_child_nodes(self): return [x for x in self.get_items() if isinstance(x, Node)] def allows_assignments(self): return False def __repr__(self): return 'Node()' class Text(Node): """ Node that represents normal text. """ def __init__(self, text, variables, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.text = text self.variables = variables def get_items(self): return [self.text] + list(self.variables) def __repr__(self): return 'Text(%r, %r)' % ( self.text, self.variables ) class NodeList(list, Node): """ A node that stores multiple childnodes. """ def __init__(self, data, lineno=None, filename=None): Node.__init__(self, lineno, filename) list.__init__(self, data) def get_items(self): return list(self) def __repr__(self): return 'NodeList(%s)' % list.__repr__(self) class Template(Node): """ Node that represents a template. """ def __init__(self, extends, body, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.extends = extends self.body = body def get_items(self): return [self.extends, self.body] def __repr__(self): return 'Template(%r, %r)' % ( self.extends, self.body ) class ForLoop(Node): """ A node that represents a for loop """ def __init__(self, item, seq, body, else_, recursive, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.item = item self.seq = seq self.body = body self.else_ = else_ self.recursive = recursive def get_items(self): return [self.item, self.seq, self.body, self.else_, self.recursive] def __repr__(self): return 'ForLoop(%r, %r, %r, %r, %r)' % ( self.item, self.seq, self.body, self.else_, self.recursive ) class IfCondition(Node): """ A node that represents an if condition. """ def __init__(self, tests, else_, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.tests = tests self.else_ = else_ def get_items(self): result = [] for test in self.tests: result.extend(test) result.append(self.else_) return result def __repr__(self): return 'IfCondition(%r, %r)' % ( self.tests, self.else_ ) class Cycle(Node): """ A node that represents the cycle statement. """ def __init__(self, seq, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.seq = seq def get_items(self): return [self.seq] def __repr__(self): return 'Cycle(%r)' % (self.seq,) class Print(Node): """ A node that represents variable tags and print calls. """ def __init__(self, expr, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.expr = expr def get_items(self): return [self.expr] def __repr__(self): return 'Print(%r)' % (self.expr,) class Macro(Node): """ A node that represents a macro. """ def __init__(self, name, arguments, body, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.name = name self.arguments = arguments self.body = body def get_items(self): return [self.name] + list(chain(*self.arguments)) + [self.body] def __repr__(self): return 'Macro(%r, %r, %r)' % ( self.name, self.arguments, self.body ) class Call(Node): """ A node that represents am extended macro call. """ def __init__(self, expr, body, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.expr = expr self.body = body def get_items(self): return [self.expr, self.body] def __repr__(self): return 'Call(%r, %r)' % ( self.expr, self.body ) class Set(Node): """ Allows defining own variables. """ def __init__(self, name, expr, scope_local, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.name = name self.expr = expr self.scope_local = scope_local def get_items(self): return [self.name, self.expr, self.scope_local] def __repr__(self): return 'Set(%r, %r, %r)' % ( self.name, self.expr, self.scope_local ) class Filter(Node): """ Node for filter sections. """ def __init__(self, body, filters, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.body = body self.filters = filters def get_items(self): return [self.body] + list(self.filters) def __repr__(self): return 'Filter(%r, %r)' % ( self.body, self.filters ) class Block(Node): """ A node that represents a block. """ def __init__(self, name, body, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.name = name self.body = body def replace(self, node): """ Replace the current data with the copied data of another block node. """ assert node.__class__ is Block self.lineno = node.lineno self.filename = node.filename self.name = node.name self.body = copy(node.body) def clone(self): """ Create an independent clone of this node. """ return copy(self) def get_items(self): return [self.name, self.body] def __repr__(self): return 'Block(%r, %r)' % ( self.name, self.body ) class Include(Node): """ A node that represents the include tag. """ def __init__(self, template, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.template = template def get_items(self): return [self.template] def __repr__(self): return 'Include(%r)' % ( self.template ) class Trans(Node): """ A node for translatable sections. """ def __init__(self, singular, plural, indicator, replacements, lineno=None, filename=None): Node.__init__(self, lineno, filename) self.singular = singular self.plural = plural self.indicator = indicator self.replacements = replacements def get_items(self): rv = [self.singular, self.plural, self.indicator] if self.replacements: rv.extend(self.replacements.values()) rv.extend(self.replacements.keys()) return rv def __repr__(self): return 'Trans(%r, %r, %r, %r)' % ( self.singular, self.plural, self.indicator, self.replacements ) class Expression(Node): """ Baseclass for all expressions. """ class BinaryExpression(Expression): """ Baseclass for all binary expressions. """ def __init__(self, left, right, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.left = left self.right = right def get_items(self): return [self.left, self.right] def __repr__(self): return '%s(%r, %r)' % ( self.__class__.__name__, self.left, self.right ) class UnaryExpression(Expression): """ Baseclass for all unary expressions. """ def __init__(self, node, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.node = node def get_items(self): return [self.node] def __repr__(self): return '%s(%r)' % ( self.__class__.__name__, self.node ) class ConstantExpression(Expression): """ any constat such as {{ "foo" }} """ def __init__(self, value, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.value = value def get_items(self): return [self.value] def __repr__(self): return 'ConstantExpression(%r)' % (self.value,) class UndefinedExpression(Expression): """ represents the special 'undefined' value. """ def __repr__(self): return 'UndefinedExpression()' class RegexExpression(Expression): """ represents the regular expression literal. """ def __init__(self, value, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.value = value def get_items(self): return [self.value] def __repr__(self): return 'RegexExpression(%r)' % (self.value,) class NameExpression(Expression): """ any name such as {{ foo }} """ def __init__(self, name, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.name = name def get_items(self): return [self.name] def allows_assignments(self): return self.name != '_' def __repr__(self): return 'NameExpression(%r)' % self.name class ListExpression(Expression): """ any list literal such as {{ [1, 2, 3] }} """ def __init__(self, items, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.items = items def get_items(self): return list(self.items) def __repr__(self): return 'ListExpression(%r)' % (self.items,) class DictExpression(Expression): """ any dict literal such as {{ {1: 2, 3: 4} }} """ def __init__(self, items, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.items = items def get_items(self): return list(chain(*self.items)) def __repr__(self): return 'DictExpression(%r)' % (self.items,) class SetExpression(Expression): """ any set literal such as {{ @(1, 2, 3) }} """ def __init__(self, items, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.items = items def get_items(self): return self.items[:] def __repr__(self): return 'SetExpression(%r)' % (self.items,) class ConditionalExpression(Expression): """ {{ foo if bar else baz }} """ def __init__(self, test, expr1, expr2, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.test = test self.expr1 = expr1 self.expr2 = expr2 def get_items(self): return [self.test, self.expr1, self.expr2] def __repr__(self): return 'ConstantExpression(%r, %r, %r)' % ( self.test, self.expr1, self.expr2 ) class FilterExpression(Expression): """ {{ foo|bar|baz }} """ def __init__(self, node, filters, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.node = node self.filters = filters def get_items(self): result = [self.node] for filter, args in self.filters: result.append(filter) result.extend(args) return result def __repr__(self): return 'FilterExpression(%r, %r)' % ( self.node, self.filters ) class TestExpression(Expression): """ {{ foo is lower }} """ def __init__(self, node, name, args, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.node = node self.name = name self.args = args def get_items(self): return [self.node, self.name] + list(self.args) def __repr__(self): return 'TestExpression(%r, %r, %r)' % ( self.node, self.name, self.args ) class CallExpression(Expression): """ {{ foo(bar) }} """ def __init__(self, node, args, kwargs, dyn_args, dyn_kwargs, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.node = node self.args = args self.kwargs = kwargs self.dyn_args = dyn_args self.dyn_kwargs = dyn_kwargs def get_items(self): return [self.node, self.args, self.kwargs, self.dyn_args, self.dyn_kwargs] def __repr__(self): return 'CallExpression(%r, %r, %r, %r, %r)' % ( self.node, self.args, self.kwargs, self.dyn_args, self.dyn_kwargs ) class SubscriptExpression(Expression): """ {{ foo.bar }} and {{ foo['bar'] }} etc. """ def __init__(self, node, arg, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.node = node self.arg = arg def get_items(self): return [self.node, self.arg] def __repr__(self): return 'SubscriptExpression(%r, %r)' % ( self.node, self.arg ) class SliceExpression(Expression): """ 1:2:3 etc. """ def __init__(self, start, stop, step, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.start = start self.stop = stop self.step = step def get_items(self): return [self.start, self.stop, self.step] def __repr__(self): return 'SliceExpression(%r, %r, %r)' % ( self.start, self.stop, self.step ) class TupleExpression(Expression): """ For loop unpacking and some other things like multiple arguments for subscripts. """ def __init__(self, items, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.items = items def get_items(self): return list(self.items) def allows_assignments(self): for item in self.items: if not item.allows_assignments(): return False return True def __repr__(self): return 'TupleExpression(%r)' % (self.items,) class ConcatExpression(Expression): """ For {{ foo ~ bar }}. Because of various reasons (especially because unicode conversion takes place for the left and right expression and is better optimized that way) """ def __init__(self, args, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.args = args def get_items(self): return list(self.args) def __repr__(self): return 'ConcatExpression(%r)' % (self.items,) class CompareExpression(Expression): """ {{ foo == bar }}, {{ foo >= bar }} etc. """ def __init__(self, expr, ops, lineno=None, filename=None): Expression.__init__(self, lineno, filename) self.expr = expr self.ops = ops def get_items(self): return [self.expr] + list(chain(*self.ops)) def __repr__(self): return 'CompareExpression(%r, %r)' % ( self.expr, self.ops ) class MulExpression(BinaryExpression): """ {{ foo * bar }} """ class DivExpression(BinaryExpression): """ {{ foo / bar }} """ class FloorDivExpression(BinaryExpression): """ {{ foo // bar }} """ class AddExpression(BinaryExpression): """ {{ foo + bar }} """ class SubExpression(BinaryExpression): """ {{ foo - bar }} """ class ModExpression(BinaryExpression): """ {{ foo % bar }} """ class PowExpression(BinaryExpression): """ {{ foo ** bar }} """ class AndExpression(BinaryExpression): """ {{ foo and bar }} """ class OrExpression(BinaryExpression): """ {{ foo or bar }} """ class NotExpression(UnaryExpression): """ {{ not foo }} """ class NegExpression(UnaryExpression): """ {{ -foo }} """ class PosExpression(UnaryExpression): """ {{ +foo }} """
gpl-2.0
jamesmcm/luigi
test/util_test.py
13
6224
# -*- coding: utf-8 -*- # # Copyright 2016 VNG Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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 helpers import LuigiTestCase, RunOnceTask import luigi import luigi.task from luigi.util import inherits, requires class BasicsTest(LuigiTestCase): # following tests using inherits decorator def test_task_ids_using_inherits(self): class ParentTask(luigi.Task): my_param = luigi.Parameter() luigi.namespace('blah') @inherits(ParentTask) class ChildTask(luigi.Task): def requires(self): return self.clone(ParentTask) luigi.namespace('') child_task = ChildTask(my_param='hello') self.assertEqual(str(child_task), 'blah.ChildTask(my_param=hello)') self.assertIn(ParentTask(my_param='hello'), luigi.task.flatten(child_task.requires())) def test_task_ids_using_inherits_2(self): # Here we use this decorator in a unnormal way. # But it should still work. class ParentTask(luigi.Task): my_param = luigi.Parameter() decorator = inherits(ParentTask) luigi.namespace('blah') class ChildTask(luigi.Task): def requires(self): return self.clone_parent() luigi.namespace('') ChildTask = decorator(ChildTask) child_task = ChildTask(my_param='hello') self.assertEqual(str(child_task), 'blah.ChildTask(my_param=hello)') self.assertIn(ParentTask(my_param='hello'), luigi.task.flatten(child_task.requires())) def _setup_parent_and_child_inherits(self): class ParentTask(luigi.Task): my_parameter = luigi.Parameter() class_variable = 'notset' def run(self): self.__class__.class_variable = self.my_parameter def complete(self): return self.class_variable == 'actuallyset' @inherits(ParentTask) class ChildTask(RunOnceTask): def requires(self): return self.clone_parent() return ParentTask def test_inherits_has_effect_run_child(self): ParentTask = self._setup_parent_and_child_inherits() self.assertTrue(self.run_locally_split('ChildTask --my-parameter actuallyset')) self.assertEqual(ParentTask.class_variable, 'actuallyset') def test_inherits_has_effect_run_parent(self): ParentTask = self._setup_parent_and_child_inherits() self.assertTrue(self.run_locally_split('ParentTask --my-parameter actuallyset')) self.assertEqual(ParentTask.class_variable, 'actuallyset') def _setup_inherits_inheritence(self): class InheritedTask(luigi.Task): pass class ParentTask(luigi.Task): pass @inherits(InheritedTask) class ChildTask(ParentTask): pass return ChildTask def test_inherits_has_effect_MRO(self): ChildTask = self._setup_inherits_inheritence() self.assertNotEqual(str(ChildTask.__mro__[0]), str(ChildTask.__mro__[1])) # following tests using requires decorator def test_task_ids_using_requries(self): class ParentTask(luigi.Task): my_param = luigi.Parameter() luigi.namespace('blah') @requires(ParentTask) class ChildTask(luigi.Task): pass luigi.namespace('') child_task = ChildTask(my_param='hello') self.assertEqual(str(child_task), 'blah.ChildTask(my_param=hello)') self.assertIn(ParentTask(my_param='hello'), luigi.task.flatten(child_task.requires())) def test_task_ids_using_requries_2(self): # Here we use this decorator in a unnormal way. # But it should still work. class ParentTask(luigi.Task): my_param = luigi.Parameter() decorator = requires(ParentTask) luigi.namespace('blah') class ChildTask(luigi.Task): pass luigi.namespace('') ChildTask = decorator(ChildTask) child_task = ChildTask(my_param='hello') self.assertEqual(str(child_task), 'blah.ChildTask(my_param=hello)') self.assertIn(ParentTask(my_param='hello'), luigi.task.flatten(child_task.requires())) def _setup_parent_and_child(self): class ParentTask(luigi.Task): my_parameter = luigi.Parameter() class_variable = 'notset' def run(self): self.__class__.class_variable = self.my_parameter def complete(self): return self.class_variable == 'actuallyset' @requires(ParentTask) class ChildTask(RunOnceTask): pass return ParentTask def test_requires_has_effect_run_child(self): ParentTask = self._setup_parent_and_child() self.assertTrue(self.run_locally_split('ChildTask --my-parameter actuallyset')) self.assertEqual(ParentTask.class_variable, 'actuallyset') def test_requires_has_effect_run_parent(self): ParentTask = self._setup_parent_and_child() self.assertTrue(self.run_locally_split('ParentTask --my-parameter actuallyset')) self.assertEqual(ParentTask.class_variable, 'actuallyset') def _setup_requires_inheritence(self): class RequiredTask(luigi.Task): pass class ParentTask(luigi.Task): pass @requires(RequiredTask) class ChildTask(ParentTask): pass return ChildTask def test_requires_has_effect_MRO(self): ChildTask = self._setup_requires_inheritence() self.assertNotEqual(str(ChildTask.__mro__[0]), str(ChildTask.__mro__[1]))
apache-2.0
pitch-sands/i-MPI
flask/Lib/site-packages/whoosh/fields.py
36
51656
# Copyright 2007 Matt Chaput. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are # those of the authors and should not be interpreted as representing official # policies, either expressed or implied, of Matt Chaput. """ Contains functions and classes related to fields. """ import datetime, fnmatch, re, struct, sys from array import array from decimal import Decimal from whoosh import analysis, columns, formats from whoosh.compat import u, b, PY3 from whoosh.compat import with_metaclass from whoosh.compat import itervalues, xrange from whoosh.compat import bytes_type, string_type, integer_types, text_type from whoosh.system import emptybytes from whoosh.system import pack_byte, unpack_byte from whoosh.util.numeric import to_sortable, from_sortable from whoosh.util.numeric import typecode_max, NaN from whoosh.util.text import utf8encode, utf8decode from whoosh.util.times import datetime_to_long, long_to_datetime # Exceptions class FieldConfigurationError(Exception): pass class UnknownFieldError(Exception): pass # Field Types class FieldType(object): """Represents a field configuration. The FieldType object supports the following attributes: * format (formats.Format): the storage format for the field's contents. * analyzer (analysis.Analyzer): the analyzer to use to turn text into terms. * vector (formats.Format): the storage format for the field's vectors (forward index), or None if the field should not store vectors. * scorable (boolean): whether searches against this field may be scored. This controls whether the index stores per-document field lengths for this field. * stored (boolean): whether the content of this field is stored for each document. For example, in addition to indexing the title of a document, you usually want to store the title so it can be presented as part of the search results. * unique (boolean): whether this field's value is unique to each document. For example, 'path' or 'ID'. IndexWriter.update_document() will use fields marked as 'unique' to find the previous version of a document being updated. * multitoken_query is a string indicating what kind of query to use when a "word" in a user query parses into multiple tokens. The string is interpreted by the query parser. The strings understood by the default query parser are "first" (use first token only), "and" (join the tokens with an AND query), "or" (join the tokens with OR), "phrase" (join the tokens with a phrase query), and "default" (use the query parser's default join type). The constructor for the base field type simply lets you supply your own configured field format, vector format, and scorable and stored values. Subclasses may configure some or all of this for you. """ analyzer = format = vector = scorable = stored = unique = None indexed = True multitoken_query = "default" sortable_typecode = None spelling = False column_type = None def __init__(self, format, analyzer, vector=None, scorable=False, stored=False, unique=False, multitoken_query="default", sortable=False): assert isinstance(format, formats.Format) self.format = format self.analyzer = analyzer self.vector = vector self.scorable = scorable self.stored = stored self.unique = unique self.multitoken_query = multitoken_query self.set_sortable(sortable) def __repr__(self): temp = "%s(format=%r, vector=%r, scorable=%s, stored=%s, unique=%s)" return temp % (self.__class__.__name__, self.format, self.vector, self.scorable, self.stored, self.unique) def __eq__(self, other): return all((isinstance(other, FieldType), (self.format == other.format), (self.vector == other.vector), (self.scorable == other.scorable), (self.stored == other.stored), (self.unique == other.unique), (self.column_type == other.column_type))) def __ne__(self, other): return not(self.__eq__(other)) # Column methods def set_sortable(self, sortable): if sortable: if isinstance(sortable, columns.Column): self.column_type = sortable else: self.column_type = self.default_column() else: self.column_type = None def default_column(self): return columns.VarBytesColumn() # Methods for converting input into indexing information def index(self, value, **kwargs): """Returns an iterator of (btext, frequency, weight, encoded_value) tuples for each unique word in the input value. The default implementation uses the ``analyzer`` attribute to tokenize the value into strings, then encodes them into bytes using UTF-8. """ if not self.format: raise Exception("%s field %r cannot index without a format" % (self.__class__.__name__, self)) if not isinstance(value, (text_type, list, tuple)): raise ValueError("%r is not unicode or sequence" % value) assert isinstance(self.format, formats.Format) if "mode" not in kwargs: kwargs["mode"] = "index" word_values = self.format.word_values ana = self.analyzer for tstring, freq, wt, vbytes in word_values(value, ana, **kwargs): yield (utf8encode(tstring)[0], freq, wt, vbytes) def process_text(self, qstring, mode='', **kwargs): """Analyzes the given string and returns an iterator of token texts. >>> field = fields.TEXT() >>> list(field.process_text("The ides of March")) ["ides", "march"] """ if not self.format: raise Exception("%s field has no format" % self) return (t.text for t in self.tokenize(qstring, mode=mode, **kwargs)) def tokenize(self, value, **kwargs): """Analyzes the given string and returns an iterator of Token objects (note: for performance reasons, actually the same token yielded over and over with different attributes). """ if not self.analyzer: raise Exception("%s field has no analyzer" % self.__class__) return self.analyzer(value, **kwargs) def to_bytes(self, value): """Returns a bytes representation of the given value, appropriate to be written to disk. The default implementation assumes a unicode value and encodes it using UTF-8. """ if isinstance(value, (list, tuple)): value = value[0] if not isinstance(value, bytes_type): value = utf8encode(value)[0] return value def to_column_value(self, value): """Returns an object suitable to be inserted into the document values column for this field. The default implementation simply calls ``self.to_bytes(value)``. """ return self.to_bytes(value) def from_column_value(self, value): return self.from_bytes(value) def from_bytes(self, bs): return utf8decode(bs)[0] # Methods related to query parsing def self_parsing(self): """Subclasses should override this method to return True if they want the query parser to call the field's ``parse_query()`` method instead of running the analyzer on text in this field. This is useful where the field needs full control over how queries are interpreted, such as in the numeric field type. """ return False def parse_query(self, fieldname, qstring, boost=1.0): """When ``self_parsing()`` returns True, the query parser will call this method to parse basic query text. """ raise NotImplementedError(self.__class__.__name__) def parse_range(self, fieldname, start, end, startexcl, endexcl, boost=1.0): """When ``self_parsing()`` returns True, the query parser will call this method to parse range query text. If this method returns None instead of a query object, the parser will fall back to parsing the start and end terms using process_text(). """ return None # Methods related to sortings def sortable_terms(self, ixreader, fieldname): """Returns an iterator of the "sortable" tokens in the given reader and field. These values can be used for sorting. The default implementation simply returns all tokens in the field. This can be overridden by field types such as NUMERIC where some values in a field are not useful for sorting. """ return ixreader.lexicon(fieldname) # Methods related to spelling def separate_spelling(self): """Returns True if this field requires special handling of the words that go into the field's word graph. The default behavior is to return True if the field is "spelled" but not indexed, or if the field is indexed but the analyzer has morphological transformations (e.g. stemming). Exotic field types may need to override this behavior. This method should return False if the field does not support spelling (i.e. the ``spelling`` attribute is False). """ return self.spelling and self.analyzer.has_morph() def spellable_words(self, value): """Returns an iterator of each unique word (in sorted order) in the input value, suitable for inclusion in the field's word graph. The default behavior is to call the field analyzer with the keyword argument ``no_morph=True``, which should make the analyzer skip any morphological transformation filters (e.g. stemming) to preserve the original form of the words. Exotic field types may need to override this behavior. """ if isinstance(value, (list, tuple)): words = value else: words = [token.text for token in self.analyzer(value, no_morph=True)] return iter(sorted(set(words))) def has_morph(self): """Returns True if this field by default performs morphological transformations on its terms, e.g. stemming. """ if self.analyzer: return self.analyzer.has_morph() else: return False # Methods related to the posting/vector formats def supports(self, name): """Returns True if the underlying format supports the given posting value type. >>> field = TEXT() >>> field.supports("positions") True >>> field.supports("characters") False """ return self.format.supports(name) def clean(self): """Clears any cached information in the field and any child objects. """ if self.format and hasattr(self.format, "clean"): self.format.clean() if self.vector and hasattr(self.vector, "clean"): self.vector.clean() # Event methods def on_add(self, schema, fieldname): pass def on_remove(self, schema, fieldname): pass class ID(FieldType): """Configured field type that indexes the entire value of the field as one token. This is useful for data you don't want to tokenize, such as the path of a file. """ __inittypes__ = dict(stored=bool, unique=bool, field_boost=float) def __init__(self, stored=False, unique=False, field_boost=1.0, spelling=False, sortable=False, analyzer=None): """ :param stored: Whether the value of this field is stored with the document. """ self.analyzer = analyzer or analysis.IDAnalyzer() self.format = formats.Existence(field_boost=field_boost) self.stored = stored self.unique = unique self.spelling = spelling self.set_sortable(sortable) class IDLIST(FieldType): """Configured field type for fields containing IDs separated by whitespace and/or punctuation (or anything else, using the expression param). """ __inittypes__ = dict(stored=bool, unique=bool, expression=bool, field_boost=float) def __init__(self, stored=False, unique=False, expression=None, field_boost=1.0, spelling=False): """ :param stored: Whether the value of this field is stored with the document. :param unique: Whether the value of this field is unique per-document. :param expression: The regular expression object to use to extract tokens. The default expression breaks tokens on CRs, LFs, tabs, spaces, commas, and semicolons. """ expression = expression or re.compile(r"[^\r\n\t ,;]+") self.analyzer = analysis.RegexAnalyzer(expression=expression) self.format = formats.Existence(field_boost=field_boost) self.stored = stored self.unique = unique self.spelling = spelling class NUMERIC(FieldType): """Special field type that lets you index integer or floating point numbers in relatively short fixed-width terms. The field converts numbers to sortable bytes for you before indexing. You specify the numeric type of the field (``int`` or ``float``) when you create the ``NUMERIC`` object. The default is ``int``. For ``int``, you can specify a size in bits (``32`` or ``64``). For both ``int`` and ``float`` you can specify a ``signed`` keyword argument (default is ``True``). >>> schema = Schema(path=STORED, position=NUMERIC(int, 64, signed=False)) >>> ix = storage.create_index(schema) >>> with ix.writer() as w: ... w.add_document(path="/a", position=5820402204) ... You can also use the NUMERIC field to store Decimal instances by specifying a type of ``int`` or ``long`` and the ``decimal_places`` keyword argument. This simply multiplies each number by ``(10 ** decimal_places)`` before storing it as an integer. Of course this may throw away decimal prcesision (by truncating, not rounding) and imposes the same maximum value limits as ``int``/``long``, but these may be acceptable for certain applications. >>> from decimal import Decimal >>> schema = Schema(path=STORED, position=NUMERIC(int, decimal_places=4)) >>> ix = storage.create_index(schema) >>> with ix.writer() as w: ... w.add_document(path="/a", position=Decimal("123.45") ... """ def __init__(self, numtype=int, bits=32, stored=False, unique=False, field_boost=1.0, decimal_places=0, shift_step=4, signed=True, sortable=False, default=None): """ :param numtype: the type of numbers that can be stored in this field, either ``int``, ``float``. If you use ``Decimal``, use the ``decimal_places`` argument to control how many decimal places the field will store. :param bits: When ``numtype`` is ``int``, the number of bits to use to store the number: 8, 16, 32, or 64. :param stored: Whether the value of this field is stored with the document. :param unique: Whether the value of this field is unique per-document. :param decimal_places: specifies the number of decimal places to save when storing Decimal instances. If you set this, you will always get Decimal instances back from the field. :param shift_steps: The number of bits of precision to shift away at each tiered indexing level. Values should generally be 1-8. Lower values yield faster searches but take up more space. A value of `0` means no tiered indexing. :param signed: Whether the numbers stored in this field may be negative. """ # Allow users to specify strings instead of Python types in case # docstring isn't clear if numtype == "int": numtype = int if numtype == "float": numtype = float # Raise an error if the user tries to use a type other than int or # float if numtype is Decimal: numtype = int if not decimal_places: raise TypeError("To store Decimal instances, you must set the " "decimal_places argument") elif numtype not in (int, float): raise TypeError("Can't use %r as a type, use int or float" % numtype) # Sanity check if numtype is float and decimal_places: raise Exception("A float type and decimal_places argument %r are " "incompatible" % decimal_places) intsizes = [8, 16, 32, 64] intcodes = ["B", "H", "I", "Q"] # Set up field configuration based on type and size if numtype is float: bits = 64 # Floats are converted to 64 bit ints else: if bits not in intsizes: raise Exception("Invalid bits %r, use 8, 16, 32, or 64" % bits) # Type code for the *sortable* representation self.sortable_typecode = intcodes[intsizes.index(bits)] self._struct = struct.Struct(">" + self.sortable_typecode) self.numtype = numtype self.bits = bits self.stored = stored self.unique = unique self.decimal_places = decimal_places self.shift_step = shift_step self.signed = signed self.analyzer = analysis.IDAnalyzer() self.format = formats.Existence(field_boost=field_boost) self.min_value, self.max_value = self._min_max() # Column configuration if default is None: if numtype is int: default = typecode_max[self.sortable_typecode] else: default = NaN elif not self.is_valid(default): raise Exception("The default %r is not a valid number for this " "field" % default) self.default = default self.set_sortable(sortable) def __getstate__(self): d = self.__dict__.copy() if "_struct" in d: del d["_struct"] return d def __setstate__(self, d): self.__dict__.update(d) self._struct = struct.Struct(">" + self.sortable_typecode) if "min_value" not in d: d["min_value"], d["max_value"] = self._min_max() def _min_max(self): numtype = self.numtype bits = self.bits signed = self.signed # Calculate the minimum and maximum possible values for error checking min_value = from_sortable(numtype, bits, signed, 0) max_value = from_sortable(numtype, bits, signed, 2 ** bits - 1) return min_value, max_value def default_column(self): return columns.NumericColumn(self.sortable_typecode, default=self.default) def is_valid(self, x): try: x = self.to_bytes(x) except ValueError: return False except OverflowError: return False return True def index(self, num, **kwargs): # If the user gave us a list of numbers, recurse on the list if isinstance(num, (list, tuple)): for n in num: for item in self.index(n): yield item return # word, freq, weight, valuestring if self.shift_step: for shift in xrange(0, self.bits, self.shift_step): yield (self.to_bytes(num, shift), 1, 1.0, emptybytes) else: yield (self.to_bytes(num), 1, 1.0, emptybytes) def prepare_number(self, x): if x == emptybytes or x is None: return x dc = self.decimal_places if dc and isinstance(x, (string_type, Decimal)): x = Decimal(x) * (10 ** dc) elif isinstance(x, Decimal): raise TypeError("Can't index a Decimal object unless you specified " "decimal_places on the field") try: x = self.numtype(x) except OverflowError: raise ValueError("Value %r overflowed number type %r" % (x, self.numtype)) if x < self.min_value or x > self.max_value: raise ValueError("Numeric field value %s out of range [%s, %s]" % (x, self.min_value, self.max_value)) return x def unprepare_number(self, x): dc = self.decimal_places if dc: s = str(x) x = Decimal(s[:-dc] + "." + s[-dc:]) return x def to_column_value(self, x): if isinstance(x, (list, tuple, array)): x = x[0] x = self.prepare_number(x) return to_sortable(self.numtype, self.bits, self.signed, x) def from_column_value(self, x): x = from_sortable(self.numtype, self.bits, self.signed, x) return self.unprepare_number(x) def to_bytes(self, x, shift=0): # Try to avoid re-encoding; this sucks because on Python 2 we can't # tell the difference between a string and encoded bytes, so we have # to require the user use unicode when they mean string if isinstance(x, bytes_type): return x if x == emptybytes or x is None: return self.sortable_to_bytes(0) x = self.prepare_number(x) x = to_sortable(self.numtype, self.bits, self.signed, x) return self.sortable_to_bytes(x, shift) def sortable_to_bytes(self, x, shift=0): if shift: x >>= shift return pack_byte(shift) + self._struct.pack(x) def from_bytes(self, bs): x = self._struct.unpack(bs[1:])[0] x = from_sortable(self.numtype, self.bits, self.signed, x) x = self.unprepare_number(x) return x def process_text(self, text, **kwargs): return (self.to_bytes(text),) def self_parsing(self): return True def parse_query(self, fieldname, qstring, boost=1.0): from whoosh import query from whoosh.qparser.common import QueryParserError if qstring == "*": return query.Every(fieldname, boost=boost) if not self.is_valid(qstring): raise QueryParserError("%r is not a valid number" % qstring) token = self.to_bytes(qstring) return query.Term(fieldname, token, boost=boost) def parse_range(self, fieldname, start, end, startexcl, endexcl, boost=1.0): from whoosh import query from whoosh.qparser.common import QueryParserError if start is not None: if not self.is_valid(start): raise QueryParserError("Range start %r is not a valid number" % start) start = self.prepare_number(start) if end is not None: if not self.is_valid(end): raise QueryParserError("Range end %r is not a valid number" % end) end = self.prepare_number(end) return query.NumericRange(fieldname, start, end, startexcl, endexcl, boost=boost) def sortable_terms(self, ixreader, fieldname): zero = b("\x00") for token in ixreader.lexicon(fieldname): if token[0:1] != zero: # Only yield the full-precision values break yield token class DATETIME(NUMERIC): """Special field type that lets you index datetime objects. The field converts the datetime objects to sortable text for you before indexing. Since this field is based on Python's datetime module it shares all the limitations of that module, such as the inability to represent dates before year 1 in the proleptic Gregorian calendar. However, since this field stores datetimes as an integer number of microseconds, it could easily represent a much wider range of dates if the Python datetime implementation ever supports them. >>> schema = Schema(path=STORED, date=DATETIME) >>> ix = storage.create_index(schema) >>> w = ix.writer() >>> w.add_document(path="/a", date=datetime.now()) >>> w.commit() """ __inittypes__ = dict(stored=bool, unique=bool) def __init__(self, stored=False, unique=False, sortable=False): """ :param stored: Whether the value of this field is stored with the document. :param unique: Whether the value of this field is unique per-document. """ super(DATETIME, self).__init__(int, 64, stored=stored, unique=unique, shift_step=8, sortable=sortable) def prepare_datetime(self, x): from whoosh.util.times import floor if isinstance(x, text_type): # For indexing, support same strings as for query parsing -- # convert unicode to datetime object x = self._parse_datestring(x) x = floor(x) # this makes most sense (unspecified = lowest) if isinstance(x, datetime.datetime): return datetime_to_long(x) elif isinstance(x, bytes_type): return x else: raise Exception("%r is not a datetime" % (x,)) def to_column_value(self, x): if isinstance(x, bytes_type): raise Exception("%r is not a datetime" % (x,)) if isinstance(x, (list, tuple)): x = x[0] return self.prepare_datetime(x) def from_column_value(self, x): return long_to_datetime(x) def to_bytes(self, x, shift=0): x = self.prepare_datetime(x) return NUMERIC.to_bytes(self, x, shift=shift) def from_bytes(self, bs): x = NUMERIC.from_bytes(self, bs) return long_to_datetime(x) def _parse_datestring(self, qstring): # This method parses a very simple datetime representation of the form # YYYY[MM[DD[hh[mm[ss[uuuuuu]]]]]] from whoosh.util.times import adatetime, fix, is_void qstring = qstring.replace(" ", "").replace("-", "").replace(".", "") year = month = day = hour = minute = second = microsecond = None if len(qstring) >= 4: year = int(qstring[:4]) if len(qstring) >= 6: month = int(qstring[4:6]) if len(qstring) >= 8: day = int(qstring[6:8]) if len(qstring) >= 10: hour = int(qstring[8:10]) if len(qstring) >= 12: minute = int(qstring[10:12]) if len(qstring) >= 14: second = int(qstring[12:14]) if len(qstring) == 20: microsecond = int(qstring[14:]) at = fix(adatetime(year, month, day, hour, minute, second, microsecond)) if is_void(at): raise Exception("%r is not a parseable date" % qstring) return at def parse_query(self, fieldname, qstring, boost=1.0): from whoosh import query from whoosh.util.times import is_ambiguous try: at = self._parse_datestring(qstring) except: e = sys.exc_info()[1] return query.error_query(e) if is_ambiguous(at): startnum = datetime_to_long(at.floor()) endnum = datetime_to_long(at.ceil()) return query.NumericRange(fieldname, startnum, endnum) else: return query.Term(fieldname, at, boost=boost) def parse_range(self, fieldname, start, end, startexcl, endexcl, boost=1.0): from whoosh import query if start is None and end is None: return query.Every(fieldname, boost=boost) if start is not None: startdt = self._parse_datestring(start).floor() start = datetime_to_long(startdt) if end is not None: enddt = self._parse_datestring(end).ceil() end = datetime_to_long(enddt) return query.NumericRange(fieldname, start, end, boost=boost) class BOOLEAN(FieldType): """Special field type that lets you index boolean values (True and False). The field converts the boolean values to text for you before indexing. >>> schema = Schema(path=STORED, done=BOOLEAN) >>> ix = storage.create_index(schema) >>> w = ix.writer() >>> w.add_document(path="/a", done=False) >>> w.commit() """ bytestrings = (b("f"), b("t")) trues = frozenset(u("t true yes 1").split()) falses = frozenset(u("f false no 0").split()) __inittypes__ = dict(stored=bool, field_boost=float) def __init__(self, stored=False, field_boost=1.0): """ :param stored: Whether the value of this field is stored with the document. """ self.stored = stored self.field_boost = field_boost self.format = formats.Existence(field_boost=field_boost) def _obj_to_bool(self, x): # We special case strings such as "true", "false", "yes", "no", but # otherwise call bool() on the query value. This lets you pass objects # as query values and do the right thing. if isinstance(x, string_type) and x.lower() in self.trues: x = True elif isinstance(x, string_type) and x.lower() in self.falses: x = False else: x = bool(x) return x def to_bytes(self, x): if isinstance(x, bytes_type): return x elif isinstance(x, string_type): x = x.lower() in self.trues else: x = bool(x) bs = self.bytestrings[int(x)] return bs def index(self, bit, **kwargs): if isinstance(bit, string_type): bit = bit.lower() in self.trues else: bit = bool(bit) # word, freq, weight, valuestring return [(self.bytestrings[int(bit)], 1, 1.0, emptybytes)] def self_parsing(self): return True def parse_query(self, fieldname, qstring, boost=1.0): from whoosh import query if qstring == "*": return query.Every(fieldname, boost=boost) return query.Term(fieldname, self._obj_to_bool(qstring), boost=boost) class STORED(FieldType): """Configured field type for fields you want to store but not index. """ indexed = False stored = True def __init__(self): pass class COLUMN(FieldType): """Configured field type for fields you want to store as a per-document value column but not index. """ indexed = False stored = False def __init__(self, columnobj=None): if columnobj is None: columnobj = columns.VarBytesColumn() if not isinstance(columnobj, columns.Column): raise TypeError("%r is not a column object" % (columnobj,)) self.column_type = columnobj def to_bytes(self, v): return v def from_bytes(self, b): return b class KEYWORD(FieldType): """Configured field type for fields containing space-separated or comma-separated keyword-like data (such as tags). The default is to not store positional information (so phrase searching is not allowed in this field) and to not make the field scorable. """ __inittypes__ = dict(stored=bool, lowercase=bool, commas=bool, scorable=bool, unique=bool, field_boost=float) def __init__(self, stored=False, lowercase=False, commas=False, vector=None, scorable=False, unique=False, field_boost=1.0, spelling=False, sortable=False): """ :param stored: Whether to store the value of the field with the document. :param comma: Whether this is a comma-separated field. If this is False (the default), it is treated as a space-separated field. :param scorable: Whether this field is scorable. """ self.analyzer = analysis.KeywordAnalyzer(lowercase=lowercase, commas=commas) self.format = formats.Frequency(field_boost=field_boost) self.scorable = scorable self.stored = stored self.unique = unique self.spelling = spelling if vector: if type(vector) is type: vector = vector() elif isinstance(vector, formats.Format): pass else: vector = self.format else: vector = None self.vector = vector if sortable: self.column_type = self.default_column() class TEXT(FieldType): """Configured field type for text fields (for example, the body text of an article). The default is to store positional information to allow phrase searching. This field type is always scorable. """ __inittypes__ = dict(analyzer=analysis.Analyzer, phrase=bool, vector=object, stored=bool, field_boost=float) def __init__(self, analyzer=None, phrase=True, chars=False, vector=None, stored=False, field_boost=1.0, multitoken_query="default", spelling=False, sortable=False, lang=None): """ :param analyzer: The analysis.Analyzer to use to index the field contents. See the analysis module for more information. If you omit this argument, the field uses analysis.StandardAnalyzer. :param phrase: Whether the store positional information to allow phrase searching. :param chars: Whether to store character ranges along with positions. If this is True, "phrase" is also implied. :param vector: A :class:`whoosh.formats.Format` object to use to store term vectors, or ``True`` to store vectors using the same format as the inverted index, or ``None`` or ``False`` to not store vectors. By default, fields do not store term vectors. :param stored: Whether to store the value of this field with the document. Since this field type generally contains a lot of text, you should avoid storing it with the document unless you need to, for example to allow fast excerpts in the search results. :param spelling: Whether to generate word graphs for this field to make spelling suggestions much faster. :param sortable: If True, make this field sortable using the default column type. If you pass a :class:`whoosh.columns.Column` instance instead of True, the field will use the given column type. :param lang: automaticaly configure a :class:`whoosh.analysis.LanguageAnalyzer` for the given language. This is ignored if you also specify an ``analyzer``. """ if analyzer: self.analyzer = analyzer elif lang: self.analyzer = analysis.LanguageAnalyzer(lang) else: self.analyzer = analysis.StandardAnalyzer() if chars: formatclass = formats.Characters elif phrase: formatclass = formats.Positions else: formatclass = formats.Frequency self.format = formatclass(field_boost=field_boost) if vector: if type(vector) is type: vector = vector() elif isinstance(vector, formats.Format): pass else: vector = formatclass() else: vector = None self.vector = vector if sortable: if isinstance(sortable, columns.Column): self.column_type = sortable else: self.column_type = columns.VarBytesColumn() else: self.column_type = None self.multitoken_query = multitoken_query self.scorable = True self.stored = stored self.spelling = spelling class NGRAM(FieldType): """Configured field that indexes text as N-grams. For example, with a field type NGRAM(3,4), the value "hello" will be indexed as tokens "hel", "hell", "ell", "ello", "llo". This field type chops the entire text into N-grams, including whitespace and punctuation. See :class:`NGRAMWORDS` for a field type that breaks the text into words first before chopping the words into N-grams. """ __inittypes__ = dict(minsize=int, maxsize=int, stored=bool, field_boost=float, queryor=bool, phrase=bool) scorable = True def __init__(self, minsize=2, maxsize=4, stored=False, field_boost=1.0, queryor=False, phrase=False, sortable=False): """ :param minsize: The minimum length of the N-grams. :param maxsize: The maximum length of the N-grams. :param stored: Whether to store the value of this field with the document. Since this field type generally contains a lot of text, you should avoid storing it with the document unless you need to, for example to allow fast excerpts in the search results. :param queryor: if True, combine the N-grams with an Or query. The default is to combine N-grams with an And query. :param phrase: store positions on the N-grams to allow exact phrase searching. The default is off. """ formatclass = formats.Frequency if phrase: formatclass = formats.Positions self.analyzer = analysis.NgramAnalyzer(minsize, maxsize) self.format = formatclass(field_boost=field_boost) self.stored = stored self.queryor = queryor self.set_sortable(sortable) def self_parsing(self): return True def parse_query(self, fieldname, qstring, boost=1.0): from whoosh import query terms = [query.Term(fieldname, g) for g in self.process_text(qstring, mode='query')] cls = query.Or if self.queryor else query.And return cls(terms, boost=boost) class NGRAMWORDS(NGRAM): """Configured field that chops text into words using a tokenizer, lowercases the words, and then chops the words into N-grams. """ __inittypes__ = dict(minsize=int, maxsize=int, stored=bool, field_boost=float, tokenizer=analysis.Tokenizer, at=str, queryor=bool) scorable = True def __init__(self, minsize=2, maxsize=4, stored=False, field_boost=1.0, tokenizer=None, at=None, queryor=False, sortable=False): """ :param minsize: The minimum length of the N-grams. :param maxsize: The maximum length of the N-grams. :param stored: Whether to store the value of this field with the document. Since this field type generally contains a lot of text, you should avoid storing it with the document unless you need to, for example to allow fast excerpts in the search results. :param tokenizer: an instance of :class:`whoosh.analysis.Tokenizer` used to break the text into words. :param at: if 'start', only takes N-grams from the start of the word. If 'end', only takes N-grams from the end. Otherwise the default is to take all N-grams from each word. :param queryor: if True, combine the N-grams with an Or query. The default is to combine N-grams with an And query. """ self.analyzer = analysis.NgramWordAnalyzer(minsize, maxsize, tokenizer, at=at) self.format = formats.Frequency(field_boost=field_boost) self.stored = stored self.queryor = queryor self.set_sortable(sortable) # Schema class class MetaSchema(type): def __new__(cls, name, bases, attrs): super_new = super(MetaSchema, cls).__new__ if not any(b for b in bases if isinstance(b, MetaSchema)): # If this isn't a subclass of MetaSchema, don't do anything special return super_new(cls, name, bases, attrs) # Create the class special_attrs = {} for key in list(attrs.keys()): if key.startswith("__"): special_attrs[key] = attrs.pop(key) new_class = super_new(cls, name, bases, special_attrs) fields = {} for b in bases: if hasattr(b, "_clsfields"): fields.update(b._clsfields) fields.update(attrs) new_class._clsfields = fields return new_class def schema(self): return Schema(**self._clsfields) class Schema(object): """Represents the collection of fields in an index. Maps field names to FieldType objects which define the behavior of each field. Low-level parts of the index use field numbers instead of field names for compactness. This class has several methods for converting between the field name, field number, and field object itself. """ def __init__(self, **fields): """ All keyword arguments to the constructor are treated as fieldname = fieldtype pairs. The fieldtype can be an instantiated FieldType object, or a FieldType sub-class (in which case the Schema will instantiate it with the default constructor before adding it). For example:: s = Schema(content = TEXT, title = TEXT(stored = True), tags = KEYWORD(stored = True)) """ self._fields = {} self._dyn_fields = {} for name in sorted(fields.keys()): self.add(name, fields[name]) def copy(self): """Returns a shallow copy of the schema. The field instances are not deep copied, so they are shared between schema copies. """ return self.__class__(**self._fields) def __eq__(self, other): return (other.__class__ is self.__class__ and list(self.items()) == list(other.items())) def __ne__(self, other): return not(self.__eq__(other)) def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.names()) def __iter__(self): """Returns the field objects in this schema. """ return iter(self._fields.values()) def __getitem__(self, name): """Returns the field associated with the given field name. """ if name in self._fields: return self._fields[name] for expr, fieldtype in itervalues(self._dyn_fields): if expr.match(name): return fieldtype raise KeyError("No field named %r" % (name,)) def __len__(self): """Returns the number of fields in this schema. """ return len(self._fields) def __contains__(self, fieldname): """Returns True if a field by the given name is in this schema. """ # Defined in terms of __getitem__ so that there's only one method to # override to provide dynamic fields try: field = self[fieldname] return field is not None except KeyError: return False def items(self): """Returns a list of ("fieldname", field_object) pairs for the fields in this schema. """ return sorted(self._fields.items()) def names(self, check_names=None): """Returns a list of the names of the fields in this schema. :param check_names: (optional) sequence of field names to check whether the schema accepts them as (dynamic) field names - acceptable names will also be in the result list. Note: You may also have static field names in check_names, that won't create duplicates in the result list. Unsupported names will not be in the result list. """ fieldnames = set(self._fields.keys()) if check_names is not None: check_names = set(check_names) - fieldnames fieldnames.update(fieldname for fieldname in check_names if fieldname in self) return sorted(fieldnames) def clean(self): for field in self: field.clean() def add(self, name, fieldtype, glob=False): """Adds a field to this schema. :param name: The name of the field. :param fieldtype: An instantiated fields.FieldType object, or a FieldType subclass. If you pass an instantiated object, the schema will use that as the field configuration for this field. If you pass a FieldType subclass, the schema will automatically instantiate it with the default constructor. """ # Check field name if name.startswith("_"): raise FieldConfigurationError("Field names cannot start with an " "underscore") if " " in name: raise FieldConfigurationError("Field names cannot contain spaces") if name in self._fields or (glob and name in self._dyn_fields): raise FieldConfigurationError("Schema already has a field %r" % name) # If the user passed a type rather than an instantiated field object, # instantiate it automatically if type(fieldtype) is type: try: fieldtype = fieldtype() except: e = sys.exc_info()[1] raise FieldConfigurationError("Error: %s instantiating field " "%r: %r" % (e, name, fieldtype)) if not isinstance(fieldtype, FieldType): raise FieldConfigurationError("%r is not a FieldType object" % fieldtype) if glob: expr = re.compile(fnmatch.translate(name)) self._dyn_fields[name] = (expr, fieldtype) else: fieldtype.on_add(self, name) self._fields[name] = fieldtype def remove(self, fieldname): if fieldname in self._fields: self._fields[fieldname].on_remove(self, fieldname) del self._fields[fieldname] elif fieldname in self._dyn_fields: del self._dyn_fields[fieldname] else: raise KeyError("No field named %r" % fieldname) def has_vectored_fields(self): """Returns True if any of the fields in this schema store term vectors. """ return any(ftype.vector for ftype in self) def has_scorable_fields(self): return any(ftype.scorable for ftype in self) def stored_names(self): """Returns a list of the names of fields that are stored. """ return [name for name, field in self.items() if field.stored] def scorable_names(self): """Returns a list of the names of fields that store field lengths. """ return [name for name, field in self.items() if field.scorable] def vector_names(self): """Returns a list of the names of fields that store vectors. """ return [name for name, field in self.items() if field.vector] def separate_spelling_names(self): """Returns a list of the names of fields that require special handling for generating spelling graphs... either because they store graphs but aren't indexed, or because the analyzer is stemmed. """ return [name for name, field in self.items() if field.spelling and field.separate_spelling()] class SchemaClass(with_metaclass(MetaSchema, Schema)): """Allows you to define a schema using declarative syntax, similar to Django models:: class MySchema(SchemaClass): path = ID date = DATETIME content = TEXT You can use inheritance to share common fields between schemas:: class Parent(SchemaClass): path = ID(stored=True) date = DATETIME class Child1(Parent): content = TEXT(positions=False) class Child2(Parent): tags = KEYWORD This class overrides ``__new__`` so instantiating your sub-class always results in an instance of ``Schema``. >>> class MySchema(SchemaClass): ... title = TEXT(stored=True) ... content = TEXT ... >>> s = MySchema() >>> type(s) <class 'whoosh.fields.Schema'> """ def __new__(cls, *args, **kwargs): obj = super(Schema, cls).__new__(Schema) kw = getattr(cls, "_clsfields", {}) kw.update(kwargs) obj.__init__(*args, **kw) return obj def ensure_schema(schema): if isinstance(schema, type) and issubclass(schema, Schema): schema = schema.schema() if not isinstance(schema, Schema): raise FieldConfigurationError("%r is not a Schema" % schema) return schema def merge_fielddict(d1, d2): keyset = set(d1.keys()) | set(d2.keys()) out = {} for name in keyset: field1 = d1.get(name) field2 = d2.get(name) if field1 and field2 and field1 != field2: raise Exception("Inconsistent field %r: %r != %r" % (name, field1, field2)) out[name] = field1 or field2 return out def merge_schema(s1, s2): schema = Schema() schema._fields = merge_fielddict(s1._fields, s2._fields) schema._dyn_fields = merge_fielddict(s1._dyn_fields, s2._dyn_fields) return schema def merge_schemas(schemas): schema = schemas[0] for i in xrange(1, len(schemas)): schema = merge_schema(schema, schemas[i]) return schema
bsd-3-clause
stacywsmith/ansible
lib/ansible/plugins/action/group_by.py
130
1556
# Copyright 2012, Jeroen Hoekx <jeroen@hoekx.be> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action import ActionBase class ActionModule(ActionBase): ''' Create inventory groups based on variables ''' ### We need to be able to modify the inventory TRANSFERS_FILES = False def run(self, tmp=None, task_vars=None): if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) if 'key' not in self._task.args: result['failed'] = True result['msg'] = "the 'key' param is required when using group_by" return result group_name = self._task.args.get('key') group_name = group_name.replace(' ','-') result['changed'] = False result['add_group'] = group_name return result
gpl-3.0
ESSolutions/ESSArch_Core
ESSArch_Core/maintenance/migrations/0001_initial.py
1
3077
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-01-24 20:01 import uuid from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('ip', '0064_informationpackage_appraisal_date'), ] operations = [ migrations.CreateModel( name='AppraisalRule', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('name', models.CharField(max_length=255)), ('type', models.CharField(choices=[('archival_object', 'Archival Object'), ('metadata', 'Metadata')], default='archival_object', max_length=100)), ('frequency', models.CharField(blank=True, default='', max_length=255)), ('specification', models.JSONField(default=None, null=True)), ('information_packages', models.ManyToManyField(related_name='appraisal_rules', to='ip.InformationPackage')), ], ), migrations.CreateModel( name='AppraisalJob', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('start_date', models.DateTimeField(null=True)), ('end_date', models.DateTimeField(null=True)), ('rule', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='jobs', to='maintenance.AppraisalRule')), ('status', models.CharField(choices=[('RECEIVED', 'RECEIVED'), ('RETRY', 'RETRY'), ('REVOKED', 'REVOKED'), ('SUCCESS', 'SUCCESS'), ( 'STARTED', 'STARTED'), ('FAILURE', 'FAILURE'), ('PENDING', 'PENDING')], default='PENDING', max_length=50)), ], ), migrations.CreateModel( name='AppraisalJobEntry', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('start_date', models.DateTimeField(null=True)), ('end_date', models.DateTimeField(null=True)), ('document', models.CharField(blank=True, max_length=255)), ('component', models.CharField(blank=True, max_length=255)), ('component_field', models.CharField(blank=True, max_length=255)), ('ip', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='appraisal_job_entries', to='ip.InformationPackage')), ('job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='entries', to='maintenance.AppraisalJob')), ], ), migrations.AlterModelOptions( name='appraisaljob', options={'get_latest_by': 'start_date'}, ), ]
gpl-3.0
nolanelena/MyProjectSite-
node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py
1355
44604
# 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. """cmake output module This module is under development and should be considered experimental. This module produces cmake (2.8.8+) input as its output. One CMakeLists.txt is created for each configuration. This module's original purpose was to support editing in IDEs like KDevelop which use CMake for project management. It is also possible to use CMake to generate projects for other IDEs such as eclipse cdt and code::blocks. QtCreator will convert the CMakeLists.txt to a code::blocks cbp for the editor to read, but build using CMake. As a result QtCreator editor is unaware of compiler defines. The generated CMakeLists.txt can also be used to build on Linux. There is currently no support for building on platforms other than Linux. The generated CMakeLists.txt should properly compile all projects. However, there is a mismatch between gyp and cmake with regard to linking. All attempts are made to work around this, but CMake sometimes sees -Wl,--start-group as a library and incorrectly repeats it. As a result the output of this generator should not be relied on for building. When using with kdevelop, use version 4.4+. Previous versions of kdevelop will not be able to find the header file directories described in the generated CMakeLists.txt file. """ import multiprocessing import os import signal import string import subprocess import gyp.common generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'SHARED_LIB_PREFIX': 'lib', 'SHARED_LIB_SUFFIX': '.so', 'SHARED_LIB_DIR': '${builddir}/lib.${TOOLSET}', 'LIB_DIR': '${obj}.${TOOLSET}', 'INTERMEDIATE_DIR': '${obj}.${TOOLSET}/${TARGET}/geni', 'SHARED_INTERMEDIATE_DIR': '${obj}/gen', 'PRODUCT_DIR': '${builddir}', 'RULE_INPUT_PATH': '${RULE_INPUT_PATH}', 'RULE_INPUT_DIRNAME': '${RULE_INPUT_DIRNAME}', 'RULE_INPUT_NAME': '${RULE_INPUT_NAME}', 'RULE_INPUT_ROOT': '${RULE_INPUT_ROOT}', 'RULE_INPUT_EXT': '${RULE_INPUT_EXT}', 'CONFIGURATION_NAME': '${configuration}', } FULL_PATH_VARS = ('${CMAKE_CURRENT_LIST_DIR}', '${builddir}', '${obj}') generator_supports_multiple_toolsets = True generator_wants_static_library_dependencies_adjusted = True COMPILABLE_EXTENSIONS = { '.c': 'cc', '.cc': 'cxx', '.cpp': 'cxx', '.cxx': 'cxx', '.s': 's', # cc '.S': 's', # cc } def RemovePrefix(a, prefix): """Returns 'a' without 'prefix' if it starts with 'prefix'.""" return a[len(prefix):] if a.startswith(prefix) else a def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" default_variables.setdefault('OS', gyp.common.GetFlavor(params)) def Compilable(filename): """Return true if the file is compilable (should be in OBJS).""" return any(filename.endswith(e) for e in COMPILABLE_EXTENSIONS) def Linkable(filename): """Return true if the file is linkable (should be on the link line).""" return filename.endswith('.o') def NormjoinPathForceCMakeSource(base_path, rel_path): """Resolves rel_path against base_path and returns the result. If rel_path is an absolute path it is returned unchanged. Otherwise it is resolved against base_path and normalized. If the result is a relative path, it is forced to be relative to the CMakeLists.txt. """ if os.path.isabs(rel_path): return rel_path if any([rel_path.startswith(var) for var in FULL_PATH_VARS]): return rel_path # TODO: do we need to check base_path for absolute variables as well? return os.path.join('${CMAKE_CURRENT_LIST_DIR}', os.path.normpath(os.path.join(base_path, rel_path))) def NormjoinPath(base_path, rel_path): """Resolves rel_path against base_path and returns the result. TODO: what is this really used for? If rel_path begins with '$' it is returned unchanged. Otherwise it is resolved against base_path if relative, then normalized. """ if rel_path.startswith('$') and not rel_path.startswith('${configuration}'): return rel_path return os.path.normpath(os.path.join(base_path, rel_path)) def CMakeStringEscape(a): """Escapes the string 'a' for use inside a CMake string. This means escaping '\' otherwise it may be seen as modifying the next character '"' otherwise it will end the string ';' otherwise the string becomes a list The following do not need to be escaped '#' when the lexer is in string state, this does not start a comment The following are yet unknown '$' generator variables (like ${obj}) must not be escaped, but text $ should be escaped what is wanted is to know which $ come from generator variables """ return a.replace('\\', '\\\\').replace(';', '\\;').replace('"', '\\"') def SetFileProperty(output, source_name, property_name, values, sep): """Given a set of source file, sets the given property on them.""" output.write('set_source_files_properties(') output.write(source_name) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n') def SetFilesProperty(output, variable, property_name, values, sep): """Given a set of source files, sets the given property on them.""" output.write('set_source_files_properties(') WriteVariable(output, variable) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n') def SetTargetProperty(output, target_name, property_name, values, sep=''): """Given a target, sets the given property.""" output.write('set_target_properties(') output.write(target_name) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n') def SetVariable(output, variable_name, value): """Sets a CMake variable.""" output.write('set(') output.write(variable_name) output.write(' "') output.write(CMakeStringEscape(value)) output.write('")\n') def SetVariableList(output, variable_name, values): """Sets a CMake variable to a list.""" if not values: return SetVariable(output, variable_name, "") if len(values) == 1: return SetVariable(output, variable_name, values[0]) output.write('list(APPEND ') output.write(variable_name) output.write('\n "') output.write('"\n "'.join([CMakeStringEscape(value) for value in values])) output.write('")\n') def UnsetVariable(output, variable_name): """Unsets a CMake variable.""" output.write('unset(') output.write(variable_name) output.write(')\n') def WriteVariable(output, variable_name, prepend=None): if prepend: output.write(prepend) output.write('${') output.write(variable_name) output.write('}') class CMakeTargetType(object): def __init__(self, command, modifier, property_modifier): self.command = command self.modifier = modifier self.property_modifier = property_modifier cmake_target_type_from_gyp_target_type = { 'executable': CMakeTargetType('add_executable', None, 'RUNTIME'), 'static_library': CMakeTargetType('add_library', 'STATIC', 'ARCHIVE'), 'shared_library': CMakeTargetType('add_library', 'SHARED', 'LIBRARY'), 'loadable_module': CMakeTargetType('add_library', 'MODULE', 'LIBRARY'), 'none': CMakeTargetType('add_custom_target', 'SOURCES', None), } def StringToCMakeTargetName(a): """Converts the given string 'a' to a valid CMake target name. All invalid characters are replaced by '_'. Invalid for cmake: ' ', '/', '(', ')', '"' Invalid for make: ':' Invalid for unknown reasons but cause failures: '.' """ return a.translate(string.maketrans(' /():."', '_______')) def WriteActions(target_name, actions, extra_sources, extra_deps, path_to_gyp, output): """Write CMake for the 'actions' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(<cmake_src>, <src>)] to append with generated source files. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ for action in actions: action_name = StringToCMakeTargetName(action['action_name']) action_target_name = '%s__%s' % (target_name, action_name) inputs = action['inputs'] inputs_name = action_target_name + '__input' SetVariableList(output, inputs_name, [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs]) outputs = action['outputs'] cmake_outputs = [NormjoinPathForceCMakeSource(path_to_gyp, out) for out in outputs] outputs_name = action_target_name + '__output' SetVariableList(output, outputs_name, cmake_outputs) # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir) if int(action.get('process_outputs_as_sources', False)): extra_sources.extend(zip(cmake_outputs, outputs)) # add_custom_command output.write('add_custom_command(OUTPUT ') WriteVariable(output, outputs_name) output.write('\n') if len(dirs) > 0: for directory in dirs: output.write(' COMMAND ${CMAKE_COMMAND} -E make_directory ') output.write(directory) output.write('\n') output.write(' COMMAND ') output.write(gyp.common.EncodePOSIXShellList(action['action'])) output.write('\n') output.write(' DEPENDS ') WriteVariable(output, inputs_name) output.write('\n') output.write(' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/') output.write(path_to_gyp) output.write('\n') output.write(' COMMENT ') if 'message' in action: output.write(action['message']) else: output.write(action_target_name) output.write('\n') output.write(' VERBATIM\n') output.write(')\n') # add_custom_target output.write('add_custom_target(') output.write(action_target_name) output.write('\n DEPENDS ') WriteVariable(output, outputs_name) output.write('\n SOURCES ') WriteVariable(output, inputs_name) output.write('\n)\n') extra_deps.append(action_target_name) def NormjoinRulePathForceCMakeSource(base_path, rel_path, rule_source): if rel_path.startswith(("${RULE_INPUT_PATH}","${RULE_INPUT_DIRNAME}")): if any([rule_source.startswith(var) for var in FULL_PATH_VARS]): return rel_path return NormjoinPathForceCMakeSource(base_path, rel_path) def WriteRules(target_name, rules, extra_sources, extra_deps, path_to_gyp, output): """Write CMake for the 'rules' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(<cmake_src>, <src>)] to append with generated source files. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ for rule in rules: rule_name = StringToCMakeTargetName(target_name + '__' + rule['rule_name']) inputs = rule.get('inputs', []) inputs_name = rule_name + '__input' SetVariableList(output, inputs_name, [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs]) outputs = rule['outputs'] var_outputs = [] for count, rule_source in enumerate(rule.get('rule_sources', [])): action_name = rule_name + '_' + str(count) rule_source_dirname, rule_source_basename = os.path.split(rule_source) rule_source_root, rule_source_ext = os.path.splitext(rule_source_basename) SetVariable(output, 'RULE_INPUT_PATH', rule_source) SetVariable(output, 'RULE_INPUT_DIRNAME', rule_source_dirname) SetVariable(output, 'RULE_INPUT_NAME', rule_source_basename) SetVariable(output, 'RULE_INPUT_ROOT', rule_source_root) SetVariable(output, 'RULE_INPUT_EXT', rule_source_ext) # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir) # Create variables for the output, as 'local' variable will be unset. these_outputs = [] for output_index, out in enumerate(outputs): output_name = action_name + '_' + str(output_index) SetVariable(output, output_name, NormjoinRulePathForceCMakeSource(path_to_gyp, out, rule_source)) if int(rule.get('process_outputs_as_sources', False)): extra_sources.append(('${' + output_name + '}', out)) these_outputs.append('${' + output_name + '}') var_outputs.append('${' + output_name + '}') # add_custom_command output.write('add_custom_command(OUTPUT\n') for out in these_outputs: output.write(' ') output.write(out) output.write('\n') for directory in dirs: output.write(' COMMAND ${CMAKE_COMMAND} -E make_directory ') output.write(directory) output.write('\n') output.write(' COMMAND ') output.write(gyp.common.EncodePOSIXShellList(rule['action'])) output.write('\n') output.write(' DEPENDS ') WriteVariable(output, inputs_name) output.write(' ') output.write(NormjoinPath(path_to_gyp, rule_source)) output.write('\n') # CMAKE_CURRENT_LIST_DIR is where the CMakeLists.txt lives. # The cwd is the current build directory. output.write(' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/') output.write(path_to_gyp) output.write('\n') output.write(' COMMENT ') if 'message' in rule: output.write(rule['message']) else: output.write(action_name) output.write('\n') output.write(' VERBATIM\n') output.write(')\n') UnsetVariable(output, 'RULE_INPUT_PATH') UnsetVariable(output, 'RULE_INPUT_DIRNAME') UnsetVariable(output, 'RULE_INPUT_NAME') UnsetVariable(output, 'RULE_INPUT_ROOT') UnsetVariable(output, 'RULE_INPUT_EXT') # add_custom_target output.write('add_custom_target(') output.write(rule_name) output.write(' DEPENDS\n') for out in var_outputs: output.write(' ') output.write(out) output.write('\n') output.write('SOURCES ') WriteVariable(output, inputs_name) output.write('\n') for rule_source in rule.get('rule_sources', []): output.write(' ') output.write(NormjoinPath(path_to_gyp, rule_source)) output.write('\n') output.write(')\n') extra_deps.append(rule_name) def WriteCopies(target_name, copies, extra_deps, path_to_gyp, output): """Write CMake for the 'copies' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ copy_name = target_name + '__copies' # CMake gets upset with custom targets with OUTPUT which specify no output. have_copies = any(copy['files'] for copy in copies) if not have_copies: output.write('add_custom_target(') output.write(copy_name) output.write(')\n') extra_deps.append(copy_name) return class Copy(object): def __init__(self, ext, command): self.cmake_inputs = [] self.cmake_outputs = [] self.gyp_inputs = [] self.gyp_outputs = [] self.ext = ext self.inputs_name = None self.outputs_name = None self.command = command file_copy = Copy('', 'copy') dir_copy = Copy('_dirs', 'copy_directory') for copy in copies: files = copy['files'] destination = copy['destination'] for src in files: path = os.path.normpath(src) basename = os.path.split(path)[1] dst = os.path.join(destination, basename) copy = file_copy if os.path.basename(src) else dir_copy copy.cmake_inputs.append(NormjoinPathForceCMakeSource(path_to_gyp, src)) copy.cmake_outputs.append(NormjoinPathForceCMakeSource(path_to_gyp, dst)) copy.gyp_inputs.append(src) copy.gyp_outputs.append(dst) for copy in (file_copy, dir_copy): if copy.cmake_inputs: copy.inputs_name = copy_name + '__input' + copy.ext SetVariableList(output, copy.inputs_name, copy.cmake_inputs) copy.outputs_name = copy_name + '__output' + copy.ext SetVariableList(output, copy.outputs_name, copy.cmake_outputs) # add_custom_command output.write('add_custom_command(\n') output.write('OUTPUT') for copy in (file_copy, dir_copy): if copy.outputs_name: WriteVariable(output, copy.outputs_name, ' ') output.write('\n') for copy in (file_copy, dir_copy): for src, dst in zip(copy.gyp_inputs, copy.gyp_outputs): # 'cmake -E copy src dst' will create the 'dst' directory if needed. output.write('COMMAND ${CMAKE_COMMAND} -E %s ' % copy.command) output.write(src) output.write(' ') output.write(dst) output.write("\n") output.write('DEPENDS') for copy in (file_copy, dir_copy): if copy.inputs_name: WriteVariable(output, copy.inputs_name, ' ') output.write('\n') output.write('WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/') output.write(path_to_gyp) output.write('\n') output.write('COMMENT Copying for ') output.write(target_name) output.write('\n') output.write('VERBATIM\n') output.write(')\n') # add_custom_target output.write('add_custom_target(') output.write(copy_name) output.write('\n DEPENDS') for copy in (file_copy, dir_copy): if copy.outputs_name: WriteVariable(output, copy.outputs_name, ' ') output.write('\n SOURCES') if file_copy.inputs_name: WriteVariable(output, file_copy.inputs_name, ' ') output.write('\n)\n') extra_deps.append(copy_name) def CreateCMakeTargetBaseName(qualified_target): """This is the name we would like the target to have.""" _, gyp_target_name, gyp_target_toolset = ( gyp.common.ParseQualifiedTarget(qualified_target)) cmake_target_base_name = gyp_target_name if gyp_target_toolset and gyp_target_toolset != 'target': cmake_target_base_name += '_' + gyp_target_toolset return StringToCMakeTargetName(cmake_target_base_name) def CreateCMakeTargetFullName(qualified_target): """An unambiguous name for the target.""" gyp_file, gyp_target_name, gyp_target_toolset = ( gyp.common.ParseQualifiedTarget(qualified_target)) cmake_target_full_name = gyp_file + ':' + gyp_target_name if gyp_target_toolset and gyp_target_toolset != 'target': cmake_target_full_name += '_' + gyp_target_toolset return StringToCMakeTargetName(cmake_target_full_name) class CMakeNamer(object): """Converts Gyp target names into CMake target names. CMake requires that target names be globally unique. One way to ensure this is to fully qualify the names of the targets. Unfortunatly, this ends up with all targets looking like "chrome_chrome_gyp_chrome" instead of just "chrome". If this generator were only interested in building, it would be possible to fully qualify all target names, then create unqualified target names which depend on all qualified targets which should have had that name. This is more or less what the 'make' generator does with aliases. However, one goal of this generator is to create CMake files for use with IDEs, and fully qualified names are not as user friendly. Since target name collision is rare, we do the above only when required. Toolset variants are always qualified from the base, as this is required for building. However, it also makes sense for an IDE, as it is possible for defines to be different. """ def __init__(self, target_list): self.cmake_target_base_names_conficting = set() cmake_target_base_names_seen = set() for qualified_target in target_list: cmake_target_base_name = CreateCMakeTargetBaseName(qualified_target) if cmake_target_base_name not in cmake_target_base_names_seen: cmake_target_base_names_seen.add(cmake_target_base_name) else: self.cmake_target_base_names_conficting.add(cmake_target_base_name) def CreateCMakeTargetName(self, qualified_target): base_name = CreateCMakeTargetBaseName(qualified_target) if base_name in self.cmake_target_base_names_conficting: return CreateCMakeTargetFullName(qualified_target) return base_name def WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use, options, generator_flags, all_qualified_targets, output): # The make generator does this always. # TODO: It would be nice to be able to tell CMake all dependencies. circular_libs = generator_flags.get('circular', True) if not generator_flags.get('standalone', False): output.write('\n#') output.write(qualified_target) output.write('\n') gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target) rel_gyp_file = gyp.common.RelativePath(gyp_file, options.toplevel_dir) rel_gyp_dir = os.path.dirname(rel_gyp_file) # Relative path from build dir to top dir. build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) # Relative path from build dir to gyp dir. build_to_gyp = os.path.join(build_to_top, rel_gyp_dir) path_from_cmakelists_to_gyp = build_to_gyp spec = target_dicts.get(qualified_target, {}) config = spec.get('configurations', {}).get(config_to_use, {}) target_name = spec.get('target_name', '<missing target name>') target_type = spec.get('type', '<missing target type>') target_toolset = spec.get('toolset') cmake_target_type = cmake_target_type_from_gyp_target_type.get(target_type) if cmake_target_type is None: print ('Target %s has unknown target type %s, skipping.' % ( target_name, target_type ) ) return SetVariable(output, 'TARGET', target_name) SetVariable(output, 'TOOLSET', target_toolset) cmake_target_name = namer.CreateCMakeTargetName(qualified_target) extra_sources = [] extra_deps = [] # Actions must come first, since they can generate more OBJs for use below. if 'actions' in spec: WriteActions(cmake_target_name, spec['actions'], extra_sources, extra_deps, path_from_cmakelists_to_gyp, output) # Rules must be early like actions. if 'rules' in spec: WriteRules(cmake_target_name, spec['rules'], extra_sources, extra_deps, path_from_cmakelists_to_gyp, output) # Copies if 'copies' in spec: WriteCopies(cmake_target_name, spec['copies'], extra_deps, path_from_cmakelists_to_gyp, output) # Target and sources srcs = spec.get('sources', []) # Gyp separates the sheep from the goats based on file extensions. # A full separation is done here because of flag handing (see below). s_sources = [] c_sources = [] cxx_sources = [] linkable_sources = [] other_sources = [] for src in srcs: _, ext = os.path.splitext(src) src_type = COMPILABLE_EXTENSIONS.get(ext, None) src_norm_path = NormjoinPath(path_from_cmakelists_to_gyp, src); if src_type == 's': s_sources.append(src_norm_path) elif src_type == 'cc': c_sources.append(src_norm_path) elif src_type == 'cxx': cxx_sources.append(src_norm_path) elif Linkable(ext): linkable_sources.append(src_norm_path) else: other_sources.append(src_norm_path) for extra_source in extra_sources: src, real_source = extra_source _, ext = os.path.splitext(real_source) src_type = COMPILABLE_EXTENSIONS.get(ext, None) if src_type == 's': s_sources.append(src) elif src_type == 'cc': c_sources.append(src) elif src_type == 'cxx': cxx_sources.append(src) elif Linkable(ext): linkable_sources.append(src) else: other_sources.append(src) s_sources_name = None if s_sources: s_sources_name = cmake_target_name + '__asm_srcs' SetVariableList(output, s_sources_name, s_sources) c_sources_name = None if c_sources: c_sources_name = cmake_target_name + '__c_srcs' SetVariableList(output, c_sources_name, c_sources) cxx_sources_name = None if cxx_sources: cxx_sources_name = cmake_target_name + '__cxx_srcs' SetVariableList(output, cxx_sources_name, cxx_sources) linkable_sources_name = None if linkable_sources: linkable_sources_name = cmake_target_name + '__linkable_srcs' SetVariableList(output, linkable_sources_name, linkable_sources) other_sources_name = None if other_sources: other_sources_name = cmake_target_name + '__other_srcs' SetVariableList(output, other_sources_name, other_sources) # CMake gets upset when executable targets provide no sources. # http://www.cmake.org/pipermail/cmake/2010-July/038461.html dummy_sources_name = None has_sources = (s_sources_name or c_sources_name or cxx_sources_name or linkable_sources_name or other_sources_name) if target_type == 'executable' and not has_sources: dummy_sources_name = cmake_target_name + '__dummy_srcs' SetVariable(output, dummy_sources_name, "${obj}.${TOOLSET}/${TARGET}/genc/dummy.c") output.write('if(NOT EXISTS "') WriteVariable(output, dummy_sources_name) output.write('")\n') output.write(' file(WRITE "') WriteVariable(output, dummy_sources_name) output.write('" "")\n') output.write("endif()\n") # CMake is opposed to setting linker directories and considers the practice # of setting linker directories dangerous. Instead, it favors the use of # find_library and passing absolute paths to target_link_libraries. # However, CMake does provide the command link_directories, which adds # link directories to targets defined after it is called. # As a result, link_directories must come before the target definition. # CMake unfortunately has no means of removing entries from LINK_DIRECTORIES. library_dirs = config.get('library_dirs') if library_dirs is not None: output.write('link_directories(') for library_dir in library_dirs: output.write(' ') output.write(NormjoinPath(path_from_cmakelists_to_gyp, library_dir)) output.write('\n') output.write(')\n') output.write(cmake_target_type.command) output.write('(') output.write(cmake_target_name) if cmake_target_type.modifier is not None: output.write(' ') output.write(cmake_target_type.modifier) if s_sources_name: WriteVariable(output, s_sources_name, ' ') if c_sources_name: WriteVariable(output, c_sources_name, ' ') if cxx_sources_name: WriteVariable(output, cxx_sources_name, ' ') if linkable_sources_name: WriteVariable(output, linkable_sources_name, ' ') if other_sources_name: WriteVariable(output, other_sources_name, ' ') if dummy_sources_name: WriteVariable(output, dummy_sources_name, ' ') output.write(')\n') # Let CMake know if the 'all' target should depend on this target. exclude_from_all = ('TRUE' if qualified_target not in all_qualified_targets else 'FALSE') SetTargetProperty(output, cmake_target_name, 'EXCLUDE_FROM_ALL', exclude_from_all) for extra_target_name in extra_deps: SetTargetProperty(output, extra_target_name, 'EXCLUDE_FROM_ALL', exclude_from_all) # Output name and location. if target_type != 'none': # Link as 'C' if there are no other files if not c_sources and not cxx_sources: SetTargetProperty(output, cmake_target_name, 'LINKER_LANGUAGE', ['C']) # Mark uncompiled sources as uncompiled. if other_sources_name: output.write('set_source_files_properties(') WriteVariable(output, other_sources_name, '') output.write(' PROPERTIES HEADER_FILE_ONLY "TRUE")\n') # Mark object sources as linkable. if linkable_sources_name: output.write('set_source_files_properties(') WriteVariable(output, other_sources_name, '') output.write(' PROPERTIES EXTERNAL_OBJECT "TRUE")\n') # Output directory target_output_directory = spec.get('product_dir') if target_output_directory is None: if target_type in ('executable', 'loadable_module'): target_output_directory = generator_default_variables['PRODUCT_DIR'] elif target_type == 'shared_library': target_output_directory = '${builddir}/lib.${TOOLSET}' elif spec.get('standalone_static_library', False): target_output_directory = generator_default_variables['PRODUCT_DIR'] else: base_path = gyp.common.RelativePath(os.path.dirname(gyp_file), options.toplevel_dir) target_output_directory = '${obj}.${TOOLSET}' target_output_directory = ( os.path.join(target_output_directory, base_path)) cmake_target_output_directory = NormjoinPathForceCMakeSource( path_from_cmakelists_to_gyp, target_output_directory) SetTargetProperty(output, cmake_target_name, cmake_target_type.property_modifier + '_OUTPUT_DIRECTORY', cmake_target_output_directory) # Output name default_product_prefix = '' default_product_name = target_name default_product_ext = '' if target_type == 'static_library': static_library_prefix = generator_default_variables['STATIC_LIB_PREFIX'] default_product_name = RemovePrefix(default_product_name, static_library_prefix) default_product_prefix = static_library_prefix default_product_ext = generator_default_variables['STATIC_LIB_SUFFIX'] elif target_type in ('loadable_module', 'shared_library'): shared_library_prefix = generator_default_variables['SHARED_LIB_PREFIX'] default_product_name = RemovePrefix(default_product_name, shared_library_prefix) default_product_prefix = shared_library_prefix default_product_ext = generator_default_variables['SHARED_LIB_SUFFIX'] elif target_type != 'executable': print ('ERROR: What output file should be generated?', 'type', target_type, 'target', target_name) product_prefix = spec.get('product_prefix', default_product_prefix) product_name = spec.get('product_name', default_product_name) product_ext = spec.get('product_extension') if product_ext: product_ext = '.' + product_ext else: product_ext = default_product_ext SetTargetProperty(output, cmake_target_name, 'PREFIX', product_prefix) SetTargetProperty(output, cmake_target_name, cmake_target_type.property_modifier + '_OUTPUT_NAME', product_name) SetTargetProperty(output, cmake_target_name, 'SUFFIX', product_ext) # Make the output of this target referenceable as a source. cmake_target_output_basename = product_prefix + product_name + product_ext cmake_target_output = os.path.join(cmake_target_output_directory, cmake_target_output_basename) SetFileProperty(output, cmake_target_output, 'GENERATED', ['TRUE'], '') # Includes includes = config.get('include_dirs') if includes: # This (target include directories) is what requires CMake 2.8.8 includes_name = cmake_target_name + '__include_dirs' SetVariableList(output, includes_name, [NormjoinPathForceCMakeSource(path_from_cmakelists_to_gyp, include) for include in includes]) output.write('set_property(TARGET ') output.write(cmake_target_name) output.write(' APPEND PROPERTY INCLUDE_DIRECTORIES ') WriteVariable(output, includes_name, '') output.write(')\n') # Defines defines = config.get('defines') if defines is not None: SetTargetProperty(output, cmake_target_name, 'COMPILE_DEFINITIONS', defines, ';') # Compile Flags - http://www.cmake.org/Bug/view.php?id=6493 # CMake currently does not have target C and CXX flags. # So, instead of doing... # cflags_c = config.get('cflags_c') # if cflags_c is not None: # SetTargetProperty(output, cmake_target_name, # 'C_COMPILE_FLAGS', cflags_c, ' ') # cflags_cc = config.get('cflags_cc') # if cflags_cc is not None: # SetTargetProperty(output, cmake_target_name, # 'CXX_COMPILE_FLAGS', cflags_cc, ' ') # Instead we must... cflags = config.get('cflags', []) cflags_c = config.get('cflags_c', []) cflags_cxx = config.get('cflags_cc', []) if (not cflags_c or not c_sources) and (not cflags_cxx or not cxx_sources): SetTargetProperty(output, cmake_target_name, 'COMPILE_FLAGS', cflags, ' ') elif c_sources and not (s_sources or cxx_sources): flags = [] flags.extend(cflags) flags.extend(cflags_c) SetTargetProperty(output, cmake_target_name, 'COMPILE_FLAGS', flags, ' ') elif cxx_sources and not (s_sources or c_sources): flags = [] flags.extend(cflags) flags.extend(cflags_cxx) SetTargetProperty(output, cmake_target_name, 'COMPILE_FLAGS', flags, ' ') else: # TODO: This is broken, one cannot generally set properties on files, # as other targets may require different properties on the same files. if s_sources and cflags: SetFilesProperty(output, s_sources_name, 'COMPILE_FLAGS', cflags, ' ') if c_sources and (cflags or cflags_c): flags = [] flags.extend(cflags) flags.extend(cflags_c) SetFilesProperty(output, c_sources_name, 'COMPILE_FLAGS', flags, ' ') if cxx_sources and (cflags or cflags_cxx): flags = [] flags.extend(cflags) flags.extend(cflags_cxx) SetFilesProperty(output, cxx_sources_name, 'COMPILE_FLAGS', flags, ' ') # Linker flags ldflags = config.get('ldflags') if ldflags is not None: SetTargetProperty(output, cmake_target_name, 'LINK_FLAGS', ldflags, ' ') # Note on Dependencies and Libraries: # CMake wants to handle link order, resolving the link line up front. # Gyp does not retain or enforce specifying enough information to do so. # So do as other gyp generators and use --start-group and --end-group. # Give CMake as little information as possible so that it doesn't mess it up. # Dependencies rawDeps = spec.get('dependencies', []) static_deps = [] shared_deps = [] other_deps = [] for rawDep in rawDeps: dep_cmake_name = namer.CreateCMakeTargetName(rawDep) dep_spec = target_dicts.get(rawDep, {}) dep_target_type = dep_spec.get('type', None) if dep_target_type == 'static_library': static_deps.append(dep_cmake_name) elif dep_target_type == 'shared_library': shared_deps.append(dep_cmake_name) else: other_deps.append(dep_cmake_name) # ensure all external dependencies are complete before internal dependencies # extra_deps currently only depend on their own deps, so otherwise run early if static_deps or shared_deps or other_deps: for extra_dep in extra_deps: output.write('add_dependencies(') output.write(extra_dep) output.write('\n') for deps in (static_deps, shared_deps, other_deps): for dep in gyp.common.uniquer(deps): output.write(' ') output.write(dep) output.write('\n') output.write(')\n') linkable = target_type in ('executable', 'loadable_module', 'shared_library') other_deps.extend(extra_deps) if other_deps or (not linkable and (static_deps or shared_deps)): output.write('add_dependencies(') output.write(cmake_target_name) output.write('\n') for dep in gyp.common.uniquer(other_deps): output.write(' ') output.write(dep) output.write('\n') if not linkable: for deps in (static_deps, shared_deps): for lib_dep in gyp.common.uniquer(deps): output.write(' ') output.write(lib_dep) output.write('\n') output.write(')\n') # Libraries if linkable: external_libs = [lib for lib in spec.get('libraries', []) if len(lib) > 0] if external_libs or static_deps or shared_deps: output.write('target_link_libraries(') output.write(cmake_target_name) output.write('\n') if static_deps: write_group = circular_libs and len(static_deps) > 1 if write_group: output.write('-Wl,--start-group\n') for dep in gyp.common.uniquer(static_deps): output.write(' ') output.write(dep) output.write('\n') if write_group: output.write('-Wl,--end-group\n') if shared_deps: for dep in gyp.common.uniquer(shared_deps): output.write(' ') output.write(dep) output.write('\n') if external_libs: for lib in gyp.common.uniquer(external_libs): output.write(' ') output.write(lib) output.write('\n') output.write(')\n') UnsetVariable(output, 'TOOLSET') UnsetVariable(output, 'TARGET') def GenerateOutputForConfig(target_list, target_dicts, data, params, config_to_use): options = params['options'] generator_flags = params['generator_flags'] # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to cmake easier, cmake doesn't put anything here. # Each Gyp configuration creates a different CMakeLists.txt file # to avoid incompatibilities between Gyp and CMake configurations. generator_dir = os.path.relpath(options.generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = generator_flags.get('output_dir', 'out') # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath(os.path.join(generator_dir, output_dir, config_to_use)) toplevel_build = os.path.join(options.toplevel_dir, build_dir) output_file = os.path.join(toplevel_build, 'CMakeLists.txt') gyp.common.EnsureDirExists(output_file) output = open(output_file, 'w') output.write('cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n') output.write('cmake_policy(VERSION 2.8.8)\n') gyp_file, project_target, _ = gyp.common.ParseQualifiedTarget(target_list[-1]) output.write('project(') output.write(project_target) output.write(')\n') SetVariable(output, 'configuration', config_to_use) ar = None cc = None cxx = None make_global_settings = data[gyp_file].get('make_global_settings', []) build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) for key, value in make_global_settings: if key == 'AR': ar = os.path.join(build_to_top, value) if key == 'CC': cc = os.path.join(build_to_top, value) if key == 'CXX': cxx = os.path.join(build_to_top, value) ar = gyp.common.GetEnvironFallback(['AR_target', 'AR'], ar) cc = gyp.common.GetEnvironFallback(['CC_target', 'CC'], cc) cxx = gyp.common.GetEnvironFallback(['CXX_target', 'CXX'], cxx) if ar: SetVariable(output, 'CMAKE_AR', ar) if cc: SetVariable(output, 'CMAKE_C_COMPILER', cc) if cxx: SetVariable(output, 'CMAKE_CXX_COMPILER', cxx) # The following appears to be as-yet undocumented. # http://public.kitware.com/Bug/view.php?id=8392 output.write('enable_language(ASM)\n') # ASM-ATT does not support .S files. # output.write('enable_language(ASM-ATT)\n') if cc: SetVariable(output, 'CMAKE_ASM_COMPILER', cc) SetVariable(output, 'builddir', '${CMAKE_CURRENT_BINARY_DIR}') SetVariable(output, 'obj', '${builddir}/obj') output.write('\n') # TODO: Undocumented/unsupported (the CMake Java generator depends on it). # CMake by default names the object resulting from foo.c to be foo.c.o. # Gyp traditionally names the object resulting from foo.c foo.o. # This should be irrelevant, but some targets extract .o files from .a # and depend on the name of the extracted .o files. output.write('set(CMAKE_C_OUTPUT_EXTENSION_REPLACE 1)\n') output.write('set(CMAKE_CXX_OUTPUT_EXTENSION_REPLACE 1)\n') output.write('\n') # Force ninja to use rsp files. Otherwise link and ar lines can get too long, # resulting in 'Argument list too long' errors. output.write('set(CMAKE_NINJA_FORCE_RESPONSE_FILE 1)\n') output.write('\n') namer = CMakeNamer(target_list) # The list of targets upon which the 'all' target should depend. # CMake has it's own implicit 'all' target, one is not created explicitly. all_qualified_targets = set() for build_file in params['build_files']: for qualified_target in gyp.common.AllTargets(target_list, target_dicts, os.path.normpath(build_file)): all_qualified_targets.add(qualified_target) for qualified_target in target_list: WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use, options, generator_flags, all_qualified_targets, output) output.close() def PerformBuild(data, configurations, params): options = params['options'] generator_flags = params['generator_flags'] # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to cmake easier, cmake doesn't put anything here. generator_dir = os.path.relpath(options.generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = generator_flags.get('output_dir', 'out') for config_name in configurations: # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath(os.path.join(generator_dir, output_dir, config_name)) arguments = ['cmake', '-G', 'Ninja'] print 'Generating [%s]: %s' % (config_name, arguments) subprocess.check_call(arguments, cwd=build_dir) arguments = ['ninja', '-C', build_dir] print 'Building [%s]: %s' % (config_name, arguments) subprocess.check_call(arguments) def CallGenerateOutputForConfig(arglist): # Ignore the interrupt signal so that the parent process catches it and # kills all multiprocessing children. signal.signal(signal.SIGINT, signal.SIG_IGN) target_list, target_dicts, data, params, config_name = arglist GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) def GenerateOutput(target_list, target_dicts, data, params): user_config = params.get('generator_flags', {}).get('config', None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['configurations'].keys() if params['parallel']: try: pool = multiprocessing.Pool(len(config_names)) arglists = [] for config_name in config_names: arglists.append((target_list, target_dicts, data, params, config_name)) pool.map(CallGenerateOutputForConfig, arglists) except KeyboardInterrupt, e: pool.terminate() raise e else: for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
mit
TeamEOS/external_chromium_org
tools/linux/PRESUBMIT.py
79
1392
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for linux. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit API built into gcl. """ def CommonChecks(input_api, output_api): import sys def join(*args): return input_api.os_path.join(input_api.PresubmitLocalPath(), *args) output = [] sys_path_backup = sys.path try: sys.path = [ join('..', 'linux'), ] + sys.path output.extend(input_api.canned_checks.RunPylint(input_api, output_api)) finally: sys.path = sys_path_backup output.extend( input_api.canned_checks.RunUnitTestsInDirectory( input_api, output_api, input_api.os_path.join(input_api.PresubmitLocalPath(), 'tests'), whitelist=[r'.+_tests\.py$'])) if input_api.is_committing: output.extend(input_api.canned_checks.PanProjectChecks(input_api, output_api, owners_check=False)) return output def CheckChangeOnUpload(input_api, output_api): return CommonChecks(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return CommonChecks(input_api, output_api)
bsd-3-clause
smarr/PySOM
src/rtruffle/abstract_node.py
2
2126
from rlib.unroll import unrolling_iterable class AbstractNode(object): pass def _get_all_child_fields(cls): field_names = [] while cls is not AbstractNode: if hasattr(cls, "_child_nodes_"): field_names += cls._child_nodes_ # pylint: disable=protected-access cls = cls.__base__ return field_names def _generate_replace_method(cls): child_fields = unrolling_iterable(_get_all_child_fields(cls)) def _replace_child_with(parent_node, old_child, new_child): was_replaced = False # pylint: disable=unused-variable for child_slot in child_fields: if child_slot.endswith("[*]"): slot_name = child_slot[:-3] nodes = getattr(parent_node, slot_name) if nodes and old_child in nodes: # update old list, because iterators might have a copy of it for i, n in enumerate(nodes): if n is old_child: nodes[i] = new_child setattr( parent_node, slot_name, nodes[:] ) # TODO: figure out whether we need the copy of the list here was_replaced = True else: current = getattr(parent_node, child_slot) if current is old_child: setattr(parent_node, child_slot, new_child) was_replaced = True # TODO: method recursion is a problem causing specialization more than # once of a node if the containing method is already on the stack # if not was_replaced: # raise ValueError("%s was not a direct child node of %s" % ( # old_child, parent_node)) return new_child cls.replace_child_with = _replace_child_with class NodeInitializeMetaClass(type): def __init__(cls, name, bases, dic): type.__init__(cls, name, bases, dic) cls._initialize_node_class() # pylint: disable=no-value-for-parameter def _initialize_node_class(cls): _generate_replace_method(cls)
mit
hvekriya/mojwmt
node_modules/grunt-sass/node_modules/node-sass/node_modules/node-gyp/gyp/tools/pretty_gyp.py
2618
4756
#!/usr/bin/env python # Copyright (c) 2012 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. """Pretty-prints the contents of a GYP file.""" import sys import re # Regex to remove comments when we're counting braces. COMMENT_RE = re.compile(r'\s*#.*') # Regex to remove quoted strings when we're counting braces. # It takes into account quoted quotes, and makes sure that the quotes match. # NOTE: It does not handle quotes that span more than one line, or # cases where an escaped quote is preceeded by an escaped backslash. QUOTE_RE_STR = r'(?P<q>[\'"])(.*?)(?<![^\\][\\])(?P=q)' QUOTE_RE = re.compile(QUOTE_RE_STR) def comment_replace(matchobj): return matchobj.group(1) + matchobj.group(2) + '#' * len(matchobj.group(3)) def mask_comments(input): """Mask the quoted strings so we skip braces inside quoted strings.""" search_re = re.compile(r'(.*?)(#)(.*)') return [search_re.sub(comment_replace, line) for line in input] def quote_replace(matchobj): return "%s%s%s%s" % (matchobj.group(1), matchobj.group(2), 'x'*len(matchobj.group(3)), matchobj.group(2)) def mask_quotes(input): """Mask the quoted strings so we skip braces inside quoted strings.""" search_re = re.compile(r'(.*?)' + QUOTE_RE_STR) return [search_re.sub(quote_replace, line) for line in input] def do_split(input, masked_input, search_re): output = [] mask_output = [] for (line, masked_line) in zip(input, masked_input): m = search_re.match(masked_line) while m: split = len(m.group(1)) line = line[:split] + r'\n' + line[split:] masked_line = masked_line[:split] + r'\n' + masked_line[split:] m = search_re.match(masked_line) output.extend(line.split(r'\n')) mask_output.extend(masked_line.split(r'\n')) return (output, mask_output) def split_double_braces(input): """Masks out the quotes and comments, and then splits appropriate lines (lines that matche the double_*_brace re's above) before indenting them below. These are used to split lines which have multiple braces on them, so that the indentation looks prettier when all laid out (e.g. closing braces make a nice diagonal line). """ double_open_brace_re = re.compile(r'(.*?[\[\{\(,])(\s*)([\[\{\(])') double_close_brace_re = re.compile(r'(.*?[\]\}\)],?)(\s*)([\]\}\)])') masked_input = mask_quotes(input) masked_input = mask_comments(masked_input) (output, mask_output) = do_split(input, masked_input, double_open_brace_re) (output, mask_output) = do_split(output, mask_output, double_close_brace_re) return output def count_braces(line): """keeps track of the number of braces on a given line and returns the result. It starts at zero and subtracts for closed braces, and adds for open braces. """ open_braces = ['[', '(', '{'] close_braces = [']', ')', '}'] closing_prefix_re = re.compile(r'(.*?[^\s\]\}\)]+.*?)([\]\}\)],?)\s*$') cnt = 0 stripline = COMMENT_RE.sub(r'', line) stripline = QUOTE_RE.sub(r"''", stripline) for char in stripline: for brace in open_braces: if char == brace: cnt += 1 for brace in close_braces: if char == brace: cnt -= 1 after = False if cnt > 0: after = True # This catches the special case of a closing brace having something # other than just whitespace ahead of it -- we don't want to # unindent that until after this line is printed so it stays with # the previous indentation level. if cnt < 0 and closing_prefix_re.match(stripline): after = True return (cnt, after) def prettyprint_input(lines): """Does the main work of indenting the input based on the brace counts.""" indent = 0 basic_offset = 2 last_line = "" for line in lines: if COMMENT_RE.match(line): print line else: line = line.strip('\r\n\t ') # Otherwise doesn't strip \r on Unix. if len(line) > 0: (brace_diff, after) = count_braces(line) if brace_diff != 0: if after: print " " * (basic_offset * indent) + line indent += brace_diff else: indent += brace_diff print " " * (basic_offset * indent) + line else: print " " * (basic_offset * indent) + line else: print "" last_line = line def main(): if len(sys.argv) > 1: data = open(sys.argv[1]).read().splitlines() else: data = sys.stdin.read().splitlines() # Split up the double braces. lines = split_double_braces(data) # Indent and print the output. prettyprint_input(lines) return 0 if __name__ == '__main__': sys.exit(main())
mit
ychen820/microblog
src/lib/flask/debughelpers.py
777
3508
# -*- coding: utf-8 -*- """ flask.debughelpers ~~~~~~~~~~~~~~~~~~ Various helpers to make the development experience better. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from ._compat import implements_to_string class UnexpectedUnicodeError(AssertionError, UnicodeError): """Raised in places where we want some better error reporting for unexpected unicode or binary data. """ @implements_to_string class DebugFilesKeyError(KeyError, AssertionError): """Raised from request.files during debugging. The idea is that it can provide a better error message than just a generic KeyError/BadRequest. """ def __init__(self, request, key): form_matches = request.form.getlist(key) buf = ['You tried to access the file "%s" in the request.files ' 'dictionary but it does not exist. The mimetype for the request ' 'is "%s" instead of "multipart/form-data" which means that no ' 'file contents were transmitted. To fix this error you should ' 'provide enctype="multipart/form-data" in your form.' % (key, request.mimetype)] if form_matches: buf.append('\n\nThe browser instead transmitted some file names. ' 'This was submitted: %s' % ', '.join('"%s"' % x for x in form_matches)) self.msg = ''.join(buf) def __str__(self): return self.msg class FormDataRoutingRedirect(AssertionError): """This exception is raised by Flask in debug mode if it detects a redirect caused by the routing system when the request method is not GET, HEAD or OPTIONS. Reasoning: form data will be dropped. """ def __init__(self, request): exc = request.routing_exception buf = ['A request was sent to this URL (%s) but a redirect was ' 'issued automatically by the routing system to "%s".' % (request.url, exc.new_url)] # In case just a slash was appended we can be extra helpful if request.base_url + '/' == exc.new_url.split('?')[0]: buf.append(' The URL was defined with a trailing slash so ' 'Flask will automatically redirect to the URL ' 'with the trailing slash if it was accessed ' 'without one.') buf.append(' Make sure to directly send your %s-request to this URL ' 'since we can\'t make browsers or HTTP clients redirect ' 'with form data reliably or without user interaction.' % request.method) buf.append('\n\nNote: this exception is only raised in debug mode') AssertionError.__init__(self, ''.join(buf).encode('utf-8')) def attach_enctype_error_multidict(request): """Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed. """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key): try: return oldcls.__getitem__(self, key) except KeyError as e: if key not in request.form: raise raise DebugFilesKeyError(request, key) newcls.__name__ = oldcls.__name__ newcls.__module__ = oldcls.__module__ request.files.__class__ = newcls
bsd-3-clause
agiliopadua/lammps
examples/PACKAGES/cgdna/util/generate.py
5
19265
#!/usr/bin/env python """ /* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/ Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Oliver Henrich (University of Strathclyde, Glasgow) ------------------------------------------------------------------------- */ """ """ Import basic modules """ import sys, os, timeit from timeit import default_timer as timer start_time = timer() """ Try to import numpy; if failed, import a local version mynumpy which needs to be provided """ try: import numpy as np except: print >> sys.stderr, "numpy not found. Exiting." sys.exit(1) """ Check that the required arguments (box offset and size in simulation units and the sequence file were provided """ try: box_offset = float(sys.argv[1]) box_length = float(sys.argv[2]) infile = sys.argv[3] except: print >> sys.stderr, "Usage: %s <%s> <%s> <%s>" % (sys.argv[0], \ "box offset", "box length", "file with sequences") sys.exit(1) box = np.array ([box_length, box_length, box_length]) """ Try to open the file and fail gracefully if file cannot be opened """ try: inp = open (infile, 'r') inp.close() except: print >> sys.stderr, "Could not open file '%s' for reading. \ Aborting." % infile sys.exit(2) # return parts of a string def partition(s, d): if d in s: sp = s.split(d, 1) return sp[0], d, sp[1] else: return s, "", "" """ Define the model constants """ # set model constants PI = np.pi POS_BASE = 0.4 POS_BACK = -0.4 EXCL_RC1 = 0.711879214356 EXCL_RC2 = 0.335388426126 EXCL_RC3 = 0.52329943261 """ Define auxiliary variables for the construction of a helix """ # center of the double strand CM_CENTER_DS = POS_BASE + 0.2 # ideal distance between base sites of two nucleotides # which are to be base paired in a duplex BASE_BASE = 0.3897628551303122 # cutoff distance for overlap check RC2 = 16 # squares of the excluded volume distances for overlap check RC2_BACK = EXCL_RC1**2 RC2_BASE = EXCL_RC2**2 RC2_BACK_BASE = EXCL_RC3**2 # enumeration to translate from letters to numbers and vice versa number_to_base = {1 : 'A', 2 : 'C', 3 : 'G', 4 : 'T'} base_to_number = {'A' : 1, 'a' : 1, 'C' : 2, 'c' : 2, 'G' : 3, 'g' : 3, 'T' : 4, 't' : 4} # auxiliary arrays positions = [] a1s = [] a3s = [] quaternions = [] newpositions = [] newa1s = [] newa3s = [] basetype = [] strandnum = [] bonds = [] """ Convert local body frame to quaternion DOF """ def exyz_to_quat (mya1, mya3): mya2 = np.cross(mya3, mya1) myquat = [1,0,0,0] q0sq = 0.25 * (mya1[0] + mya2[1] + mya3[2] + 1.0) q1sq = q0sq - 0.5 * (mya2[1] + mya3[2]) q2sq = q0sq - 0.5 * (mya1[0] + mya3[2]) q3sq = q0sq - 0.5 * (mya1[0] + mya2[1]) # some component must be greater than 1/4 since they sum to 1 # compute other components from it if q0sq >= 0.25: myquat[0] = np.sqrt(q0sq) myquat[1] = (mya2[2] - mya3[1]) / (4.0*myquat[0]) myquat[2] = (mya3[0] - mya1[2]) / (4.0*myquat[0]) myquat[3] = (mya1[1] - mya2[0]) / (4.0*myquat[0]) elif q1sq >= 0.25: myquat[1] = np.sqrt(q1sq) myquat[0] = (mya2[2] - mya3[1]) / (4.0*myquat[1]) myquat[2] = (mya2[0] + mya1[1]) / (4.0*myquat[1]) myquat[3] = (mya1[2] + mya3[0]) / (4.0*myquat[1]) elif q2sq >= 0.25: myquat[2] = np.sqrt(q2sq) myquat[0] = (mya3[0] - mya1[2]) / (4.0*myquat[2]) myquat[1] = (mya2[0] + mya1[1]) / (4.0*myquat[2]) myquat[3] = (mya3[1] + mya2[2]) / (4.0*myquat[2]) elif q3sq >= 0.25: myquat[3] = np.sqrt(q3sq) myquat[0] = (mya1[1] - mya2[0]) / (4.0*myquat[3]) myquat[1] = (mya3[0] + mya1[2]) / (4.0*myquat[3]) myquat[2] = (mya3[1] + mya2[2]) / (4.0*myquat[3]) norm = 1.0/np.sqrt(myquat[0]*myquat[0] + myquat[1]*myquat[1] + \ myquat[2]*myquat[2] + myquat[3]*myquat[3]) myquat[0] *= norm myquat[1] *= norm myquat[2] *= norm myquat[3] *= norm return np.array([myquat[0],myquat[1],myquat[2],myquat[3]]) """ Adds a strand to the system by appending it to the array of previous strands """ def add_strands (mynewpositions, mynewa1s, mynewa3s): overlap = False # This is a simple check for each of the particles where for previously # placed particles i we check whether it overlaps with any of the # newly created particles j print >> sys.stdout, "## Checking for overlaps" for i in xrange(len(positions)): p = positions[i] pa1 = a1s[i] for j in xrange (len(mynewpositions)): q = mynewpositions[j] qa1 = mynewa1s[j] # skip particles that are anyway too far away dr = p - q dr -= box * np.rint (dr / box) if np.dot(dr, dr) > RC2: continue # base site and backbone site of the two particles p_pos_back = p + pa1 * POS_BACK p_pos_base = p + pa1 * POS_BASE q_pos_back = q + qa1 * POS_BACK q_pos_base = q + qa1 * POS_BASE # check for no overlap between the two backbone sites dr = p_pos_back - q_pos_back dr -= box * np.rint (dr / box) if np.dot(dr, dr) < RC2_BACK: overlap = True # check for no overlap between the two base sites dr = p_pos_base - q_pos_base dr -= box * np.rint (dr / box) if np.dot(dr, dr) < RC2_BASE: overlap = True # check for no overlap between backbone site of particle p # with base site of particle q dr = p_pos_back - q_pos_base dr -= box * np.rint (dr / box) if np.dot(dr, dr) < RC2_BACK_BASE: overlap = True # check for no overlap between base site of particle p and # backbone site of particle q dr = p_pos_base - q_pos_back dr -= box * np.rint (dr / box) if np.dot(dr, dr) < RC2_BACK_BASE: overlap = True # exit if there is an overlap if overlap: return False # append to the existing list if no overlap is found if not overlap: for p in mynewpositions: positions.append(p) for p in mynewa1s: a1s.append (p) for p in mynewa3s: a3s.append (p) # calculate quaternion from local body frame and append for ia in xrange(len(mynewpositions)): mynewquaternions = exyz_to_quat(mynewa1s[ia],mynewa3s[ia]) quaternions.append(mynewquaternions) return True """ Returns the rotation matrix defined by an axis and angle """ def get_rotation_matrix(axis, anglest): # The argument anglest can be either an angle in radiants # (accepted types are float, int or np.float64 or np.float64) # or a tuple [angle, units] where angle is a number and # units is a string. It tells the routine whether to use degrees, # radiants (the default) or base pairs turns. if not isinstance (anglest, (np.float64, np.float32, float, int)): if len(anglest) > 1: if anglest[1] in ["degrees", "deg", "o"]: #angle = np.deg2rad (anglest[0]) angle = (np.pi / 180.) * (anglest[0]) elif anglest[1] in ["bp"]: angle = int(anglest[0]) * (np.pi / 180.) * (35.9) else: angle = float(anglest[0]) else: angle = float(anglest[0]) else: angle = float(anglest) # in degrees (?) axis = np.array(axis) axis /= np.sqrt(np.dot(axis, axis)) ct = np.cos(angle) st = np.sin(angle) olc = 1. - ct x, y, z = axis return np.array([[olc*x*x+ct, olc*x*y-st*z, olc*x*z+st*y], [olc*x*y+st*z, olc*y*y+ct, olc*y*z-st*x], [olc*x*z-st*y, olc*y*z+st*x, olc*z*z+ct]]) """ Generates the position and orientation vectors of a (single or double) strand from a sequence string """ def generate_strand(bp, sequence=None, start_pos=np.array([0, 0, 0]), \ dir=np.array([0, 0, 1]), perp=False, double=True, rot=0.): # generate empty arrays mynewpositions, mynewa1s, mynewa3s = [], [], [] # cast the provided start_pos array into a numpy array start_pos = np.array(start_pos, dtype=float) # overall direction of the helix dir = np.array(dir, dtype=float) if sequence == None: sequence = np.random.randint(1, 5, bp) # the elseif here is most likely redundant elif len(sequence) != bp: n = bp - len(sequence) sequence += np.random.randint(1, 5, n) print >> sys.stderr, "sequence is too short, adding %d random bases" % n # normalize direction dir_norm = np.sqrt(np.dot(dir,dir)) if dir_norm < 1e-10: print >> sys.stderr, "direction must be a valid vector, \ defaulting to (0, 0, 1)" dir = np.array([0, 0, 1]) else: dir /= dir_norm # find a vector orthogonal to dir to act as helix direction, # if not provided switch off random orientation if perp is None or perp is False: v1 = np.random.random_sample(3) v1 -= dir * (np.dot(dir, v1)) v1 /= np.sqrt(sum(v1*v1)) else: v1 = perp; # generate rotational matrix representing the overall rotation of the helix R0 = get_rotation_matrix(dir, rot) # rotation matrix corresponding to one step along the helix R = get_rotation_matrix(dir, [1, "bp"]) # set the vector a1 (backbone to base) to v1 a1 = v1 # apply the global rotation to a1 a1 = np.dot(R0, a1) # set the position of the fist backbone site to start_pos rb = np.array(start_pos) # set a3 to the direction of the helix a3 = dir for i in range(bp): # work out the position of the centre of mass of the nucleotide rcdm = rb - CM_CENTER_DS * a1 # append to newpositions mynewpositions.append(rcdm) mynewa1s.append(a1) mynewa3s.append(a3) # if we are not at the end of the helix, we work out a1 and rb for the # next nucleotide along the helix if i != bp - 1: a1 = np.dot(R, a1) rb += a3 * BASE_BASE # if we are working on a double strand, we do a cycle similar # to the previous one but backwards if double == True: a1 = -a1 a3 = -dir R = R.transpose() for i in range(bp): rcdm = rb - CM_CENTER_DS * a1 mynewpositions.append (rcdm) mynewa1s.append (a1) mynewa3s.append (a3) a1 = np.dot(R, a1) rb += a3 * BASE_BASE assert (len (mynewpositions) > 0) return [mynewpositions, mynewa1s, mynewa3s] """ Main function for this script. Reads a text file with the following format: - Each line contains the sequence for a single strand (A,C,G,T) - Lines beginning with the keyword 'DOUBLE' produce double-stranded DNA Ex: Two ssDNA (single stranded DNA) ATATATA GCGCGCG Ex: Two strands, one double stranded, the other single stranded. DOUBLE AGGGCT CCTGTA """ def read_strands(filename): try: infile = open (filename) except: print >> sys.stderr, "Could not open file '%s'. Aborting." % filename sys.exit(2) # This block works out the number of nucleotides and strands by reading # the number of non-empty lines in the input file and the number of letters, # taking the possible DOUBLE keyword into account. nstrands, nnucl, nbonds = 0, 0, 0 lines = infile.readlines() for line in lines: line = line.upper().strip() if len(line) == 0: continue if line[:6] == 'DOUBLE': line = line.split()[1] length = len(line) print >> sys.stdout, "## Found duplex of %i base pairs" % length nnucl += 2*length nstrands += 2 nbonds += (2*length-2) else: line = line.split()[0] length = len(line) print >> sys.stdout, \ "## Found single strand of %i bases" % length nnucl += length nstrands += 1 nbonds += length-1 # rewind the sequence input file infile.seek(0) print >> sys.stdout, "## nstrands, nnucl = ", nstrands, nnucl # generate the data file in LAMMPS format try: out = open ("data.oxdna", "w") except: print >> sys.stderr, "Could not open data file for writing. Aborting." sys.exit(2) lines = infile.readlines() nlines = len(lines) i = 1 myns = 0 noffset = 1 for line in lines: line = line.upper().strip() # skip empty lines if len(line) == 0: i += 1 continue # block for duplexes: last argument of the generate function # is set to 'True' if line[:6] == 'DOUBLE': line = line.split()[1] length = len(line) seq = [(base_to_number[x]) for x in line] myns += 1 for b in xrange(length): basetype.append(seq[b]) strandnum.append(myns) for b in xrange(length-1): bondpair = [noffset + b, noffset + b + 1] bonds.append(bondpair) noffset += length # create the sequence of the second strand as made of # complementary bases seq2 = [5-s for s in seq] seq2.reverse() myns += 1 for b in xrange(length): basetype.append(seq2[b]) strandnum.append(myns) for b in xrange(length-1): bondpair = [noffset + b, noffset + b + 1] bonds.append(bondpair) noffset += length print >> sys.stdout, "## Created duplex of %i bases" % (2*length) # generate random position of the first nucleotide cdm = box_offset + np.random.random_sample(3) * box # generate the random direction of the helix axis = np.random.random_sample(3) axis /= np.sqrt(np.dot(axis, axis)) # use the generate function defined above to create # the position and orientation vector of the strand newpositions, newa1s, newa3s = generate_strand(len(line), \ sequence=seq, dir=axis, start_pos=cdm, double=True) # generate a new position for the strand until it does not overlap # with anything already present start = timer() while not add_strands(newpositions, newa1s, newa3s): cdm = box_offset + np.random.random_sample(3) * box axis = np.random.random_sample(3) axis /= np.sqrt(np.dot(axis, axis)) newpositions, newa1s, newa3s = generate_strand(len(line), \ sequence=seq, dir=axis, start_pos=cdm, double=True) print >> sys.stdout, "## Trying %i" % i end = timer() print >> sys.stdout, "## Added duplex of %i bases (line %i/%i) in %.2fs, now at %i/%i" % \ (2*length, i, nlines, end-start, len(positions), nnucl) # block for single strands: last argument of the generate function # is set to 'False' else: length = len(line) seq = [(base_to_number[x]) for x in line] myns += 1 for b in xrange(length): basetype.append(seq[b]) strandnum.append(myns) for b in xrange(length-1): bondpair = [noffset + b, noffset + b + 1] bonds.append(bondpair) noffset += length # generate random position of the first nucleotide cdm = box_offset + np.random.random_sample(3) * box # generate the random direction of the helix axis = np.random.random_sample(3) axis /= np.sqrt(np.dot(axis, axis)) print >> sys.stdout, \ "## Created single strand of %i bases" % length newpositions, newa1s, newa3s = generate_strand(length, \ sequence=seq, dir=axis, start_pos=cdm, double=False) start = timer() while not add_strands(newpositions, newa1s, newa3s): cdm = box_offset + np.random.random_sample(3) * box axis = np.random.random_sample(3) axis /= np.sqrt(np.dot(axis, axis)) newpositions, newa1s, newa3s = generate_strand(length, \ sequence=seq, dir=axis, start_pos=cdm, double=False) print >> sys.stdout, "## Trying %i" % (i) end = timer() print >> sys.stdout, "## Added single strand of %i bases (line %i/%i) in %.2fs, now at %i/%i" % \ (length, i, nlines, end-start,len(positions), nnucl) i += 1 # sanity check if not len(positions) == nnucl: print len(positions), nnucl raise AssertionError out.write('# LAMMPS data file\n') out.write('%d atoms\n' % nnucl) out.write('%d ellipsoids\n' % nnucl) out.write('%d bonds\n' % nbonds) out.write('\n') out.write('4 atom types\n') out.write('1 bond types\n') out.write('\n') out.write('# System size\n') out.write('%f %f xlo xhi\n' % (box_offset,box_offset+box_length)) out.write('%f %f ylo yhi\n' % (box_offset,box_offset+box_length)) out.write('%f %f zlo zhi\n' % (box_offset,box_offset+box_length)) out.write('\n') out.write('Masses\n') out.write('\n') out.write('1 3.1575\n') out.write('2 3.1575\n') out.write('3 3.1575\n') out.write('4 3.1575\n') # for each nucleotide print a line under the headers # Atoms, Velocities, Ellipsoids and Bonds out.write('\n') out.write(\ '# Atom-ID, type, position, molecule-ID, ellipsoid flag, density\n') out.write('Atoms\n') out.write('\n') for i in xrange(nnucl): out.write('%d %d %22.15le %22.15le %22.15le %d 1 1\n' \ % (i+1, basetype[i], \ positions[i][0], positions[i][1], positions[i][2], \ strandnum[i])) out.write('\n') out.write('# Atom-ID, translational, rotational velocity\n') out.write('Velocities\n') out.write('\n') for i in xrange(nnucl): out.write("%d %22.15le %22.15le %22.15le %22.15le %22.15le %22.15le\n" \ % (i+1,0.0,0.0,0.0,0.0,0.0,0.0)) out.write('\n') out.write('# Atom-ID, shape, quaternion\n') out.write('Ellipsoids\n') out.write('\n') for i in xrange(nnucl): out.write(\ "%d %22.15le %22.15le %22.15le %22.15le %22.15le %22.15le %22.15le\n" \ % (i+1,1.1739845031423408,1.1739845031423408,1.1739845031423408, \ quaternions[i][0],quaternions[i][1], quaternions[i][2],quaternions[i][3])) out.write('\n') out.write('# Bond topology\n') out.write('Bonds\n') out.write('\n') for i in xrange(nbonds): out.write("%d %d %d %d\n" % (i+1,1,bonds[i][0],bonds[i][1])) out.close() print >> sys.stdout, "## Wrote data to 'data.oxdna'" print >> sys.stdout, "## DONE" # call the above main() function, which executes the program read_strands (infile) end_time=timer() runtime = end_time-start_time hours = runtime/3600 minutes = (runtime-np.rint(hours)*3600)/60 seconds = (runtime-np.rint(hours)*3600-np.rint(minutes)*60)%60 print >> sys.stdout, "## Total runtime %ih:%im:%.2fs" % (hours,minutes,seconds)
gpl-2.0
LearnEra/LearnEra-Configuration
playbooks/callback_plugins/hipchat_plugin.py
51
9800
import os import time from ansible import utils try: import prettytable except ImportError: prettytable = None try: import hipchat except ImportError: hipchat = None class CallbackModule(object): """Send status updates to a HipChat channel during playbook execution. This plugin makes use of the following environment variables: HIPCHAT_TOKEN (required): HipChat API token HIPCHAT_ROOM (optional): HipChat room to post in. Default: ansible HIPCHAT_FROM (optional): Name to post as. Default: ansible HIPCHAT_NOTIFY (optional): Add notify flag to important messages ("true" or "false"). Default: true HIPCHAT_MSG_PREFIX (option): Optional prefix to add to all hipchat messages HIPCHAT_MSG_COLOR (option): Optional color for hipchat messages HIPCHAT_CONDENSED (option): Condense the task summary output Requires: prettytable """ def __init__(self): self.enabled = "HIPCHAT_TOKEN" in os.environ if not self.enabled: return # make sure we got our imports if not hipchat: raise ImportError( "The hipchat plugin requires the hipchat Python module, " "which is not installed or was not found." ) if not prettytable: raise ImportError( "The hipchat plugin requires the prettytable Python module, " "which is not installed or was not found." ) self.start_time = time.time() self.task_report = [] self.last_task = None self.last_task_changed = False self.last_task_count = 0 self.last_task_delta = 0 self.last_task_start = time.time() self.condensed_task_report = (os.getenv('HIPCHAT_CONDENSED', True) == True) self.room = os.getenv('HIPCHAT_ROOM', 'ansible') self.from_name = os.getenv('HIPCHAT_FROM', 'ansible') self.allow_notify = (os.getenv('HIPCHAT_NOTIFY') != 'false') try: self.hipchat_conn = hipchat.HipChat(token=os.getenv('HIPCHAT_TOKEN')) except Exception as e: utils.warning("Unable to connect to hipchat: {}".format(e)) self.hipchat_msg_prefix = os.getenv('HIPCHAT_MSG_PREFIX', '') self.hipchat_msg_color = os.getenv('HIPCHAT_MSG_COLOR', '') self.printed_playbook = False self.playbook_name = None def _send_hipchat(self, message, room=None, from_name=None, color=None, message_format='text'): if not room: room = self.room if not from_name: from_name = self.from_name if not color: color = self.hipchat_msg_color try: self.hipchat_conn.message_room(room, from_name, message, color=color, message_format=message_format) except Exception as e: utils.warning("Could not submit message to hipchat: {}".format(e)) def _flush_last_task(self): if self.last_task: delta = time.time() - self.last_task_start self.task_report.append(dict( changed=self.last_task_changed, count=self.last_task_count, delta="{:0>.1f}".format(self.last_task_delta), task=self.last_task)) self.last_task_count = 0 self.last_task_changed = False self.last_task = None self.last_task_delta = 0 def _process_message(self, msg, msg_type='STATUS'): if msg_type == 'OK' and self.last_task: if msg.get('changed', True): self.last_task_changed = True if msg.get('delta', False): (hour, minute, sec) = msg['delta'].split(':') total = float(hour) * 1200 + float(minute) * 60 + float(sec) self.last_task_delta += total self.last_task_count += 1 else: self._flush_last_task() if msg_type == 'TASK_START': self.last_task = msg self.last_task_start = time.time() elif msg_type == 'FAILED': self.last_task_start = time.time() if 'msg' in msg: self._send_hipchat('/code {}: The ansible run returned the following error:\n\n {}'.format( self.hipchat_msg_prefix, msg['msg']), color='red', message_format='text') else: # move forward the last task start time self.last_task_start = time.time() def on_any(self, *args, **kwargs): pass def runner_on_failed(self, host, res, ignore_errors=False): if self.enabled: self._process_message(res, 'FAILED') def runner_on_ok(self, host, res): if self.enabled: # don't send the setup results if res['invocation']['module_name'] != "setup": self._process_message(res, 'OK') def runner_on_error(self, host, msg): if self.enabled: self._process_message(msg, 'ERROR') def runner_on_skipped(self, host, item=None): if self.enabled: self._process_message(item, 'SKIPPED') 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): if self.enabled: self._process_message(res, 'ASYNC_POLL') def runner_on_async_ok(self, host, res, jid): if self.enabled: self._process_message(res, 'ASYNC_OK') def runner_on_async_failed(self, host, res, jid): if self.enabled: self._process_message(res, 'ASYNC_FAILED') 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): if self.enabled: self._process_message(name, 'TASK_START') 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, pattern): if self.enabled: """Display Playbook and play start messages""" self.start_time = time.time() self.playbook_name, _ = os.path.splitext(os.path.basename(self.play.playbook.filename)) host_list = self.play.playbook.inventory.host_list inventory = os.path.basename(os.path.realpath(host_list)) subset = self.play.playbook.inventory._subset msg = "<b>{description}</b>: Starting ansible run for play <b><i>{play}</i></b>".format(description=self.hipchat_msg_prefix, play=self.playbook_name) if self.play.playbook.only_tags and 'all' not in self.play.playbook.only_tags: msg = msg + " with tags <b><i>{}</i></b>".format(','.join(self.play.playbook.only_tags)) if subset: msg = msg + " on hosts <b><i>{}</i></b>".format(','.join(subset)) self._send_hipchat(msg, message_format='html') def playbook_on_stats(self, stats): if self.enabled: self._flush_last_task() delta = time.time() - self.start_time self.start_time = time.time() """Display info about playbook statistics""" hosts = sorted(stats.processed.keys()) task_column = '{} - Task'.format(self.hipchat_msg_prefix) task_summary = prettytable.PrettyTable([task_column, 'Time', 'Count', 'Changed']) task_summary.align[task_column] = "l" task_summary.align['Time'] = "r" task_summary.align['Count'] = "r" task_summary.align['Changed'] = "r" for task in self.task_report: if self.condensed_task_report: # for the condensed task report skip all tasks # that are not marked as changed and that have # a time delta less than 1 if not task['changed'] and float(task['delta']) < 1: continue task_summary.add_row([task['task'], task['delta'], str(task['count']), str(task['changed'])]) summary_table = prettytable.PrettyTable(['Ok', 'Changed', 'Unreachable', 'Failures']) self._send_hipchat("/code " + str(task_summary) ) summary_all_host_output = [] for host in hosts: stats = stats.summarize(host) summary_output = "<b>{}</b>: <i>{}</i> - ".format(self.hipchat_msg_prefix, host) for summary_item in ['ok', 'changed', 'unreachable', 'failures']: if stats[summary_item] != 0: summary_output += "<b>{}</b> - {} ".format(summary_item, stats[summary_item]) summary_all_host_output.append(summary_output) self._send_hipchat("<br />".join(summary_all_host_output), message_format='html') msg = "<b>{description}</b>: Finished Ansible run for <b><i>{play}</i> in {min:02} minutes, {sec:02} seconds</b><br /><br />".format( description=self.hipchat_msg_prefix, play=self.playbook_name, min=int(delta / 60), sec=int(delta % 60)) self._send_hipchat(msg, message_format='html')
agpl-3.0
sebalix/OpenUpgrade
addons/product_extended/wizard/__init__.py
374
1078
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # 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/>. # ############################################################################## import wizard_price # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
adrienbrault/home-assistant
homeassistant/components/nissan_leaf/binary_sensor.py
21
1707
"""Plugged In Status Support for the Nissan Leaf.""" import logging from homeassistant.components.binary_sensor import BinarySensorEntity from . import DATA_CHARGING, DATA_LEAF, DATA_PLUGGED_IN, LeafEntity _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up of a Nissan Leaf binary sensor.""" if discovery_info is None: return devices = [] for vin, datastore in hass.data[DATA_LEAF].items(): _LOGGER.debug("Adding binary_sensors for vin=%s", vin) devices.append(LeafPluggedInSensor(datastore)) devices.append(LeafChargingSensor(datastore)) add_entities(devices, True) class LeafPluggedInSensor(LeafEntity, BinarySensorEntity): """Plugged In Sensor class.""" @property def name(self): """Sensor name.""" return f"{self.car.leaf.nickname} Plug Status" @property def is_on(self): """Return true if plugged in.""" return self.car.data[DATA_PLUGGED_IN] @property def icon(self): """Icon handling.""" if self.car.data[DATA_PLUGGED_IN]: return "mdi:power-plug" return "mdi:power-plug-off" class LeafChargingSensor(LeafEntity, BinarySensorEntity): """Charging Sensor class.""" @property def name(self): """Sensor name.""" return f"{self.car.leaf.nickname} Charging Status" @property def is_on(self): """Return true if charging.""" return self.car.data[DATA_CHARGING] @property def icon(self): """Icon handling.""" if self.car.data[DATA_CHARGING]: return "mdi:flash" return "mdi:flash-off"
mit
havard024/prego
venv/lib/python2.7/site-packages/django/utils/unittest/loader.py
109
13441
"""Loading unittests.""" import os import re import sys import traceback import types import unittest from fnmatch import fnmatch from django.utils.unittest import case, suite try: from os.path import relpath except ImportError: from django.utils.unittest.compatibility import relpath __unittest = True def _CmpToKey(mycmp): 'Convert a cmp= function into a key= function' class K(object): def __init__(self, obj): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) == -1 return K # what about .pyc or .pyo (etc) # we would need to avoid loading the same tests multiple times # from '.py', '.pyc' *and* '.pyo' VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE) def _make_failed_import_test(name, suiteClass): message = 'Failed to import test module: %s' % name if hasattr(traceback, 'format_exc'): # Python 2.3 compatibility # format_exc returns two frames of discover.py as well message += '\n%s' % traceback.format_exc() return _make_failed_test('ModuleImportFailure', name, ImportError(message), suiteClass) def _make_failed_load_tests(name, exception, suiteClass): return _make_failed_test('LoadTestsFailure', name, exception, suiteClass) def _make_failed_test(classname, methodname, exception, suiteClass): def testFailure(self): raise exception attrs = {methodname: testFailure} TestClass = type(classname, (case.TestCase,), attrs) return suiteClass((TestClass(methodname),)) class TestLoader(unittest.TestLoader): """ This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite """ testMethodPrefix = 'test' sortTestMethodsUsing = cmp suiteClass = suite.TestSuite _top_level_dir = None def loadTestsFromTestCase(self, testCaseClass): """Return a suite of all tests cases contained in testCaseClass""" if issubclass(testCaseClass, suite.TestSuite): raise TypeError("Test cases should not be derived from TestSuite." " Maybe you meant to derive from TestCase?") testCaseNames = self.getTestCaseNames(testCaseClass) if not testCaseNames and hasattr(testCaseClass, 'runTest'): testCaseNames = ['runTest'] loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) return loaded_suite def loadTestsFromModule(self, module, use_load_tests=True): """Return a suite of all tests cases contained in the given module""" tests = [] for name in dir(module): obj = getattr(module, name) if isinstance(obj, type) and issubclass(obj, unittest.TestCase): tests.append(self.loadTestsFromTestCase(obj)) load_tests = getattr(module, 'load_tests', None) tests = self.suiteClass(tests) if use_load_tests and load_tests is not None: try: return load_tests(self, tests, None) except Exception as e: return _make_failed_load_tests(module.__name__, e, self.suiteClass) return tests def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier. The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a TestCase or TestSuite instance. The method optionally resolves the names relative to a given module. """ parts = name.split('.') if module is None: parts_copy = parts[:] while parts_copy: try: module = __import__('.'.join(parts_copy)) break except ImportError: del parts_copy[-1] if not parts_copy: raise parts = parts[1:] obj = module for part in parts: parent, obj = obj, getattr(obj, part) if isinstance(obj, types.ModuleType): return self.loadTestsFromModule(obj) elif isinstance(obj, type) and issubclass(obj, unittest.TestCase): return self.loadTestsFromTestCase(obj) elif (isinstance(obj, types.UnboundMethodType) and isinstance(parent, type) and issubclass(parent, case.TestCase)): return self.suiteClass([parent(obj.__name__)]) elif isinstance(obj, unittest.TestSuite): return obj elif hasattr(obj, '__call__'): test = obj() if isinstance(test, unittest.TestSuite): return test elif isinstance(test, unittest.TestCase): return self.suiteClass([test]) else: raise TypeError("calling %s returned %s, not a test" % (obj, test)) else: raise TypeError("don't know how to make test from: %s" % obj) def loadTestsFromNames(self, names, module=None): """Return a suite of all tests cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. """ suites = [self.loadTestsFromName(name, module) for name in names] return self.suiteClass(suites) def getTestCaseNames(self, testCaseClass): """Return a sorted sequence of method names found within testCaseClass """ def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix): return attrname.startswith(prefix) and \ hasattr(getattr(testCaseClass, attrname), '__call__') testFnNames = filter(isTestMethod, dir(testCaseClass)) if self.sortTestMethodsUsing: testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing)) return testFnNames def discover(self, start_dir, pattern='test*.py', top_level_dir=None): """Find and return all test modules from the specified start directory, recursing into subdirectories to find them. Only test files that match the pattern will be loaded. (Using shell style pattern matching.) All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately. If a test package name (directory with '__init__.py') matches the pattern then the package will be checked for a 'load_tests' function. If this exists then it will be called with loader, tests, pattern. If load_tests exists then discovery does *not* recurse into the package, load_tests is responsible for loading all tests in the package. The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. top_level_dir is stored so load_tests does not need to pass this argument in to loader.discover(). """ set_implicit_top = False if top_level_dir is None and self._top_level_dir is not None: # make top_level_dir optional if called from load_tests in a package top_level_dir = self._top_level_dir elif top_level_dir is None: set_implicit_top = True top_level_dir = start_dir top_level_dir = os.path.abspath(top_level_dir) if not top_level_dir in sys.path: # all test modules must be importable from the top level directory # should we *unconditionally* put the start directory in first # in sys.path to minimise likelihood of conflicts between installed # modules and development versions? sys.path.insert(0, top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False if os.path.isdir(os.path.abspath(start_dir)): start_dir = os.path.abspath(start_dir) if start_dir != top_level_dir: is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py')) else: # support for discovery from dotted module names try: __import__(start_dir) except ImportError: is_not_importable = True else: the_module = sys.modules[start_dir] top_part = start_dir.split('.')[0] start_dir = os.path.abspath(os.path.dirname((the_module.__file__))) if set_implicit_top: self._top_level_dir = os.path.abspath(os.path.dirname(os.path.dirname(sys.modules[top_part].__file__))) sys.path.remove(top_level_dir) if is_not_importable: raise ImportError('Start directory is not importable: %r' % start_dir) tests = list(self._find_tests(start_dir, pattern)) return self.suiteClass(tests) def _get_name_from_path(self, path): path = os.path.splitext(os.path.normpath(path))[0] _relpath = relpath(path, self._top_level_dir) assert not os.path.isabs(_relpath), "Path must be within the project" assert not _relpath.startswith('..'), "Path must be within the project" name = _relpath.replace(os.path.sep, '.') return name def _get_module_from_name(self, name): __import__(name) return sys.modules[name] def _match_path(self, path, full_path, pattern): # override this method to use alternative matching strategy return fnmatch(path, pattern) def _find_tests(self, start_dir, pattern): """Used by discovery. Yields test suites it loads.""" paths = os.listdir(start_dir) for path in paths: full_path = os.path.join(start_dir, path) if os.path.isfile(full_path): if not VALID_MODULE_NAME.match(path): # valid Python identifiers only continue if not self._match_path(path, full_path, pattern): continue # if the test file matches, load it name = self._get_name_from_path(full_path) try: module = self._get_module_from_name(name) except: yield _make_failed_import_test(name, self.suiteClass) else: mod_file = os.path.abspath(getattr(module, '__file__', full_path)) realpath = os.path.splitext(mod_file)[0] fullpath_noext = os.path.splitext(full_path)[0] if realpath.lower() != fullpath_noext.lower(): module_dir = os.path.dirname(realpath) mod_name = os.path.splitext(os.path.basename(full_path))[0] expected_dir = os.path.dirname(full_path) msg = ("%r module incorrectly imported from %r. Expected %r. " "Is this module globally installed?") raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): continue load_tests = None tests = None if fnmatch(path, pattern): # only check load_tests if the package directory itself matches the filter name = self._get_name_from_path(full_path) package = self._get_module_from_name(name) load_tests = getattr(package, 'load_tests', None) tests = self.loadTestsFromModule(package, use_load_tests=False) if load_tests is None: if tests is not None: # tests loaded from package file yield tests # recurse into the package for test in self._find_tests(full_path, pattern): yield test else: try: yield load_tests(self, tests, pattern) except Exception as e: yield _make_failed_load_tests(package.__name__, e, self.suiteClass) defaultTestLoader = TestLoader() def _makeLoader(prefix, sortUsing, suiteClass=None): loader = TestLoader() loader.sortTestMethodsUsing = sortUsing loader.testMethodPrefix = prefix if suiteClass: loader.suiteClass = suiteClass return loader def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass) def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=suite.TestSuite): return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass) def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=suite.TestSuite): return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
mit
billyhunt/osf.io
scripts/cron.py
10
2772
# -*- coding: utf-8 -*- import os import sys import logging import crontab from website import settings logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def app_prefix(path): return os.path.join(settings.APP_PATH, path) def ensure_item(cron, command): items = list(cron.find_command(command)) return items[0] if items else cron.new(command) def main(dry_run=True): cron = crontab.CronTab(user=settings.CRON_USER) analytics = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/analytics.sh'))) analytics.hour.on(2) analytics.minute.on(0) # Daily 2:00 a.m. box = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/refresh_box_tokens.sh'))) box.hour.on(2) box.minute.on(0) # Daily 2:00 a.m. retractions = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/retract_registrations.sh'))) retractions.hour.on(0) retractions.minute.on(0) # Daily 12 a.m. embargoes = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/embargo_registrations.sh'))) embargoes.hour.on(0) embargoes.minute.on(0) # Daily 12 a.m. registration_approvals = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/approve_registrations.sh'))) registration_approvals.hour.on(0) registration_approvals.minute.on(0) # Daily 12 a.m. files_audit = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/osfstorage/files_audit.sh'))) files_audit.dow.on(0) files_audit.hour.on(2) files_audit.minute.on(0) # Sunday 2:00 a.m. glacier_inventory = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/osfstorage/glacier_inventory.sh'))) glacier_inventory.dow.on(0) glacier_inventory.hour.on(0) glacier_inventory.minute.on(0) # Sunday 12:00 a.m. glacier_audit = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/osfstorage/glacier_audit.sh'))) glacier_audit.dow.on(0) glacier_audit.hour.on(6) glacier_audit.minute.on(0) # Sunday 6:00 a.m. triggered_mails = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/triggered_mails.sh'))) triggered_mails.hour.on(0) triggered_mails.minute.on(0) # Daily 12 a.m. send_queued_mails = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/send_queued_mails.sh'))) send_queued_mails.hour.on(12) send_queued_mails.minute.on(0) # Daily 12 p.m. usage_audit = ensure_item(cron, 'bash {}'.format(app_prefix('scripts/osfstorage/usage_audit.sh'))) usage_audit.hour.on(0) usage_audit.minute.on(0) # Daily 12 a.m. logger.info('Updating crontab file:') logger.info(cron.render()) if not dry_run: cron.write_to_user(settings.CRON_USER) if __name__ == '__main__': dry_run = 'dry' in sys.argv main(dry_run=dry_run)
apache-2.0
ToonTownInfiniteRepo/ToontownInfinite
toontown/coghq/DistributedStomperAI.py
4
1783
from otp.ai.AIBase import * from direct.interval.IntervalGlobal import * from direct.directnotify import DirectNotifyGlobal import DistributedCrusherEntityAI import StomperGlobals from direct.distributed import ClockDelta from toontown.coghq import CrusherCellAI class DistributedStomperAI(DistributedCrusherEntityAI.DistributedCrusherEntityAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedStomperAI') def __init__(self, level, entId, pairId = -1): DistributedCrusherEntityAI.DistributedCrusherEntityAI.__init__(self, level, entId) self.pairId = pairId def generate(self): DistributedCrusherEntityAI.DistributedCrusherEntityAI.generate(self) if self.switchId != 0: self.accept(self.getOutputEventName(self.switchId), self.reactToSwitch) self.d_startStomper() def delete(self): del self.pos self.ignoreAll() DistributedCrusherEntityAI.DistributedCrusherEntityAI.delete(self) def d_startStomper(self): self.sendUpdate('setMovie', [StomperGlobals.STOMPER_START, ClockDelta.globalClockDelta.getRealNetworkTime(), []]) def reactToSwitch(self, on): if on: crushedList = [] if self.crushCell: self.crushCell.updateCrushables() for id in self.crushCell.occupantIds: if id in self.crushCell.crushables: crushedList.append(id) self.sendCrushMsg() self.sendUpdate('setMovie', [StomperGlobals.STOMPER_STOMP, ClockDelta.globalClockDelta.getRealNetworkTime(), crushedList]) else: self.sendUpdate('setMovie', [StomperGlobals.STOMPER_RISE, ClockDelta.globalClockDelta.getRealNetworkTime(), []])
mit
home-assistant/home-assistant
homeassistant/components/devolo_home_control/sensor.py
2
5953
"""Platform for sensor integration.""" from homeassistant.components.sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_ENERGY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_POWER, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_VOLTAGE, SensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import PERCENTAGE from homeassistant.core import HomeAssistant from .const import DOMAIN from .devolo_device import DevoloDeviceEntity DEVICE_CLASS_MAPPING = { "battery": DEVICE_CLASS_BATTERY, "temperature": DEVICE_CLASS_TEMPERATURE, "light": DEVICE_CLASS_ILLUMINANCE, "humidity": DEVICE_CLASS_HUMIDITY, "current": DEVICE_CLASS_POWER, "total": DEVICE_CLASS_ENERGY, "voltage": DEVICE_CLASS_VOLTAGE, } async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Get all sensor devices and setup them via config entry.""" entities = [] for gateway in hass.data[DOMAIN][entry.entry_id]["gateways"]: for device in gateway.multi_level_sensor_devices: for multi_level_sensor in device.multi_level_sensor_property: entities.append( DevoloGenericMultiLevelDeviceEntity( homecontrol=gateway, device_instance=device, element_uid=multi_level_sensor, ) ) for device in gateway.devices.values(): if hasattr(device, "consumption_property"): for consumption in device.consumption_property: for consumption_type in ["current", "total"]: entities.append( DevoloConsumptionEntity( homecontrol=gateway, device_instance=device, element_uid=consumption, consumption=consumption_type, ) ) if hasattr(device, "battery_level"): entities.append( DevoloBatteryEntity( homecontrol=gateway, device_instance=device, element_uid=f"devolo.BatterySensor:{device.uid}", ) ) async_add_entities(entities, False) class DevoloMultiLevelDeviceEntity(DevoloDeviceEntity, SensorEntity): """Abstract representation of a multi level sensor within devolo Home Control.""" @property def device_class(self) -> str: """Return device class.""" return self._device_class @property def state(self): """Return the state of the sensor.""" return self._value @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit class DevoloGenericMultiLevelDeviceEntity(DevoloMultiLevelDeviceEntity): """Representation of a generic multi level sensor within devolo Home Control.""" def __init__( self, homecontrol, device_instance, element_uid, ): """Initialize a devolo multi level sensor.""" self._multi_level_sensor_property = device_instance.multi_level_sensor_property[ element_uid ] super().__init__( homecontrol=homecontrol, device_instance=device_instance, element_uid=element_uid, ) self._device_class = DEVICE_CLASS_MAPPING.get( self._multi_level_sensor_property.sensor_type ) self._value = self._multi_level_sensor_property.value self._unit = self._multi_level_sensor_property.unit if self._device_class is None: self._name += f" {self._multi_level_sensor_property.sensor_type}" if element_uid.startswith("devolo.VoltageMultiLevelSensor:"): self._enabled_default = False class DevoloBatteryEntity(DevoloMultiLevelDeviceEntity): """Representation of a battery entity within devolo Home Control.""" def __init__(self, homecontrol, device_instance, element_uid): """Initialize a battery sensor.""" super().__init__( homecontrol=homecontrol, device_instance=device_instance, element_uid=element_uid, ) self._device_class = DEVICE_CLASS_MAPPING.get("battery") self._value = device_instance.battery_level self._unit = PERCENTAGE class DevoloConsumptionEntity(DevoloMultiLevelDeviceEntity): """Representation of a consumption entity within devolo Home Control.""" def __init__(self, homecontrol, device_instance, element_uid, consumption): """Initialize a devolo consumption sensor.""" super().__init__( homecontrol=homecontrol, device_instance=device_instance, element_uid=element_uid, ) self._sensor_type = consumption self._device_class = DEVICE_CLASS_MAPPING.get(consumption) self._value = getattr( device_instance.consumption_property[element_uid], consumption ) self._unit = getattr( device_instance.consumption_property[element_uid], f"{consumption}_unit" ) self._name += f" {consumption}" @property def unique_id(self): """Return the unique ID of the entity.""" return f"{self._unique_id}_{self._sensor_type}" def _sync(self, message): """Update the consumption sensor state.""" if message[0] == self._unique_id: self._value = getattr( self._device_instance.consumption_property[self._unique_id], self._sensor_type, ) else: self._generic_message(message) self.schedule_update_ha_state()
apache-2.0
kajgan/e2
skin.py
1
32686
from Tools.Profile import profile profile("LOAD:ElementTree") import xml.etree.cElementTree import os profile("LOAD:enigma_skin") from enigma import eSize, ePoint, eRect, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \ addFont, gRGB, eWindowStyleSkinned, getDesktop from Components.config import ConfigSubsection, ConfigText, config, ConfigNothing from Components.Converter.Converter import Converter from Components.Sources.Source import Source, ObsoleteSource from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_FONTS, SCOPE_CURRENT_SKIN, SCOPE_CONFIG, fileExists, SCOPE_SKIN_IMAGE from Tools.Import import my_import from Tools.LoadPixmap import LoadPixmap from Components.RcModel import rc_model from boxbranding import getBoxType colorNames = {} # Predefined fonts, typically used in built-in screens and for components like # the movie list and so. fonts = { "Body": ("Regular", 18, 22, 16), "ChoiceList": ("Regular", 20, 24, 18), } parameters = {} def dump(x, i=0): print " " * i + str(x) try: for n in x.childNodes: dump(n, i + 1) except: None class SkinError(Exception): def __init__(self, message): self.msg = message def __str__(self): return "{%s}: %s. Please contact the skin's author!" % (config.skin.primary_skin.value, self.msg) dom_skins = [ ] def addSkin(name, scope = SCOPE_SKIN): # read the skin if name is None or not len(name): print "[SKIN ERROR] attempt to add a skin without filename" return False filename = resolveFilename(scope, name) if fileExists(filename): mpath = os.path.dirname(filename) + "/" try: dom_skins.append((mpath, xml.etree.cElementTree.parse(filename).getroot())) except: print "[SKIN ERROR] error in %s" % filename return False else: return True return False # get own skin_user_skinname.xml file, if exist def skin_user_skinname(): name = "skin_user_" + config.skin.primary_skin.value[:config.skin.primary_skin.value.rfind('/')] + ".xml" filename = resolveFilename(SCOPE_CONFIG, name) if fileExists(filename): return name return None # we do our best to always select the "right" value # skins are loaded in order of priority: skin with # highest priority is loaded last, usually the user-provided # skin. # currently, loadSingleSkinData (colors, bordersets etc.) # are applied one-after-each, in order of ascending priority. # the dom_skin will keep all screens in descending priority, # so the first screen found will be used. # example: loadSkin("nemesis_greenline/skin.xml") config.skin = ConfigSubsection() DEFAULT_SKIN = "GigabluePax/skin.xml" if not fileExists(resolveFilename(SCOPE_SKIN, DEFAULT_SKIN)): DEFAULT_SKIN = "om-black/skin.xml" if not fileExists(resolveFilename(SCOPE_SKIN, DEFAULT_SKIN)): DEFAULT_SKIN = "adriatic32_turquoise/skin.xml" if not fileExists(resolveFilename(SCOPE_SKIN, DEFAULT_SKIN)): DEFAULT_SKIN = "Vali.HD.flex.MOD.wolv007/skin.xml" config.skin.primary_skin = ConfigText(default=DEFAULT_SKIN) profile("LoadSkin") res = None name = skin_user_skinname() if name: res = addSkin(name, SCOPE_CONFIG) if not name or not res: addSkin('skin_user.xml', SCOPE_CONFIG) # some boxes lie about their dimensions addSkin('skin_box.xml') # add optional discrete second infobar addSkin('skin_second_infobar.xml') # Only one of these is present, compliments of AM_CONDITIONAL if getBoxType() in ('gb800ue', 'gb800ueplus', 'gbultraue', 'gbquad', 'gbquadplus'): config.skin.lcdskin = ConfigText(default = "skin_lcd_default.xml") else: config.skin.lcdskin = ConfigNothing() display_skin_id = 1 if fileExists('/usr/share/enigma2/lcd_skin/skin_lcd_default.xml'): if fileExists(resolveFilename(SCOPE_CONFIG, config.skin.lcdskin.value)): addSkin(config.skin.lcdskin.value, SCOPE_CONFIG) else: addSkin('lcd_skin/' + config.skin.lcdskin.value) addSkin('skin_display.xml') if addSkin('skin_display96.xml'): # Color OLED display_skin_id = 2 addSkin('skin_text.xml') addSkin('skin_subtitles.xml') try: if not addSkin(config.skin.primary_skin.value): raise SkinError, "primary skin not found" except Exception, err: print "SKIN ERROR:", err skin = DEFAULT_SKIN if config.skin.primary_skin.value == skin: skin = 'skin.xml' print "defaulting to standard skin...", skin config.skin.primary_skin.value = skin addSkin(skin) del skin addSkin('skin_default.xml') profile("LoadSkinDefaultDone") def parseCoordinate(s, e, size=0, font=None): s = s.strip() if s == "center": val = (e - size)/2 elif s == '*': return None else: if s[0] is 'e': val = e s = s[1:] elif s[0] is 'c': val = e/2 s = s[1:] else: val = 0; if s: if s[-1] is '%': val += e * int(s[:-1]) / 100 elif s[-1] is 'w': val += fonts[font][3] * int(s[:-1]); elif s[-1] is 'h': val += fonts[font][2] * int(s[:-1]); else: val += int(s) #if val < 0: # Label shadowsOffset # val = 0 # can have a negative value return val def getParentSize(object, desktop): size = eSize() if object: parent = object.getParent() # For some widgets (e.g. ScrollLabel) the skin attributes are applied to # a child widget, instead of to the widget itself. In that case, the parent # we have here is not the real parent, but it is the main widget. # We have to go one level higher to get the actual parent. # We can detect this because the 'parent' will not have a size yet # (the main widget's size will be calculated internally, as soon as the child # widget has parsed the skin attributes) if parent and parent.size().isEmpty(): parent = parent.getParent() if parent: size = parent.size() elif desktop: #widget has no parent, use desktop size instead for relative coordinates size = desktop.size() return size def parsePosition(s, scale, object = None, desktop = None, size = None): x, y = s.split(',') parentsize = eSize() if object and (x[0] in ('c', 'e') or y[0] in ('c', 'e')): parentsize = getParentSize(object, desktop) xval = parseCoordinate(x, parentsize.width(), size and size.width()) yval = parseCoordinate(y, parentsize.height(), size and size.height()) return ePoint(xval * scale[0][0] / scale[0][1], yval * scale[1][0] / scale[1][1]) def parseSize(s, scale, object = None, desktop = None): x, y = s.split(',') parentsize = eSize() if object and (x[0] in ('c', 'e') or y[0] in ('c', 'e')): parentsize = getParentSize(object, desktop) xval = parseCoordinate(x, parentsize.width()) yval = parseCoordinate(y, parentsize.height()) return eSize(xval * scale[0][0] / scale[0][1], yval * scale[1][0] / scale[1][1]) def parseFont(s, scale): try: f = fonts[s] name = f[0] size = f[1] except: name, size = s.split(';') return gFont(name, int(size) * scale[0][0] / scale[0][1]) def parseColor(s): if s[0] != '#': try: return colorNames[s] except: raise SkinError("color '%s' must be #aarrggbb or valid named color" % (s)) return gRGB(int(s[1:], 0x10)) def collectAttributes(skinAttributes, node, context, skin_path_prefix=None, ignore=(), filenames=frozenset(("pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap", "sliderPixmap", "scrollbarbackgroundPixmap"))): # walk all attributes size = None pos = None font = None for attrib, value in node.items(): if attrib not in ignore: if attrib in filenames: value = resolveFilename(SCOPE_CURRENT_SKIN, value, path_prefix=skin_path_prefix) # Bit of a hack this, really. When a window has a flag (e.g. wfNoBorder) # it needs to be set at least before the size is set, in order for the # window dimensions to be calculated correctly in all situations. # If wfNoBorder is applied after the size has been set, the window will fail to clear the title area. # Similar situation for a scrollbar in a listbox; when the scrollbar setting is applied after # the size, a scrollbar will not be shown until the selection moves for the first time if attrib == 'size': size = value.encode("utf-8") elif attrib == 'position': pos = value.encode("utf-8") elif attrib == 'font': font = value.encode("utf-8") skinAttributes.append((attrib, font)) else: skinAttributes.append((attrib, value.encode("utf-8"))) if pos is not None: pos, size = context.parse(pos, size, font) skinAttributes.append(('position', pos)) if size is not None: skinAttributes.append(('size', size)) def morphRcImagePath(value): if rc_model.rcIsDefault() is False: if value == '/usr/share/enigma2/skin_default/rc.png' or value == '/usr/share/enigma2/skin_default/rcold.png': value = rc_model.getRcLocation() + 'rc.png' return value def loadPixmap(path, desktop): option = path.find("#") if option != -1: path = path[:option] ptr = LoadPixmap(morphRcImagePath(path), desktop) if ptr is None: raise SkinError("pixmap file %s not found!" % (path)) return ptr class AttributeParser: def __init__(self, guiObject, desktop, scale=((1,1),(1,1))): self.guiObject = guiObject self.desktop = desktop self.scaleTuple = scale def applyOne(self, attrib, value): try: getattr(self, attrib)(value) except AttributeError: print "[Skin] Attribute not implemented:", attrib, "value:", value except SkinError, ex: print "[Skin] Error:", ex def applyAll(self, attrs): for attrib, value in attrs: self.applyOne(attrib, value) def conditional(self, value): pass def position(self, value): if isinstance(value, tuple): self.guiObject.move(ePoint(*value)) else: self.guiObject.move(parsePosition(value, self.scaleTuple, self.guiObject, self.desktop, self.guiObject.csize())) def size(self, value): if isinstance(value, tuple): self.guiObject.resize(eSize(*value)) else: self.guiObject.resize(parseSize(value, self.scaleTuple, self.guiObject, self.desktop)) def animationMode(self, value): self.guiObject.setAnimationMode( { "disable": 0x00, "off": 0x00, "offshow": 0x10, "offhide": 0x01, "onshow": 0x01, "onhide": 0x10, }[value]) def title(self, value): self.guiObject.setTitle(_(value)) def text(self, value): self.guiObject.setText(_(value)) def font(self, value): self.guiObject.setFont(parseFont(value, self.scaleTuple)) def zPosition(self, value): self.guiObject.setZPosition(int(value)) def itemHeight(self, value): self.guiObject.setItemHeight(int(value)) def pixmap(self, value): ptr = loadPixmap(value, self.desktop) self.guiObject.setPixmap(ptr) def backgroundPixmap(self, value): ptr = loadPixmap(value, self.desktop) self.guiObject.setBackgroundPicture(ptr) def selectionPixmap(self, value): ptr = loadPixmap(value, self.desktop) self.guiObject.setSelectionPicture(ptr) def sliderPixmap(self, value): ptr = loadPixmap(value, self.desktop) self.guiObject.setSliderPicture(ptr) def scrollbarbackgroundPixmap(self, value): ptr = loadPixmap(value, self.desktop) self.guiObject.setScrollbarBackgroundPicture(ptr) def alphatest(self, value): self.guiObject.setAlphatest( { "on": 1, "off": 0, "blend": 2, }[value]) def scale(self, value): self.guiObject.setScale(1) def orientation(self, value): # used by eSlider try: self.guiObject.setOrientation(* { "orVertical": (self.guiObject.orVertical, False), "orTopToBottom": (self.guiObject.orVertical, False), "orBottomToTop": (self.guiObject.orVertical, True), "orHorizontal": (self.guiObject.orHorizontal, False), "orLeftToRight": (self.guiObject.orHorizontal, False), "orRightToLeft": (self.guiObject.orHorizontal, True), }[value]) except KeyError: print "oprientation must be either orVertical or orHorizontal!" def valign(self, value): try: self.guiObject.setVAlign( { "top": self.guiObject.alignTop, "center": self.guiObject.alignCenter, "bottom": self.guiObject.alignBottom }[value]) except KeyError: print "valign must be either top, center or bottom!" def halign(self, value): try: self.guiObject.setHAlign( { "left": self.guiObject.alignLeft, "center": self.guiObject.alignCenter, "right": self.guiObject.alignRight, "block": self.guiObject.alignBlock }[value]) except KeyError: print "halign must be either left, center, right or block!" def textOffset(self, value): x, y = value.split(',') self.guiObject.setTextOffset(ePoint(int(x) * self.scaleTuple[0][0] / self.scaleTuple[0][1], int(y) * self.scaleTuple[1][0] / self.scaleTuple[1][1])) def flags(self, value): flags = value.split(',') for f in flags: try: fv = eWindow.__dict__[f] self.guiObject.setFlag(fv) except KeyError: print "illegal flag %s!" % f def backgroundColor(self, value): self.guiObject.setBackgroundColor(parseColor(value)) def backgroundColorSelected(self, value): self.guiObject.setBackgroundColorSelected(parseColor(value)) def foregroundColor(self, value): self.guiObject.setForegroundColor(parseColor(value)) def foregroundColorSelected(self, value): self.guiObject.setForegroundColorSelected(parseColor(value)) def shadowColor(self, value): self.guiObject.setShadowColor(parseColor(value)) def selectionDisabled(self, value): self.guiObject.setSelectionEnable(0) def transparent(self, value): self.guiObject.setTransparent(int(value)) def borderColor(self, value): self.guiObject.setBorderColor(parseColor(value)) def borderWidth(self, value): self.guiObject.setBorderWidth(int(value)) def scrollbarMode(self, value): self.guiObject.setScrollbarMode(getattr(self.guiObject, value)) # { "showOnDemand": self.guiObject.showOnDemand, # "showAlways": self.guiObject.showAlways, # "showNever": self.guiObject.showNever, # "showLeft": self.guiObject.showLeft # }[value]) def enableWrapAround(self, value): self.guiObject.setWrapAround(True) def itemHeight(self, value): self.guiObject.setItemHeight(int(value)) def pointer(self, value): (name, pos) = value.split(':') pos = parsePosition(pos, self.scaleTuple) ptr = loadPixmap(name, self.desktop) self.guiObject.setPointer(0, ptr, pos) def seek_pointer(self, value): (name, pos) = value.split(':') pos = parsePosition(pos, self.scaleTuple) ptr = loadPixmap(name, self.desktop) self.guiObject.setPointer(1, ptr, pos) def shadowOffset(self, value): self.guiObject.setShadowOffset(parsePosition(value, self.scaleTuple)) def noWrap(self, value): self.guiObject.setNoWrap(1) def applySingleAttribute(guiObject, desktop, attrib, value, scale = ((1,1),(1,1))): # Someone still using applySingleAttribute? AttributeParser(guiObject, desktop, scale).applyOne(attrib, value) def applyAllAttributes(guiObject, desktop, attributes, scale): AttributeParser(guiObject, desktop, scale).applyAll(attributes) def loadSingleSkinData(desktop, skin, path_prefix): """loads skin data like colors, windowstyle etc.""" assert skin.tag == "skin", "root element in skin must be 'skin'!" for c in skin.findall("output"): id = c.attrib.get('id') if id: id = int(id) else: id = 0 if id == 0: # framebuffer for res in c.findall("resolution"): get_attr = res.attrib.get xres = get_attr("xres") if xres: xres = int(xres) else: xres = 720 yres = get_attr("yres") if yres: yres = int(yres) else: yres = 576 bpp = get_attr("bpp") if bpp: bpp = int(bpp) else: bpp = 32 #print "Resolution:", xres,yres,bpp from enigma import gMainDC gMainDC.getInstance().setResolution(xres, yres) desktop.resize(eSize(xres, yres)) if bpp != 32: # load palette (not yet implemented) pass for skininclude in skin.findall("include"): filename = skininclude.attrib.get("filename") if filename: skinfile = resolveFilename(SCOPE_CURRENT_SKIN, filename, path_prefix=path_prefix) if not fileExists(skinfile): skinfile = resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix) if fileExists(skinfile): print "[SKIN] loading include:", skinfile loadSkin(skinfile) for c in skin.findall("colors"): for color in c.findall("color"): get_attr = color.attrib.get name = get_attr("name") color = get_attr("value") if name and color: colorNames[name] = parseColor(color) #print "Color:", name, color else: raise SkinError("need color and name, got %s %s" % (name, color)) for c in skin.findall("fonts"): for font in c.findall("font"): get_attr = font.attrib.get filename = get_attr("filename", "<NONAME>") name = get_attr("name", "Regular") scale = get_attr("scale") if scale: scale = int(scale) else: scale = 100 is_replacement = get_attr("replacement") and True or False render = get_attr("render") if render: render = int(render) else: render = 0 resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix) if not fileExists(resolved_font): #when font is not available look at current skin path skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename) if fileExists(skin_path): resolved_font = skin_path addFont(resolved_font, name, scale, is_replacement, render) #print "Font: ", resolved_font, name, scale, is_replacement for alias in c.findall("alias"): get = alias.attrib.get try: name = get("name") font = get("font") size = int(get("size")) height = int(get("height", size)) # to be calculated some day width = int(get("width", size)) global fonts fonts[name] = (font, size, height, width) except Exception, ex: print "[SKIN] bad font alias", ex for c in skin.findall("parameters"): for parameter in c.findall("parameter"): get = parameter.attrib.get try: name = get("name") value = get("value") parameters[name] = map(int, value.split(",")) except Exception, ex: print "[SKIN] bad parameter", ex for c in skin.findall("subtitles"): from enigma import eWidget, eSubtitleWidget scale = ((1,1),(1,1)) for substyle in c.findall("sub"): get_attr = substyle.attrib.get font = parseFont(get_attr("font"), scale) col = get_attr("foregroundColor") if col: foregroundColor = parseColor(col) haveColor = 1 else: foregroundColor = gRGB(0xFFFFFF) haveColor = 0 col = get_attr("borderColor") if col: borderColor = parseColor(col) else: borderColor = gRGB(0) borderwidth = get_attr("borderWidth") if borderwidth is None: # default: use a subtitle border borderWidth = 3 else: borderWidth = int(borderwidth) face = eSubtitleWidget.__dict__[get_attr("name")] eSubtitleWidget.setFontStyle(face, font, haveColor, foregroundColor, borderColor, borderWidth) for windowstyle in skin.findall("windowstyle"): style = eWindowStyleSkinned() style_id = windowstyle.attrib.get("id") if style_id: style_id = int(style_id) else: style_id = 0 # defaults font = gFont("Regular", 20) offset = eSize(20, 5) for title in windowstyle.findall("title"): get_attr = title.attrib.get offset = parseSize(get_attr("offset"), ((1,1),(1,1))) font = parseFont(get_attr("font"), ((1,1),(1,1))) style.setTitleFont(font); style.setTitleOffset(offset) #print " ", font, offset for borderset in windowstyle.findall("borderset"): bsName = str(borderset.attrib.get("name")) for pixmap in borderset.findall("pixmap"): get_attr = pixmap.attrib.get bpName = get_attr("pos") filename = get_attr("filename") if filename and bpName: png = loadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, filename, path_prefix=path_prefix), desktop) style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png) #print " borderset:", bpName, filename for color in windowstyle.findall("color"): get_attr = color.attrib.get colorType = get_attr("name") color = parseColor(get_attr("color")) try: style.setColor(eWindowStyleSkinned.__dict__["col" + colorType], color) except: raise SkinError("Unknown color %s" % (colorType)) #pass #print " color:", type, color x = eWindowStyleManager.getInstance() x.setStyle(style_id, style) for margin in skin.findall("margin"): style_id = margin.attrib.get("id") if style_id: style_id = int(style_id) else: style_id = 0 r = eRect(0,0,0,0) v = margin.attrib.get("left") if v: r.setLeft(int(v)) v = margin.attrib.get("top") if v: r.setTop(int(v)) v = margin.attrib.get("right") if v: r.setRight(int(v)) v = margin.attrib.get("bottom") if v: r.setBottom(int(v)) # the "desktop" parameter is hardcoded to the UI screen, so we must ask # for the one that this actually applies to. getDesktop(style_id).setMargins(r) dom_screens = {} def loadSkin(name, scope = SCOPE_SKIN): # Now a utility for plugins to add skin data to the screens global dom_screens, display_skin_id filename = resolveFilename(scope, name) if fileExists(filename): path = os.path.dirname(filename) + "/" for elem in xml.etree.cElementTree.parse(filename).getroot(): if elem.tag == 'screen': name = elem.attrib.get('name', None) if name: sid = elem.attrib.get('id', None) if sid and (sid != display_skin_id): # not for this display elem.clear() continue if name in dom_screens: print "loadSkin: Screen already defined elsewhere:", name elem.clear() else: dom_screens[name] = (elem, path) else: elem.clear() else: elem.clear() def loadSkinData(desktop): # Kinda hackish, but this is called once by mytest.py global dom_skins skins = dom_skins[:] skins.reverse() for (path, dom_skin) in skins: loadSingleSkinData(desktop, dom_skin, path) for elem in dom_skin: if elem.tag == 'screen': name = elem.attrib.get('name', None) if name: sid = elem.attrib.get('id', None) if sid and (sid != display_skin_id): # not for this display elem.clear() continue if name in dom_screens: # Kill old versions, save memory dom_screens[name][0].clear() dom_screens[name] = (elem, path) else: # without name, it's useless! elem.clear() else: # non-screen element, no need for it any longer elem.clear() # no longer needed, we know where the screens are now. del dom_skins class additionalWidget: pass # Class that makes a tuple look like something else. Some plugins just assume # that size is a string and try to parse it. This class makes that work. class SizeTuple(tuple): def split(self, *args): return (str(self[0]), str(self[1])) def strip(self, *args): return '%s,%s' % self def __str__(self): return '%s,%s' % self class SkinContext: def __init__(self, parent=None, pos=None, size=None, font=None): if parent is not None: if pos is not None: pos, size = parent.parse(pos, size, font) self.x, self.y = pos self.w, self.h = size else: self.x = None self.y = None self.w = None self.h = None def __str__(self): return "Context (%s,%s)+(%s,%s) " % (self.x, self.y, self.w, self.h) def parse(self, pos, size, font): if pos == "fill": pos = (self.x, self.y) size = (self.w, self.h) self.w = 0 self.h = 0 else: w,h = size.split(',') w = parseCoordinate(w, self.w, 0, font) h = parseCoordinate(h, self.h, 0, font) if pos == "bottom": pos = (self.x, self.y + self.h - h) size = (self.w, h) self.h -= h elif pos == "top": pos = (self.x, self.y) size = (self.w, h) self.h -= h self.y += h elif pos == "left": pos = (self.x, self.y) size = (w, self.h) self.x += w self.w -= w elif pos == "right": pos = (self.x + self.w - w, self.y) size = (w, self.h) self.w -= w else: size = (w, h) pos = pos.split(',') pos = (self.x + parseCoordinate(pos[0], self.w, size[0], font), self.y + parseCoordinate(pos[1], self.h, size[1], font)) return (SizeTuple(pos), SizeTuple(size)) class SkinContextStack(SkinContext): # A context that stacks things instead of aligning them def parse(self, pos, size, font): if pos == "fill": pos = (self.x, self.y) size = (self.w, self.h) else: w,h = size.split(',') w = parseCoordinate(w, self.w, 0, font) h = parseCoordinate(h, self.h, 0, font) if pos == "bottom": pos = (self.x, self.y + self.h - h) size = (self.w, h) elif pos == "top": pos = (self.x, self.y) size = (self.w, h) elif pos == "left": pos = (self.x, self.y) size = (w, self.h) elif pos == "right": pos = (self.x + self.w - w, self.y) size = (w, self.h) else: size = (w, h) pos = pos.split(',') pos = (self.x + parseCoordinate(pos[0], self.w, size[0], font), self.y + parseCoordinate(pos[1], self.h, size[1], font)) return (SizeTuple(pos), SizeTuple(size)) def readSkin(screen, skin, names, desktop): if not isinstance(names, list): names = [names] # try all skins, first existing one have priority global dom_screens for n in names: myscreen, path = dom_screens.get(n, (None,None)) if myscreen is not None: # use this name for debug output name = n break else: name = "<embedded-in-'%s'>" % screen.__class__.__name__ # otherwise try embedded skin if myscreen is None: myscreen = getattr(screen, "parsedSkin", None) # try uncompiled embedded skin if myscreen is None and getattr(screen, "skin", None): skin = screen.skin print "[SKIN] Parsing embedded skin", name if (isinstance(skin, tuple)): for s in skin: candidate = xml.etree.cElementTree.fromstring(s) if candidate.tag == 'screen': sid = candidate.attrib.get('id', None) if (not sid) or (int(sid) == display_skin_id): myscreen = candidate break; else: print "[SKIN] Hey, no suitable screen!" else: myscreen = xml.etree.cElementTree.fromstring(skin) if myscreen: screen.parsedSkin = myscreen if myscreen is None: print "[SKIN] No skin to read..." myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring("<screen></screen>") screen.skinAttributes = [ ] skin_path_prefix = getattr(screen, "skin_path", path) context = SkinContextStack() s = desktop.bounds() context.x = s.left() context.y = s.top() context.w = s.width() context.h = s.height() del s collectAttributes(screen.skinAttributes, myscreen, context, skin_path_prefix, ignore=("name",)) context = SkinContext(context, myscreen.attrib.get('position'), myscreen.attrib.get('size')) screen.additionalWidgets = [ ] screen.renderer = [ ] visited_components = set() # now walk all widgets and stuff def process_none(widget, context): pass def process_widget(widget, context): get_attr = widget.attrib.get # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped # widgets (source->renderer). wname = get_attr('name') wsource = get_attr('source') if wname is None and wsource is None: print "widget has no name and no source!" return if wname: #print "Widget name=", wname visited_components.add(wname) # get corresponding 'gui' object try: attributes = screen[wname].skinAttributes = [ ] except: raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!") # assert screen[wname] is not Source collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('name',)) elif wsource: # get corresponding source #print "Widget source=", wsource while True: # until we found a non-obsolete source # parse our current "wsource", which might specifiy a "related screen" before the dot, # for example to reference a parent, global or session-global screen. scr = screen # resolve all path components path = wsource.split('.') while len(path) > 1: scr = screen.getRelatedScreen(path[0]) if scr is None: #print wsource #print name raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!") path = path[1:] # resolve the source. source = scr.get(path[0]) if isinstance(source, ObsoleteSource): # however, if we found an "obsolete source", issue warning, and resolve the real source. print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source) print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date) if source.description: print source.description wsource = source.new_source else: # otherwise, use that source. break if source is None: raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!") wrender = get_attr('render') if not wrender: raise SkinError("you must define a renderer with render= for source '%s'" % (wsource)) for converter in widget.findall("convert"): ctype = converter.get('type') assert ctype, "'convert'-tag needs a 'type'-attribute" #print "Converter:", ctype try: parms = converter.text.strip() except: parms = "" #print "Params:", parms converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype) c = None for i in source.downstream_elements: if isinstance(i, converter_class) and i.converter_arguments == parms: c = i if c is None: c = converter_class(parms) c.connect(source) source = c renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender) renderer = renderer_class() # instantiate renderer renderer.connect(source) # connect to source attributes = renderer.skinAttributes = [ ] collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('render', 'source')) screen.renderer.append(renderer) def process_applet(widget, context): try: codeText = widget.text.strip() widgetType = widget.attrib.get('type') code = compile(codeText, "skin applet", "exec") except Exception, ex: raise SkinError("applet failed to compile: " + str(ex)) if widgetType == "onLayoutFinish": screen.onLayoutFinish.append(code) else: raise SkinError("applet type '%s' unknown!" % widgetType) def process_elabel(widget, context): w = additionalWidget() w.widget = eLabel w.skinAttributes = [ ] collectAttributes(w.skinAttributes, widget, context, skin_path_prefix, ignore=('name',)) screen.additionalWidgets.append(w) def process_epixmap(widget, context): w = additionalWidget() w.widget = ePixmap w.skinAttributes = [ ] collectAttributes(w.skinAttributes, widget, context, skin_path_prefix, ignore=('name',)) screen.additionalWidgets.append(w) def process_screen(widget, context): for w in widget.getchildren(): conditional = w.attrib.get('conditional') if conditional and not [i for i in conditional.split(",") if i in screen.keys()]: continue p = processors.get(w.tag, process_none) try: p(w, context) except SkinError, e: print "[Skin] SKIN ERROR in screen '%s' widget '%s':" % (name, w.tag), e def process_panel(widget, context): n = widget.attrib.get('name') if n: try: s = dom_screens[n] except KeyError: print "[SKIN] Unable to find screen '%s' referred in screen '%s'" % (n, name) else: process_screen(s[0], context) layout = widget.attrib.get('layout') if layout == 'stack': cc = SkinContextStack else: cc = SkinContext try: c = cc(context, widget.attrib.get('position'), widget.attrib.get('size'), widget.attrib.get('font')) except Exception, ex: raise SkinError("Failed to create skincontext (%s,%s,%s) in %s: %s" % (widget.attrib.get('position'), widget.attrib.get('size'), widget.attrib.get('font'), context, ex) ) process_screen(widget, c) processors = { None: process_none, "widget": process_widget, "applet": process_applet, "eLabel": process_elabel, "ePixmap": process_epixmap, "panel": process_panel } try: context.x = 0 # reset offsets, all components are relative to screen context.y = 0 # coordinates. process_screen(myscreen, context) except Exception, e: print "[Skin] SKIN ERROR in %s:" % name, e from Components.GUIComponent import GUIComponent nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)] assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components)) # This may look pointless, but it unbinds 'screen' from the nested scope. A better # solution is to avoid the nested scope above and use the context object to pass # things around. screen = None visited_components = None
gpl-2.0
giocalitri/django-guardian
guardian/testapp/tests/core_test.py
17
7473
from __future__ import unicode_literals from itertools import chain from django.conf import settings # Try the new app settings (Django 1.7) and fall back to the old system try: from django.apps import apps as django_apps auth_app = django_apps.get_app_config("auth") except ImportError: from django.contrib.auth import models as auth_app from django.contrib.auth.models import Group, Permission, AnonymousUser from django.contrib.contenttypes.models import ContentType from django.test import TestCase from guardian.core import ObjectPermissionChecker from guardian.compat import get_user_model, create_permissions from guardian.exceptions import NotUserNorGroup from guardian.models import UserObjectPermission, GroupObjectPermission from guardian.shortcuts import assign_perm User = get_user_model() class ObjectPermissionTestCase(TestCase): def setUp(self): self.group, created = Group.objects.get_or_create(name='jackGroup') self.user, created = User.objects.get_or_create(username='jack') self.user.groups.add(self.group) self.ctype = ContentType.objects.create(name='foo', model='bar', app_label='fake-for-guardian-tests') try: self.anonymous_user = User.objects.get(pk=settings.ANONYMOUS_USER_ID) except User.DoesNotExist: self.anonymous_user = User( id=settings.ANONYMOUS_USER_ID, username='AnonymousUser', ) self.anonymous_user.save() class ObjectPermissionCheckerTest(ObjectPermissionTestCase): def setUp(self): super(ObjectPermissionCheckerTest, self).setUp() # Required if MySQL backend is used :/ create_permissions(auth_app, [], 1) def test_cache_for_queries_count(self): settings.DEBUG = True try: from django.db import connection ContentType.objects.clear_cache() checker = ObjectPermissionChecker(self.user) # has_perm on Checker should spawn only two queries plus one extra # for fetching the content type first time we check for specific # model and two more content types as there are additional checks # at get_user_obj_perms_model and get_group_obj_perms_model query_count = len(connection.queries) res = checker.has_perm("change_group", self.group) if 'guardian.testapp' in settings.INSTALLED_APPS: expected = 5 else: # TODO: This is strange, need to investigate; totally not sure # why there are more queries if testapp is not included expected = 11 self.assertEqual(len(connection.queries), query_count + expected) # Checking again shouldn't spawn any queries query_count = len(connection.queries) res_new = checker.has_perm("change_group", self.group) self.assertEqual(res, res_new) self.assertEqual(len(connection.queries), query_count) # Checking for other permission but for Group object again # shouldn't spawn any query too query_count = len(connection.queries) checker.has_perm("delete_group", self.group) self.assertEqual(len(connection.queries), query_count) # Checking for same model but other instance should spawn 2 queries new_group = Group.objects.create(name='new-group') query_count = len(connection.queries) checker.has_perm("change_group", new_group) self.assertEqual(len(connection.queries), query_count + 2) # Checking for permission for other model should spawn 3 queries # (again: content type and actual permissions for the object... query_count = len(connection.queries) checker.has_perm("change_user", self.user) self.assertEqual(len(connection.queries), query_count + 3) finally: settings.DEBUG = False def test_init(self): self.assertRaises(NotUserNorGroup, ObjectPermissionChecker, user_or_group=ContentType()) self.assertRaises(NotUserNorGroup, ObjectPermissionChecker) def test_anonymous_user(self): user = AnonymousUser() check = ObjectPermissionChecker(user) # assert anonymous user has no object permissions at all for obj self.assertTrue( [] == list(check.get_perms(self.ctype)) ) def test_superuser(self): user = User.objects.create(username='superuser', is_superuser=True) check = ObjectPermissionChecker(user) ctype = ContentType.objects.get_for_model(self.ctype) perms = sorted(chain(*Permission.objects .filter(content_type=ctype) .values_list('codename'))) self.assertEqual(perms, check.get_perms(self.ctype)) for perm in perms: self.assertTrue(check.has_perm(perm, self.ctype)) def test_not_active_superuser(self): user = User.objects.create(username='not_active_superuser', is_superuser=True, is_active=False) check = ObjectPermissionChecker(user) ctype = ContentType.objects.get_for_model(self.ctype) perms = sorted(chain(*Permission.objects .filter(content_type=ctype) .values_list('codename'))) self.assertEqual(check.get_perms(self.ctype), []) for perm in perms: self.assertFalse(check.has_perm(perm, self.ctype)) def test_not_active_user(self): user = User.objects.create(username='notactive') assign_perm("change_contenttype", user, self.ctype) # new ObjectPermissionChecker is created for each User.has_perm call self.assertTrue(user.has_perm("change_contenttype", self.ctype)) user.is_active = False self.assertFalse(user.has_perm("change_contenttype", self.ctype)) # use on one checker only (as user's is_active attr should be checked # before try to use cache user = User.objects.create(username='notactive-cache') assign_perm("change_contenttype", user, self.ctype) check = ObjectPermissionChecker(user) self.assertTrue(check.has_perm("change_contenttype", self.ctype)) user.is_active = False self.assertFalse(check.has_perm("change_contenttype", self.ctype)) def test_get_perms(self): group = Group.objects.create(name='group') obj1 = ContentType.objects.create(name='ct1', model='foo', app_label='guardian-tests') obj2 = ContentType.objects.create(name='ct2', model='bar', app_label='guardian-tests') assign_perms = { group: ('change_group', 'delete_group'), obj1: ('change_contenttype', 'delete_contenttype'), obj2: ('delete_contenttype',), } check = ObjectPermissionChecker(self.user) for obj, perms in assign_perms.items(): for perm in perms: UserObjectPermission.objects.assign_perm(perm, self.user, obj) self.assertEqual(sorted(perms), sorted(check.get_perms(obj))) check = ObjectPermissionChecker(self.group) for obj, perms in assign_perms.items(): for perm in perms: GroupObjectPermission.objects.assign_perm(perm, self.group, obj) self.assertEqual(sorted(perms), sorted(check.get_perms(obj)))
bsd-2-clause
aringh/odl
odl/contrib/tomo/examples/elekta_xvi_fbp.py
3
1235
"""Example of using the Elekta XVI geometry. In this example we create an Elekta XVI geometry and use it to create some artificial data and reconstruct it using filtered backprojection. Note that this is a 3d dataset and requires some memory to run. """ import odl from odl.contrib import tomo # Get default geometry and space geometry = tomo.elekta_xvi_geometry() space = tomo.elekta_xvi_space(shape=(112, 112, 112)) # Create ray transform ray_transform = odl.tomo.RayTransform(space, geometry, use_cache=False) # Get default FDK reconstruction operator recon_op = tomo.elekta_xvi_fbp(ray_transform) # Create simplified phantom phantom = odl.phantom.shepp_logan(space, modified=True) # Create artificial data projections = ray_transform(phantom) # Reconstruct the artificial data reconstruction = recon_op(projections) # Display the results phantom.show('phantom xz', coords=[None, 0, None]) reconstruction.show('reconstruction xz', coords=[None, 0, None]) phantom.show('phantom xy', coords=[None, None, 0]) reconstruction.show('reconstruction xy', coords=[None, None, 0]) phantom.show('phantom yz', coords=[0, None, None]) reconstruction.show('reconstruction yz', coords=[0, None, None]) projections.show('projections')
mpl-2.0
bmillham/djrq
DJRQ/djrq/controllers/admin/upload/forms/privateform.py
1
1305
import djrq.middleware import web from djrq.model import * from web.auth import authorize #from ...account import AccountMixIn class PrivateForm(web.core.HTTPMethod): def __before__(self, *args, **kw): options = session.query(SiteOptions).one() kw['options'] = options kw['catalogs'] = session.query(Catalog) return super(PrivateForm, self).__before__(*args, **kw) def __after__(self, result, *args, **kw): kw.update(result) return super(PrivateForm, self).__after__(('djrq.templates.admin.upload.forms.privateform', kw)) @authorize(web.auth.authenticated) def get(self, *args, **kw): return dict(status=None) @authorize(web.auth.authenticated) def post(self, *args, **kw): result = dict(status=None) if 'cat_group' in kw: cg = kw['cat_group'] if type(cg) is not list: cg = [cg] cats = ",".join(cg) if kw['selected_catalogs'] == cg: result['status'] = "[No changes]" else: kw['selected_catalogs'] = cg kw['options'].catalog = cats session.commit() result['status'] = '[Updated]' result['selected_catalogs'] = cg return result
gpl-2.0
Cibiv/Teaser
lib/server.py
1
39115
#!/usr/bin/env python import tornado.ioloop import tornado.web import tornado.wsgi import tornado.options import yaml import sys from lib import util from lib import page Page = page.Page class Home(tornado.web.RequestHandler): def get(self): instance.pollJobs() page = Page() page.setFooter("Copyright &copy; 2015, CIBIV.") page.addSection("Home", """ <div class="jumbotron" style="border-radius:10px;"> <div class="container"> <h1>Teaser</h1> <p>A tool for fast personalized benchmarks and optimization of NGS read mapping.</p> <p><a href="define" class="btn btn-success" role="button"><span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> Start a mapper benchmark now</a> <a href="static/dataset_gallery" class="btn btn-info" role="button">View Example Report</a> <a href="http://github.com/cibiv/teaser/" class="btn btn-info" role="button">Wiki and Download</a></p> </div> </div> <div class="container-fluid"> <div class="row-fluid" align="center"> <div class="col-md-3"><h2>Find</h2> <p>...a suitable mapper for your next-gen sequencing data in minutes</p></div> <div class="col-md-3"><h2>Identify</h2> <p>...the right mapping quality thresholds for filtering</p></div> <div class="col-md-3"><h2>Optimize</h2> <p>...mapper parameters for accuracy or throughput</p></div> <div class="col-md-3"><h2>Compare</h2> <p>...simulation and real data results</p></div> </div> </div> <br> """, "", "", False) page.addStyle(""" div.featurebox { padding:10px; background-color:#CCCCCC; margin-left:10px; margin-right:10px; margin-top:10px; margin-bottom:10px; border:solid 1px black; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } """) page.addNav([{"title": "View on GitHub", "link": "https://github.com/Cibiv/Teaser"}]) page.addNav([{"title": "Wiki", "link": "https://github.com/Cibiv/Teaser/wiki"}]) page.addNav([{"title": "|", "link": "#"}]) page.addNav([{"title": "CIBIV", "link": "http://www.cibiv.at"}]) page.addNav([{"title": "CSHL", "link": "http://www.cshl.edu"}]) page.enableNavSeparators(False) page.enableSidebar(False) recent_html = "" recent_configs = [] for rid in os.listdir("reports"): if not os.path.isdir("reports/%s" % rid): continue report_config_filename = "reports/%s/config.yaml" % rid try: report_config = yaml.load(open(report_config_filename, "r")) recent_configs.append(report_config) except Exception as e: #print("Failed to load report config from %s: %s"%(report_config_filename,str(e))) pass max_i = 10 i = 0 for config_ in sorted(recent_configs, key=lambda k: k["meta_timestamp"], reverse=True): test_name = list(config_["teaser"]["tests"].keys())[0] test_config = config_["teaser"]["tests"][test_name] reference_name, reference_ext = os.path.splitext(test_config["reference"]) if not "type" in test_config or test_config["type"] == "simulated_teaser": recent_html += "<tr><td><a href=\"reports/%s\">%s</a></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % (test_name, test_name, reference_name, datetime.datetime.fromtimestamp(int(config_["meta_timestamp"])).strftime('%Y-%m-%d %H:%M:%S'), str(test_config["platform"]), "paired-end" if test_config["paired"] else "single-end", str(test_config["read_length"])) else: recent_html += "<tr><td><a href=\"reports/%s\">%s</a></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % (test_name, test_name, reference_name, datetime.datetime.fromtimestamp(int(config_["meta_timestamp"])).strftime('%Y-%m-%d %H:%M:%S'), "Unknown", "paired-end" if test_config["paired"] else "single-end", "Unknown") i += 1 if i >= max_i: break if i==0: recent_html = "<tr><td colspan=6><i>No benchmarks were performed yet.</i></td></tr>" page.addSection("Summary", "Teaser analyzes the performance of read mappers based on a data set provided by you. After you enter key characteristics such as read length and reference genome, Teaser will simulate read data including the gold standard alignment. After the simulation, Teaser automatically runs and evaluates each mapper for the selected parameters and summarizes the results in a report. Teaser also supports benchmarking mappers on real data or custom simulations, as well as testing new mappers and custom parameter sets. You can start using Teaser right now using this web application, or download and install it to unlock all advanced features.<br><br><b>If you use Teaser to optimize read mapping in your study, please cite:</b> Smolka M, Rescheneder P, Schatz MC, von Haeseler A and Sedlazeck FJ. Teaser: Individualized benchmarking and optimization of read mapping results for NGS data. Genome Biology 2015, 16:235 (22 October 2015). DOI: 10.1186/s13059-015-0803-1") if config["teaser"]["server"]["news"] != "": page.addSection("Update News", config["teaser"]["server"]["news"]) page.addSection("Recent Benchmarks", """ <div class="table-responsive"><table class=table table-striped"> <thead> <tr> <th>Teaser Accession</th> <th>Organism</th> <th>Date</th> <th>Platform</th> <th>Library</th> <th>Read Length</th> </tr> </thead> <tbody> %s </tbody> </table> </div> """ % recent_html) if config["teaser"]["server"]["send_usage_information"]: page.addScript(""" (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-66386566-1', 'auto'); ga('send', 'pageview');""") self.write(page.html()) class DefineJob(tornado.web.RequestHandler): def makeButton(self, type, selected_type, link): if not type in config["teaser"]["server"]["allowed_types"]: return "<br><i>Please download Teaser to use this option</i>" if type == selected_type: return """<a href="#" class="btn btn-default" role="button" disabled>Selected</a>""" else: return """<a href="%s" class="btn btn-info" role="button">Choose</a>""" % link def getReferenceOptions(self): reference_extensions = [".fa", ".fasta", ".fas"] reference_ignore = ".sampled" reference_files = [] for file in os.listdir(config["teaser"]["reference_directory"]): name, ext = os.path.splitext(file) if ext in reference_extensions and not reference_ignore in file: reference_files.append((file, name)) return ["<option value=\"%s\"%s>%s</option>" % (filename, (" selected" if "D_melanogaster" in filename else ""), title) for filename, title in reference_files] def getFileOptions(self, file_extensions=[".fastq", ".fq"]): files = [] for file in os.listdir(config["teaser"]["import_directory"]): name, ext = os.path.splitext(file) if ext in file_extensions: files.append(file) return ["<option value=\"%s\">%s</option>" % (filename, filename) for filename in files] def addSectionDataSource(self, page, type=""): button_teaser = self.makeButton("simulated_teaser", type, "/define") button_custom = self.makeButton("simulated_custom", type, "/define-custom") button_real = self.makeButton("real", type, "/define-real") page.addSection("Choose Data Source", """ To begin, choose the source of the NGS read data that mappers should be benchmarked for.<br><hr> <div class="container-fluid"> <div class="row-fluid" align="center"> <div class="col-md-4" style="border-right:2px solid grey;"><h3>New Simulation</h3> <p style="height:75px;"> Use Teaser to quickly define a simulated data set and benchmark mappers on it.</p><p>%s</p></div> <div class="col-md-4" style="border-right:2px solid grey;"><h3>Existing Simulation</h2> <p style="height:75px;"> Provide a custom set of reads and gold standard alignment for benchmarking mappers.</p><p>%s</p></div> <div class="col-md-4"><h3>Real Data</h3> <p style="height:75px;"> Provide real read data to benchmark mapped percentages and throughput of mappers.</p><p>%s</p></div> </div> </div> <form method="post" role="form" action="submitjob" class="form-horizontal" name="mainForm" id="mainForm"> <input type="hidden" name="type" value="%s">""" % (button_teaser, button_custom, button_real, type), """<div class="form-group"><a href="../" class="btn btn-warning" role="button">Cancel</a> <a href="#section2" class="btn btn-info" role="button">Next</a></div>""") def addSectionHaplotype(self, page): page.addSection("Data: Haplotype", """ This section covers key properties related to the organism that is the target of sequencing. If you do not find your desired reference sequence in the list, please download and place the uncompressed FASTA file in the <i>Teaser/references</i> directory.<br><hr> <div class="form-horizontal"> <div class="form-group"> <label for="reference" class="col-sm-2 control-label">Reference Genome</label> <div class="col-sm-4"> <select id="reference" class="form-control" name="reference"> """ + "\n".join(self.getReferenceOptions()) + """ </select> </div> </div> <div class="form-group"> <label for="mutation_rate" class="col-sm-2 control-label">Mutation Rate</label> <div class="col-sm-2"> <input type="number" class="form-control" id="mutation_rate" name="mutation_rate" min="0" max="0.5" value="0.001" step="0.001"> </div> </div> <div class="form-group"> <label for="mutation_indel_frac" class="col-sm-2 control-label">Mutation Indel Fraction</label> <div class="col-sm-2"> <input type="number" class="form-control" id="mutation_indel_frac" name="mutation_indel_frac" min="0" max="1" value="0.3" step="0.001"> </div> </div> <div class="form-group"> <label for="mutation_indel_avg_len" class="col-sm-2 control-label">Mutation Indel Avg. Length</label> <div class="col-sm-2"> <input type="number" class="form-control" id="mutation_indel_avg_len" name="mutation_indel_avg_len" min="0" max="1000" value="1" step="1"> </div> </div> </div> """, """<div class="form-group"> <a href="#section1" class="btn btn-info" role="button">Back</a> <a href="#section3" class="btn btn-info" role="button">Next</a> </div>""") def addSectionSequencing(self, page): page.addSection("Data: Sequencing", """ This section covers properties related to basic library preparation and sequencing.<br><hr> <div class="form-horizontal"> <div class="form-group"> <label for="platform" class="col-sm-2 control-label">Sequencing Platform</label> <div class="col-sm-4"> <select id="platform" name="platform" class="form-control"> <option value="illumina">Illumina</option> <option value="454">454</option> <option value="ion_torrent">Ion Torrent</option> </select> </div> </div> <div class="form-group"> <label for="read_length" class="col-sm-2 control-label">Read Length</label> <div class="col-sm-2"> <input type="number" class="form-control" id="read_length" name="read_length" size="1" min="22" max="10000" step="1" value="60"> </div> </div> <div class="form-group"> <label for="error_rate_mult" class="col-sm-2 control-label">Sequencing Error Multiplier</label> <div class="col-sm-2"> <input type="number" class="form-control" id="error_rate_mult" name="error_rate_mult" min="0" max="1000" step="0.01" value="1"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"> Library Type </label> <div class="radio"> <label> <input type="radio" name="paired" id="optionsRadios1" value="false" onClick="javascript:$('#insert_size').prop('disabled',true); $('#insert_size_error').prop('disabled',true);" checked> Single-End </label> <label> <input type="radio" name="paired" id="optionsRadios2" value="true" onClick="javascript:$('#insert_size').prop('disabled',false); $('#insert_size_error').prop('disabled',false);"> Paired-End </label> </div> </div> <div class="form-group"> <label for="insert_size" class="col-sm-2 control-label">Insert Size</label> <div class="col-sm-2"> <input type="number" class="form-control" id="insert_size" name="insert_size" min="0" max="1000" step="1" value="100" disabled> </div> </div> <div class="form-group"> <label for="insert_size_error" class="col-sm-2 control-label">Insert Size Error</label> <div class="col-sm-2"> <input type="number" class="form-control" id="insert_size_error" name="insert_size_error" min="0" max="1000" step="1" value="50" disabled> </div> </div> </div> """, """<div class="form-group"> <a href="#section2" class="btn btn-info" role="button">Back</a> <a href="#section4" class="btn btn-info" role="button">Next</a> </div>""") def addSectionEvaluation(self, page): mapper_options = "" mappers_missing_binaries=[] for mapper_id in sorted(config["mappers"]): if "title" in config["mappers"][mapper_id]: mapper_title = config["mappers"][mapper_id]["title"] else: mapper_title = mapper_id if isinstance(config["mappers"][mapper_id]["bin"], basestring): if not os.path.exists(config["mappers"][mapper_id]["bin"]): mappers_missing_binaries.append((mapper_title,config["mappers"][mapper_id]["bin"])) continue else: missing=False for path in config["mappers"][mapper_id]["bin"]: if not os.path.exists(path): mappers_missing_binaries.append((mapper_title,path)) missing=True break if missing: continue mapper_options += """<optgroup label="%s">""" % mapper_title selected = "selected" if mapper_id in ["bowtie2","ngm","bwamem","bwasw","bwa"] else "" mapper_options += """<option value="m%s" %s>%s - Default</option>""" % (mapper_id, selected, mapper_title) if "parameters" in config: for parameter_id in sorted(config["parameters"]): if config["parameters"][parameter_id]["mapper"] != mapper_id: continue if "title" in config["parameters"][parameter_id]: param_title = config["parameters"][parameter_id]["title"] else: param_title = parameter_id mapper_options += """<option value="p%s">%s - %s</option>""" % (parameter_id, mapper_title, param_title) mapper_options += """</optgroup>""" missing_binaries_str="" if len(mappers_missing_binaries): missing_binaries_str="""<hr><small><b><span class="glyphicon glyphicon-warning-sign" aria-hidden="true"></span> No executable files were found for the following mappers:</b>""" for mapper,bin in mappers_missing_binaries: missing_binaries_str+="<br>%s: Need '%s'"%(mapper,bin) missing_binaries_str+="</small>" page.addSection("Evaluation", """ Finally, select the mappers and parameter ensembles that should be evaluated. Community-created parameter sets are available for download at: <a href="https://github.com/Cibiv/Teaser">https://github.com/Cibiv/Teaser</a>. <br><hr> <div class="form-horizontal"> <div class="form-group"> <label for="mappers" class="col-sm-2 control-label">Mappers and Parameters</label> <div class="col-sm-4"> <select class="selectpicker" name="mappers" id="mappers" data-width="100%" multiple> """ + mapper_options + """ </select> </div> </div> <div class="form-group"> <label for="evaluator" class="col-sm-2 control-label">Alignment Evaluation Method</label> <div class="col-sm-4"> <select id="evaluator" class="form-control" name="evaluator"> <option value="1" selected>Position-based using gold standard</option> </select> </div> </div> <div class="form-group"> <label for="pos_threshold" class="col-sm-2 control-label">Position threshold (bp)</label> <div class="col-sm-4"> <select id="pos_threshold" class="form-control" name="pos_threshold"> <option value="-1" selected>Default (50% of read length)</option> <option>0</option> <option>5</option> <option>25</option> <option>50</option> <option>200</option> <option>500</option> <option>1000</option> </select> </div> </div> """+ missing_binaries_str + """ </div> """, """<div class="form-group"> <a href="#section3" class="btn btn-info" role="button">Back</a> <button type="submit" class="btn btn-primary" id="submitButton" name="submitButton">Run Teaser</button> <a href="#section5" class="btn btn-info" role="button">Advanced Options</a> </div>""") page.addScript("""window.onload = function () {$('.selectpicker').selectpicker();}""") def addSectionAdvanced(self, page): page.addSection("Advanced", """ The options below allow adjusting the resources used for evaluation and other advanced options. Please note that for large, i.e. complex mammalian, genomes simulation and mapping may require up to 16GB of memory.<br><hr> <div class="form-horizontal"> <div class="form-group"> <label for="threads" class="col-sm-2 control-label">Number of CPU cores to use</label> <div class="col-sm-2"> <input type="number" class="form-control" id="threads" name="threads" min="1" max="%d" value="%d" step="1"> </div> </div> <div class="form-group"> <label for="sub_max_memory" class="col-sm-2 control-label">Max. Mapper Memory Usage (MB)</label> <div class="col-sm-2"> <input type="number" class="form-control" id="sub_max_memory" name="sub_max_memory" min="1" max="%d" value="%d" step="1"> </div> </div> <div class="form-group"> <label for="sub_max_runtime" class="col-sm-2 control-label">Max. Mapper Runtime (s)</label> <div class="col-sm-2"> <input type="number" class="form-control" id="sub_max_memory" name="sub_max_runtime" min="60" max="%d" value="%d" step="1"> </div> </div> <div class="form-group"> <label for="simulator" class="col-sm-2 control-label">Simulator</label> <div class="col-sm-4"> <select id="simulator" class="form-control" name="simulator"> <option value="none">Choose Automatically</option> <option value="mason">Mason (Illumina,454)</option> <option value="dwgsim">DWGSIM (Illumina,454,Ion Torrent)</option> </select> </div> </div> <div class="form-group"> <label for="coverage" class="col-sm-2 control-label">Read Count Multiplier</label> <div class="col-sm-2"> <input type="number" class="form-control" id="coverage" name="coverage" size="1" min="0.1" max="5" step="0.1" value="1"> </div> </div> </div> """ % (config["teaser"]["server"]["max_threads"], config["teaser"]["server"]["default_threads"], config["teaser"]["server"]["max_memory"], config["teaser"]["server"]["default_memory"], config["teaser"]["server"]["max_runtime"], config["teaser"]["server"]["default_runtime"]), """<div class="form-group"> <a href="#section4" class="btn btn-info" role="button">Back</a> <button type="submit" class="btn btn-primary" id="submitButton" name="submitButton">Run Teaser</button> </div></form>""") class DefineJobTeaser(DefineJob): def get(self): page = Page() page.enableFullscreenSections() self.addSectionDataSource(page, "simulated_teaser") self.addSectionHaplotype(page) self.addSectionSequencing(page) self.addSectionEvaluation(page) self.addSectionAdvanced(page) page.setNavRight("""<a href="/" class="btn btn-warning" role="button">Back to Teaser Home</a>""") self.write(page.html()) class DefineJobCustom(DefineJob): def addSectionSelectData(self, page): page.addSection("Import Data Set", """ Teaser supports reads in FASTQ format and gold standard alignments in SAM format. First, place your data files in the <i>Teaser/import</i> directory. After refreshing this page, you will be able to select the files to import below. If you do not find your desired reference sequence in the list, please download and place the uncompressed FASTA file in the <i>Teaser/references</i> directory.<br><hr> <div class="form-horizontal"> <div class="form-group"> <label for="reference" class="col-sm-2 control-label">Reference Genome</label> <div class="col-sm-4"> <select id="reference" class="form-control" name="reference"> """ + "\n".join(self.getReferenceOptions()) + """ </select> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"> Library Type </label> <div class="radio"> <label> <input type="radio" name="paired" id="optionsRadios1" value="false" onClick="javascript:$('#reads2').prop('disabled',true);" checked> Single-End </label> <label> <input type="radio" name="paired" id="optionsRadios2" value="true" onClick="javascript:$('#reads2').prop('disabled',false);"> Paired-End </label> </div> </div> <div class="form-group"> <label for="reads1" class="col-sm-2 control-label">Simulated Reads File (1)</label> <div class="col-sm-4"> <select id="reads1" class="form-control" name="reads1"> """ + "\n".join(self.getFileOptions()) + """ </select> </div> </div> <div class="form-group"> <label for="reads2" class="col-sm-2 control-label">Simulated Reads File (2)</label> <div class="col-sm-4"> <select id="reads2" class="form-control" name="reads2" disabled> """ + "\n".join(self.getFileOptions()) + """ </select> </div> </div> <div class="form-group"> <label for="gold_standard" class="col-sm-2 control-label">Gold Standard Alignment File</label> <div class="col-sm-4"> <select id="gold_standard" class="form-control" name="gold_standard"> """ + "\n".join(self.getFileOptions([".sam"])) + """ </select> </div> </div> </div> """, """<div class="form-group"> <a href="#section1" class="btn btn-info" role="button">Back</a> <a href="#section3" class="btn btn-info" role="button">Next</a> </div>""") def get(self): page = Page() page.enableFullscreenSections() self.addSectionDataSource(page, "simulated_custom") self.addSectionSelectData(page) self.addSectionEvaluation(page) self.addSectionAdvanced(page) page.setNavRight("""<a href="/" class="btn btn-warning" role="button">Back to Teaser Home</a>""") self.write(page.html()) class DefineJobReal(DefineJob): def addSectionEvaluation(self, page): mapper_options = "" for mapper_id in sorted(config["mappers"]): if "title" in config["mappers"][mapper_id]: mapper_title = config["mappers"][mapper_id]["title"] else: mapper_title = mapper_id mapper_options += """<optgroup label="%s">""" % mapper_title mapper_options += """<option value="m%s" selected>%s - Default</option>""" % (mapper_id, mapper_title) if "parameters" in config: for parameter_id in sorted(config["parameters"]): if config["parameters"][parameter_id]["mapper"] != mapper_id: continue if "title" in config["parameters"][parameter_id]: param_title = config["parameters"][parameter_id]["title"] else: param_title = parameter_id mapper_options += """<option value="p%s">%s - %s</option>""" % (parameter_id, mapper_title, param_title) mapper_options += """</optgroup>""" page.addSection("Evaluation", """ Finally, select the mappers and parameter sets that should be evaluated. Community-created parameter sets are available for download at: <a href="https://github.com/Cibiv/Teaser">https://github.com/Cibiv/Teaser</a>. <br><hr> <div class="form-horizontal"> <div class="form-group"> <label for="mappers" class="col-sm-2 control-label">Mappers and Parameter Settings</label> <div class="col-sm-4"> <select class="selectpicker" name="mappers" id="mappers" data-width="100%" multiple> """ + mapper_options + """ </select> </div> </div> <div class="form-group"> <label for="evaluator" class="col-sm-2 control-label">Alignment Evaluation Method</label> <div class="col-sm-4"> <select id="evaluator" class="form-control" name="evaluator"> <option value="1" selected>Basic</option> </select> </div> </div> </div> """, """<div class="form-group"> <a href="#section2" class="btn btn-info" role="button">Back</a> <button type="submit" class="btn btn-primary" id="submitButton" name="submitButton">Run Teaser</button> <a href="#section4" class="btn btn-info" role="button">Advanced Options</a> </div>""") page.addScript("""window.onload = function () {$('.selectpicker').selectpicker();}""") def addSectionSelectData(self, page): page.addSection("Import Data Set", """ Teaser supports reads in FASTQ format. First, place your data files in the <i>Teaser/import</i> directory. After refreshing this page, you will be able to select the files to import below. If you do not find your desired reference sequence in the list, please download and place the uncompressed FASTA file in the <i>Teaser/references</i> directory.<br><hr> <div class="form-horizontal"> <div class="form-group"> <label for="reference" class="col-sm-2 control-label">Reference Genome</label> <div class="col-sm-4"> <select id="reference" class="form-control" name="reference"> """ + "\n".join(self.getReferenceOptions()) + """ </select> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"> Library Type </label> <div class="radio"> <label> <input type="radio" name="paired" id="optionsRadios1" value="false" onClick="javascript:$('#reads2').prop('disabled',true);" checked> Single-End </label> <label> <input type="radio" name="paired" id="optionsRadios2" value="true" onClick="javascript:$('#reads2').prop('disabled',false);"> Paired-End </label> </div> </div> <div class="form-group"> <label for="reads1" class="col-sm-2 control-label">Simulated Reads File (1)</label> <div class="col-sm-4"> <select id="reads1" class="form-control" name="reads1"> """ + "\n".join(self.getFileOptions()) + """ </select> </div> </div> <div class="form-group"> <label for="reads2" class="col-sm-2 control-label">Simulated Reads File (2)</label> <div class="col-sm-4"> <select id="reads2" class="form-control" name="reads2" disabled> """ + "\n".join(self.getFileOptions()) + """ </select> </div> </div> </div> """, """<div class="form-group"> <a href="#section1" class="btn btn-info" role="button">Back</a> <a href="#section3" class="btn btn-info" role="button">Next</a> </div>""") def get(self): page = Page() page.enableFullscreenSections() self.addSectionDataSource(page, "real") self.addSectionSelectData(page) self.addSectionEvaluation(page) self.addSectionAdvanced(page) page.setNavRight("""<a href="/" class="btn btn-warning" role="button">Back to Teaser Home</a>""") self.write(page.html()) class RedirectJob(tornado.web.RequestHandler): def get(self, jobid): try: with open("reports/" + jobid + "/index.html", "r") as h: if h.read().strip() == "INITIALIZING": raise else: self.redirect("/reports/" + jobid + "/") except: self.write("""<meta http-equiv="refresh" content="1">Please wait...""") class SubmitJob(tornado.web.RequestHandler): def post(self): self.job_id = util.md5(str(int(time.time())) + self.get_argument('reference', '')) config_path, config = self.generateConfig() teaser = self.startTeaser(config_path) try: os.mkdir("reports/" + self.getJobId()) except: pass with open("reports/" + self.getJobId() + "/index.html", "w") as handle: handle.write("INITIALIZING") handle.flush() handle.close() with open("reports/" + self.getJobId() + "/config.yaml", "w") as handle: handle.write(yaml.dump(config)) handle.flush() handle.close() self.redirect("/redirect/" + self.getJobId()) job = {"name": self.job_id, "process": teaser} instance.jobs.append(job) print("Started Teaser with config %s" % config_path) def generateConfig(self): head, tail = os.path.split(self.get_argument('reference', '')) name, ext = os.path.splitext(tail) pos_threshold = int(self.get_argument('pos_threshold', -1)) if pos_threshold < 0: pos_threshold = int(self.get_argument('read_length', 60)) / 2 config_ = {} config_["meta_timestamp"] = time.time() config_["include"] = ["base_teaser.yaml"] config_["report"] = {"name": self.getJobId()} config_["evaluation"] = {"pos_threshold": pos_threshold} config_["teaser"] = {} config_["teaser"]["tests"] = {} config_["threads"] = min(int(self.get_argument('threads', 1)), config["teaser"]["server"]["max_threads"]) config_["sub_max_memory"] = min(int(self.get_argument('sub_max_memory', 16000)), config["teaser"]["server"]["max_memory"]) config_["sub_max_runtime"] = min(int(self.get_argument('sub_max_memory', 16000)), config["teaser"]["server"]["max_runtime"]) test = {} test["title"] = name test["reference"] = util.sanitize_string(tail) test["type"] = util.sanitize_string(self.get_argument('type', 'simulated_teaser')) test["paired"] = self.get_argument('paired', 'false') == 'true' if self.get_argument('type', '') == "simulated_teaser": test["read_length"] = int(self.get_argument('read_length', 60)) test["mutation_rate"] = float(self.get_argument('mutation_rate', 0.001)) test["mutation_indel_frac"] = float(self.get_argument('mutation_indel_frac', 0.3)) test["mutation_indel_avg_len"] = float(self.get_argument('mutation_indel_avg_len', 1)) test["error_rate_mult"] = float(self.get_argument('error_rate_mult', 1)) test["platform"] = util.sanitize_string(self.get_argument('platform', 'illumina')) test["coverage"] = float(self.get_argument('coverage', 0)) if self.get_argument('simulator', 'none') != "none": test["simulator"] = util.sanitize_string(self.get_argument('simulator', 'none')) if test["paired"]: test["insert_size"] = int(self.get_argument('insert_size', '')) test["insert_size_error"] = int(self.get_argument('insert_size_error', '')) else: if test["paired"]: test["import_read_files"] = [config["teaser"]["import_directory"] + "/" + util.sanitize_string(self.get_argument('reads1', 'none')), config["teaser"]["import_directory"] + "/" + util.sanitize_string(self.get_argument('reads2', 'none'))] else: test["import_read_files"] = [config["teaser"]["import_directory"] + "/" + util.sanitize_string(self.get_argument('reads1', 'none'))] if "gold_standard" in self.request.arguments: test["import_gold_standard_file"] = config["teaser"]["import_directory"] + "/" + util.sanitize_string(self.get_argument('gold_standard', 'none')) config_["test_mappers"] = [] config_["test_parameters"] = [] if "mappers" in self.request.arguments: for mapper in self.request.arguments["mappers"]: if mapper[0] == "m": config_["test_mappers"].append(util.sanitize_string(mapper[1:])) elif mapper[0] == "p": config_["test_parameters"].append(util.sanitize_string(mapper[1:])) else: raise config_["teaser"]["tests"][self.getJobId()] = test config_path = "setups_generated/" + self.getJobId() + ".yaml" with open(config_path, "w") as yml: yml.write(yaml.dump(config_)) yml.flush() yml.close() #print("Wrote config to %s" % config_path) return config_path, config_ def startTeaser(self, config_path): cmd = config["teaser"]["server"]["framework_cmd"] % (config_path, self.job_id) cmd = cmd.replace("(b)", sys.executable) print("Running Teaser using %s..." % cmd) proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) return proc def getJobId(self): return self.job_id class MyStaticFileHandler(tornado.web.StaticFileHandler): def set_extra_headers(self, path): self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') class TeaserServer: def __init__(self): self.jobs = [] def main(self, wsgi=False): #args = sys.argv #args.append("--log_file_prefix=%s/logs/tornado.log" % util.getRootDir() ) #print("Log file: %s/logs/tornado.log"%util.getRootDir()) #tornado.options.parse_command_line(args) app = tornado.web.Application([("/", Home), ("/home", Home), ("/define", DefineJobTeaser), ("/define-custom", DefineJobCustom), ("/define-real", DefineJobReal), ("/submitjob", SubmitJob), (r'/reports/(.*)', MyStaticFileHandler, {'path': config["report"]["directory"], "default_filename": "index.html"}), (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': "static", "default_filename": "index.html"}), (r'/redirect/(.*)', RedirectJob)]) if wsgi: print("Running as WSGI") app = tornado.wsgi.WSGIAdapter(app) else: print("Running as standalone HTTP server on port %d" % config["teaser"]["server"]["port"]) app.listen(config["teaser"]["server"]["port"]) tornado.ioloop.IOLoop.current().start() return app def pollJobs(self): for job in self.jobs: if not job["process"].poll(): self.jobs.remove(job) import os import time import subprocess import shutil import sys import datetime def deleteContents(dir, max_age_hours=24 * 365): try: if not os.path.exists(dir): os.mkdir(dir) except: return for file in os.listdir(dir): path = dir + "/" + file if file[0] == ".": continue try: file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(path)) if datetime.datetime.now() - file_modified < datetime.timedelta(hours=max_age_hours): continue except: continue try: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) except: pass import logging tornado.options.parse_command_line() call_dir = os.getcwd() root_dir = os.path.realpath(os.path.dirname(os.path.realpath(__file__)) + "/../") os.chdir(root_dir) from lib import util setCallDir = util.setCallDir setRootDir = util.setRootDir enterCallDir = util.enterCallDir enterRootDir = util.enterRootDir setCallDir(call_dir) setRootDir(root_dir) enterRootDir() logging.getLogger("tornado.access").addHandler(logging.FileHandler("logs/server.access.log")) logging.getLogger("tornado.application").addHandler(logging.FileHandler("logs/server.application.log")) logging.getLogger("tornado.general").addHandler(logging.FileHandler("logs/server.general.log")) deleteContents("setups_generated") deleteContents("tests_generated") deleteContents("reports") config_file = "base_teaser.yaml" if len(sys.argv) > 1: config_file = sys.argv[1] config, original = util.loadConfig(config_file) print("Root dir: %s" % root_dir) #sys.stdout = open("logs/server.txt","w") #sys.stderr = sys.stdout # instance = TeaserServer() # instance.main()
mit
unsiloai/syntaxnet-ops-hack
tensorflow/contrib/predictor/testing_common.py
93
4328
# 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. # ============================================================================== """Common code used for testing `Predictor`s.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import estimator as contrib_estimator from tensorflow.contrib.learn.python.learn.estimators import model_fn as contrib_model_fn from tensorflow.contrib.learn.python.learn.utils import input_fn_utils from tensorflow.python.estimator import estimator as core_estimator from tensorflow.python.estimator import model_fn from tensorflow.python.estimator.export import export_lib from tensorflow.python.estimator.export import export_output from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.saved_model import signature_constants def get_arithmetic_estimator(core=True, model_dir=None): """Returns an `Estimator` that performs basic arithmetic. Args: core: if `True`, returns a `tensorflow.python.estimator.Estimator`. Otherwise, returns a `tensorflow.contrib.learn.Estimator`. model_dir: directory in which to export checkpoints and saved models. Returns: An `Estimator` that performs arithmetic operations on its inputs. """ def _model_fn(features, labels, mode): _ = labels x = features['x'] y = features['y'] with ops.name_scope('outputs'): predictions = {'sum': math_ops.add(x, y, name='sum'), 'product': math_ops.multiply(x, y, name='product'), 'difference': math_ops.subtract(x, y, name='difference')} if core: export_outputs = {k: export_output.PredictOutput({k: v}) for k, v in predictions.items()} export_outputs[signature_constants. DEFAULT_SERVING_SIGNATURE_DEF_KEY] = export_outputs['sum'] return model_fn.EstimatorSpec(mode=mode, predictions=predictions, export_outputs=export_outputs, loss=constant_op.constant(0), train_op=control_flow_ops.no_op()) else: output_alternatives = {k: (constants.ProblemType.UNSPECIFIED, {k: v}) for k, v in predictions.items()} return contrib_model_fn.ModelFnOps( mode=mode, predictions=predictions, output_alternatives=output_alternatives, loss=constant_op.constant(0), train_op=control_flow_ops.no_op()) if core: return core_estimator.Estimator(_model_fn) else: return contrib_estimator.Estimator(_model_fn, model_dir=model_dir) def get_arithmetic_input_fn(core=True, train=False): """Returns a input functions or serving input receiver function.""" def _input_fn(): with ops.name_scope('inputs'): x = array_ops.placeholder_with_default(0.0, shape=[], name='x') y = array_ops.placeholder_with_default(0.0, shape=[], name='y') label = constant_op.constant(0.0) features = {'x': x, 'y': y} if core: if train: return features, label return export_lib.ServingInputReceiver( features=features, receiver_tensors=features) else: if train: return features, label return input_fn_utils.InputFnOps( features=features, labels={}, default_inputs=features) return _input_fn
apache-2.0
barbuza/django
tests/raw_query/models.py
231
1182
from django.db import models class Author(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) dob = models.DateField() def __init__(self, *args, **kwargs): super(Author, self).__init__(*args, **kwargs) # Protect against annotations being passed to __init__ -- # this'll make the test suite get angry if annotations aren't # treated differently than fields. for k in kwargs: assert k in [f.attname for f in self._meta.fields], \ "Author.__init__ got an unexpected parameter: %s" % k class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author, models.CASCADE) paperback = models.BooleanField(default=False) opening_line = models.TextField() class BookFkAsPk(models.Model): book = models.ForeignKey(Book, models.CASCADE, primary_key=True, db_column="not_the_default") class Coffee(models.Model): brand = models.CharField(max_length=255, db_column="name") class Reviewer(models.Model): reviewed = models.ManyToManyField(Book) class FriendlyAuthor(Author): pass
bsd-3-clause
ClaudeZoo/iDashBoardWeb
Web/control_vm_views.py
2
2925
import json from django.shortcuts import HttpResponse from django.contrib.auth.decorators import login_required from Web.models import VM from Web.models import OperationRecord from Web.communication import communicate @login_required def control_vm(request): request_type = request.POST['request_type'] vm = VM.objects.get(uuid=request.POST['uuid']) operation = OperationRecord(vm=vm, user=request.user, type=request_type) operation.save() host = vm.host request_dict = dict(request_id=operation.id, request_type=request_type, request_userid=request.user.id, vm_name=vm.name, vm_uuid=vm.uuid) response = communicate(request_dict, host.ip, host.vm_manager_port) if response and response['request_result'] == 'success': operation.result = 'success' print request_type if request_type == 'start': vm.state = 'Online' elif request_type == 'shutdown': vm.state = 'Offline' else: vm.state = 'Hibernating' vm.save() elif response: operation.result = response['request_result'] operation.information = response['error_information'] else: operation.result = response['network_error'] operation.save() return HttpResponse(json.dumps(dict(request_result=operation.result, error_information=operation.information))) def start_vm(request): request_type = request.POST['request_type'] vm = VM.objects.get(uuid=request.POST['uuid']) operation = OperationRecord(vm=vm, user=request.user, type=request_type) operation.save() host = vm.host request_dict = dict(request_id=operation.id, request_type=request_type, request_userid=request.user.id, vm_name=vm.name, vm_uuid=vm.uuid) communicate(dict(vm_uuid=vm.uuid, type='stop'), vm.host.ip, vm.host.monitor_port) response = communicate(request_dict, host.ip, host.vm_manager_port) if response and response['request_result'] == 'success': return HttpResponse(json.dumps(dict(request_result='success'))) elif response: operation.result = response['request_result'] operation.information = response['error_information'] else: operation.result = response['network_error'] operation.save() return HttpResponse(json.dumps(dict(request_result=operation.result, error_information=operation.information))) def start_monitor(request): uuid = request.POST['uuid'] vm = VM.objects.get(uuid=uuid) if vm.state == 'Online': request_dict = dict(vm_uuid=uuid, type='stop') communicate(request_dict, vm.host.ip, vm.host.monitor_port) return HttpResponse(json.dumps(dict(result='stop'))) else: request_dict = dict(vm_uuid=uuid, type='query') response = communicate(request_dict, vm.host.ip, vm.host.monitor_port) return HttpResponse(json.dumps(response))
unlicense
Nolan330/CS292
pymavlink/setup.py
3
3759
from distutils.core import setup, Extension import glob, os, shutil version = '1.1.18' from generator import mavgen, mavparse # path to message_definitions directory mdef_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'message_definitions') dialects_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dialects') v09_dialects = glob.glob(os.path.join(mdef_path, 'v0.9', '*.xml')) v10_dialects = glob.glob(os.path.join(mdef_path, 'v1.0', '*.xml')) v09_dialects if not "NOGEN" in os.environ: for xml in v09_dialects: shutil.copy(xml, os.path.join(dialects_path, 'v09')) for xml in v10_dialects: shutil.copy(xml, os.path.join(dialects_path, 'v10')) for xml in v09_dialects: dialect = os.path.basename(xml)[:-4] print("Building %s" % xml) mavgen.mavgen_python_dialect(dialect, mavparse.PROTOCOL_0_9) for xml in v10_dialects: dialect = os.path.basename(xml)[:-4] print("Building %s" % xml) mavgen.mavgen_python_dialect(dialect, mavparse.PROTOCOL_1_0) setup (name = 'pymavlink', version = version, description = 'Python MAVLink code', long_description = '''A Python library for handling MAVLink protocol streams and log files. This allows for the creation of simple scripts to analyse telemetry logs from autopilots such as ArduPilot which use the MAVLink protocol. See the scripts that come with the package for examples of small, useful scripts that use pymavlink. For more information about the MAVLink protocol see http://qgroundcontrol.org/mavlink/''', url = 'http://github.com/mavlink/mavlink', classifiers=['Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering' ], license='LGPLv3', package_dir = { 'pymavlink' : '.' }, package_data = { 'pymavlink.dialects.v09' : ['*.xml'], 'pymavlink.dialects.v10' : ['*.xml'], 'pymavlink.generator' : [ '*.xsd' ], 'pymavlink.generator' : [ 'C/include_v0.9/*.h', 'C/include_v1.0/*.h', 'C/include_v1.0/*.hpp' ], 'pymavlink.generator.lib.minixsv': [ '*.xsd' ] }, packages = ['pymavlink', 'pymavlink.generator', 'pymavlink.generator.lib', 'pymavlink.generator.lib.genxmlif', 'pymavlink.generator.lib.minixsv', 'pymavlink.dialects', 'pymavlink.dialects.v09', 'pymavlink.dialects.v10'], scripts = [ 'tools/magfit_delta.py', 'tools/mavextract.py', 'tools/mavgraph.py', 'tools/mavparmdiff.py', 'tools/mavtogpx.py', 'tools/magfit_gps.py', 'tools/mavflightmodes.py', 'tools/mavlogdump.py', 'tools/mavparms.py', 'tools/magfit_motors.py', 'tools/mavflighttime.py', 'tools/mavloss.py', 'tools/mavplayback.py', 'tools/magfit.py', 'tools/mavgpslock.py', 'tools/mavmission.py', 'tools/mavsigloss.py', 'tools/mavsearch.py', 'tools/mavtomfile.py', 'generator/mavgen.py', 'tools/mavkml.py'] )
lgpl-3.0
LudwigKnuepfer/otm
otm.py
2
9568
#!/usr/bin/env python2 description = 'otm - display static memory of an elf file in a treemap' """ Copyright (C) 2014 Ludwig Ortmann <ludwig@spline.de> 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/>. """ import sys from os import path import subprocess import random import re import argparse from pprint import pprint import pylab from matplotlib.patches import Rectangle class Treemap: def __init__(self, tree): self.ax = pylab.subplot(111,aspect='equal') pylab.subplots_adjust(left=0, right=1, top=1, bottom=0) self.ax.set_xticks([]) self.ax.set_yticks([]) self.iterate(tree) def iterate(self, node, lower=[0,0], upper=[1,1], axis=0): axis = axis % 2 self.draw_rectangle(lower, upper, node) width = upper[axis] - lower[axis] ns = node.get_size() for child in node.children: cs = child.get_size() upper[axis] = (lower[axis] + ((width * float(cs)) / ns)) lo = list(lower) up = list(upper) self.iterate(child, lo, up, axis + 1) lower[axis] = upper[axis] def draw_rectangle(self, lower, upper, node): r = Rectangle( lower, upper[0]-lower[0], upper[1] - lower[1], edgecolor='k', facecolor= node.get_color(), label=node.name) self.ax.add_patch(r) rx, ry = r.get_xy() rw = r.get_width() rh = r.get_height() cx = rx + rw/2.0 cy = ry + rh/2.0 if isinstance(node, PathNode): t = node.name if rw * 3 < rh: t += ", " else: t += "\n" t += str(node.size) + ", " + node.stype c='w' if rw < rh: o = "vertical" else: o = "horizontal" else: t = node.name if node.isfile: c='k' o = 45 else: return self.ax.annotate( t, (cx,cy), color=c, weight='bold', ha='center', va='center', rotation=o ) class PathTree(): def __init__(self, name, path_dict): self.children = list() self.name = name self.size = None self.isfile = False print name subdirectories = list() for p in path_dict: if p == '': #print "content", p self.add_children(path_dict[p]) self.isfile = True else: #print "entry", p subdirectories.append(p) cdict = dict() for pathname in subdirectories: parts = pathname.split("/", 1) if len(parts) == 1: x = parts[0] rest = "" else: x,rest = parts if not x in cdict: cdict[x] = dict() cdict[x][rest] = path_dict[pathname] #print "adding", pathname, "to", x for k in cdict: #pprint(v, indent=2) self.children.append(PathTree(k, cdict[k])) #print "size:", self.get_size() def __repr__(self): return self.name def add_children(self, sym_list): for symbol in sym_list: self.children.append(PathNode(*symbol)) def get_size(self): if self.size is None: self.size = 0 for c in self.children: self.size += c.get_size() return self.size def get_color(self): return (random.random(),random.random(),random.random()) class PathNode(PathTree): def __init__(self, name, line, size, stype): self.children = [] print "\t", name, stype self.name = name self.size = size self.line = line self.isfile = False self.stype = stype def parse_elf(filename, minimum_size=None, symbol_type_list=None, function_path_regex_in=None, function_name_regex_in=None, object_path_regex_in=None, object_name_regex_in=None, function_path_regex_ex=None, function_name_regex_ex=None, object_path_regex_ex=None, object_name_regex_ex=None, ): """parse elf file into a {path: [(symbol, linenumber, size)]} dictionary""" output = subprocess.check_output([ "nm", "--radix=d", "-S", "-l", "--size-sort", filename]) "addr size type name [path:line]" addressses = [x.split() for x in output.splitlines()] paths = dict() for foo in addressses: size = foo[1] stype = foo[2] symbolname = foo[3] if len(foo) > 4: pathname,lineno = foo[4].split(":") else: pathname,lineno = '??','?' size = int(size) if minimum_size and size < minimum_size: continue pathname = path.normpath(pathname) if pathname[0] == '/': pathname = pathname[1:] if stype in "tT": ppati = function_path_regex_in npati = function_name_regex_in ppate = function_path_regex_ex npate = function_name_regex_ex elif stype in 'bB': ppati = object_path_regex_in npati = object_name_regex_in ppate = object_path_regex_ex npate = object_name_regex_ex else: ppat = None npat = None ppati = None ppate = None npati = None npate = None if ppati and not re.search(ppati, pathname): continue if npati and not re.search(npati, symbolname): continue if ppate and re.search(ppate, pathname): continue if npate and re.search(npate, symbolname): continue if symbol_type_list and stype not in symbol_type_list: continue if not pathname in paths: paths[pathname] = list() paths[pathname].append((symbolname, lineno, size, stype)) return paths def arg_parser(): p = argparse.ArgumentParser(description=description) p.add_argument("filename", default="a.out", nargs='?', help="the elf file to parse") p.add_argument("-d","--documentation", action="store_true", default=argparse.SUPPRESS, help="print additional documentation and exit") p.add_argument("-fp", "--function-path-regex-in", default=None, help="regular expression for function path inclusion") p.add_argument("-op","--object-path-regex-in", default=None, help="regular expression for object path inclusion") p.add_argument("-fn", "--function-name-regex-in", default=None, help="regular expression for function name inclusion") p.add_argument("-on","--object-name-regex-in", default=None, help="regular expression for object name inclusion") p.add_argument("-Fp", "--function-path-regex-ex", default=None, help="regular expression for function path exclusion") p.add_argument("-Op","--object-path-regex-ex", default=None, help="regular expression for object path exclusion") p.add_argument("-Fn", "--function-name-regex-ex", default=None, help="regular expression for function name exclusion") p.add_argument("-On","--object-name-regex-ex", default=None, help="regular expression for object name exclusion") p.add_argument("-t","--symbol-type-list", default=None, help="list of symbol types to include") p.add_argument("-m","--minimum-size", type=int, default=1, help="mininum size for all types") return p def exit_doc(): print """ Regular expression examples: display only functions that come from net or core: --function-path-regex-in "net|core" display only objects that nm could not look up --obj-path-regex "\?\?" do not display objects that end on _stack --object-name-regex-ex "_stack$" When combining these options, exclusion takes precedence over inclusion: display only objects from main.c filtering out stacks: -op "main\.c" -On "_stack$|_stk$" Symbol type list: include text and BSS section symbols check the nm manpage for details: --symbol-type-list tTbB Minumum size: The minimum-size argument is taken as an inclusion hurdle, i.e. symbols below that size are not taken into consideration at all. """ sys.exit() if __name__ == '__main__': args = arg_parser().parse_args() if hasattr(args,"documentation"): exit_doc() if not path.isfile(args.filename): sys.exit("file does not exist: " + args.filename) elf = parse_elf(**vars(args)) tree = PathTree("root", elf) Treemap(tree) pylab.show()
gpl-3.0
tistaharahap/classifier-py
textclassifier/classifier.py
1
1665
# -*- coding: utf-8 -*- from __future__ import division from store import BasicStore class Classifier(object): pass class NaiveBayesClassifier(object): thresholds = {} store = None def __init__(self, store, train_set, thresholds={}): if not isinstance(store, BasicStore): raise TypeError("Store must be an instance of BasicStore") self.store = store self.thresholds = thresholds if not isinstance(train_set, dict): raise TypeError("Train Set must be an instance of Dictionary") self.store = store self.train(train_set=train_set) def train(self, train_set): if not isinstance(train_set, dict): raise TypeError("Train Set should be a dictionary of text: category") for (t, c) in train_set.iteritems(): self.store.train(text=t, cat=c) def cat_scores(self, text): return self.store.cat_scores(text=text) def classify(self, text, default_cat='uncategorized', verbose=False): max_prob = -1000000000.0 best = None scores = self.cat_scores(text) for (cat, prob) in scores.iteritems(): if verbose: print cat, prob if prob > max_prob: max_prob = prob best = cat if verbose: print "Best: %s" % best if not best: return default_cat if self.thresholds and self.thresholds.get(best): threshold = self.thresholds[best] else: threshold = 1.0 if verbose: print "Threshold: %s" % threshold return best
mit
allenwoods/parasys
Model/q_model.py
1
1097
#! /usr/bin/env python # -*- coding: utf-8 -*- """ @file q_model.py @author Allen Woods @date 2016-08-01 @version 16-8-1 下午9:59 ??? Some other Description """ import tensorflow as tf from keras.layers import Convolution2D, Flatten, Dense, Input from keras.models import Model def build_network(num_actions, agent_history_length, resized_width, resized_height): state = tf.placeholder("float", [None, agent_history_length, resized_width, resized_height]) inputs = Input(shape=(agent_history_length, resized_width, resized_height,)) model = Convolution2D(nb_filter=16, nb_row=8, nb_col=8, subsample=(4, 4), activation='relu', border_mode='same')( inputs) model = Convolution2D(nb_filter=32, nb_row=4, nb_col=4, subsample=(2, 2), activation='relu', border_mode='same')( model) model = Flatten()(model) model = Dense(output_dim=256, activation='relu')(model) q_values = Dense(output_dim=num_actions, activation='linear')(model) m = Model(input=inputs, output=q_values) return state, m if __name__ == '__main__': pass
mit
BarakChamo/rc-badges
node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/input_test.py
1841
3207
#!/usr/bin/env python # Copyright 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. """Unit tests for the input.py file.""" import gyp.input import unittest import sys class TestFindCycles(unittest.TestCase): def setUp(self): self.nodes = {} for x in ('a', 'b', 'c', 'd', 'e'): self.nodes[x] = gyp.input.DependencyGraphNode(x) def _create_dependency(self, dependent, dependency): dependent.dependencies.append(dependency) dependency.dependents.append(dependent) def test_no_cycle_empty_graph(self): for label, node in self.nodes.iteritems(): self.assertEquals([], node.FindCycles()) def test_no_cycle_line(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['b'], self.nodes['c']) self._create_dependency(self.nodes['c'], self.nodes['d']) for label, node in self.nodes.iteritems(): self.assertEquals([], node.FindCycles()) def test_no_cycle_dag(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['a'], self.nodes['c']) self._create_dependency(self.nodes['b'], self.nodes['c']) for label, node in self.nodes.iteritems(): self.assertEquals([], node.FindCycles()) def test_cycle_self_reference(self): self._create_dependency(self.nodes['a'], self.nodes['a']) self.assertEquals([[self.nodes['a'], self.nodes['a']]], self.nodes['a'].FindCycles()) def test_cycle_two_nodes(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['b'], self.nodes['a']) self.assertEquals([[self.nodes['a'], self.nodes['b'], self.nodes['a']]], self.nodes['a'].FindCycles()) self.assertEquals([[self.nodes['b'], self.nodes['a'], self.nodes['b']]], self.nodes['b'].FindCycles()) def test_two_cycles(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['b'], self.nodes['a']) self._create_dependency(self.nodes['b'], self.nodes['c']) self._create_dependency(self.nodes['c'], self.nodes['b']) cycles = self.nodes['a'].FindCycles() self.assertTrue( [self.nodes['a'], self.nodes['b'], self.nodes['a']] in cycles) self.assertTrue( [self.nodes['b'], self.nodes['c'], self.nodes['b']] in cycles) self.assertEquals(2, len(cycles)) def test_big_cycle(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['b'], self.nodes['c']) self._create_dependency(self.nodes['c'], self.nodes['d']) self._create_dependency(self.nodes['d'], self.nodes['e']) self._create_dependency(self.nodes['e'], self.nodes['a']) self.assertEquals([[self.nodes['a'], self.nodes['b'], self.nodes['c'], self.nodes['d'], self.nodes['e'], self.nodes['a']]], self.nodes['a'].FindCycles()) if __name__ == '__main__': unittest.main()
mit
preete-dixit-ck/incubator-airflow
airflow/utils/email.py
8
4246
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str from past.builtins import basestring import importlib import logging import os import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from email.utils import formatdate from airflow import configuration from airflow.exceptions import AirflowConfigException def send_email(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed'): """ Send email using backend specified in EMAIL_BACKEND. """ path, attr = configuration.get('email', 'EMAIL_BACKEND').rsplit('.', 1) module = importlib.import_module(path) backend = getattr(module, attr) return backend(to, subject, html_content, files=files, dryrun=dryrun, cc=cc, bcc=bcc, mime_subtype=mime_subtype) def send_email_smtp(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed'): """ Send an email with html content >>> send_email('test@example.com', 'foo', '<b>Foo</b> bar', ['/dev/null'], dryrun=True) """ SMTP_MAIL_FROM = configuration.get('smtp', 'SMTP_MAIL_FROM') to = get_email_address_list(to) msg = MIMEMultipart(mime_subtype) msg['Subject'] = subject msg['From'] = SMTP_MAIL_FROM msg['To'] = ", ".join(to) recipients = to if cc: cc = get_email_address_list(cc) msg['CC'] = ", ".join(cc) recipients = recipients + cc if bcc: # don't add bcc in header bcc = get_email_address_list(bcc) recipients = recipients + bcc msg['Date'] = formatdate(localtime=True) mime_text = MIMEText(html_content, 'html') msg.attach(mime_text) for fname in files or []: basename = os.path.basename(fname) with open(fname, "rb") as f: part = MIMEApplication( f.read(), Name=basename ) part['Content-Disposition'] = 'attachment; filename="%s"' % basename part['Content-ID'] = '<%s>' % basename msg.attach(part) send_MIME_email(SMTP_MAIL_FROM, recipients, msg, dryrun) def send_MIME_email(e_from, e_to, mime_msg, dryrun=False): SMTP_HOST = configuration.get('smtp', 'SMTP_HOST') SMTP_PORT = configuration.getint('smtp', 'SMTP_PORT') SMTP_STARTTLS = configuration.getboolean('smtp', 'SMTP_STARTTLS') SMTP_SSL = configuration.getboolean('smtp', 'SMTP_SSL') SMTP_USER = None SMTP_PASSWORD = None try: SMTP_USER = configuration.get('smtp', 'SMTP_USER') SMTP_PASSWORD = configuration.get('smtp', 'SMTP_PASSWORD') except AirflowConfigException: logging.debug("No user/password found for SMTP, so logging in with no authentication.") if not dryrun: s = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) if SMTP_SSL else smtplib.SMTP(SMTP_HOST, SMTP_PORT) if SMTP_STARTTLS: s.starttls() if SMTP_USER and SMTP_PASSWORD: s.login(SMTP_USER, SMTP_PASSWORD) logging.info("Sent an alert email to " + str(e_to)) s.sendmail(e_from, e_to, mime_msg.as_string()) s.quit() def get_email_address_list(address_string): if isinstance(address_string, basestring): if ',' in address_string: address_string = address_string.split(',') elif ';' in address_string: address_string = address_string.split(';') else: address_string = [address_string] return address_string
apache-2.0
CapOM/ChromiumGStreamerBackend
tools/telemetry/third_party/gsutilz/third_party/boto/tests/integration/cognito/identity/test_cognito_identity.py
112
2545
# Copyright (c) 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved # # 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, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing 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 MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR 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 boto.cognito.identity.exceptions import ResourceNotFoundException from tests.integration.cognito import CognitoTest class TestCognitoIdentity(CognitoTest): """ Test Cognitoy identity pools operations since individual Cognito identities require an AWS account ID. """ def test_cognito_identity(self): # Ensure the identity pool is in the list of pools. response = self.cognito_identity.list_identity_pools(max_results=5) expected_identity = {'IdentityPoolId': self.identity_pool_id, 'IdentityPoolName': self.identity_pool_name} self.assertIn(expected_identity, response['IdentityPools']) # Ensure the pool's attributes are as expected. response = self.cognito_identity.describe_identity_pool( identity_pool_id=self.identity_pool_id ) self.assertEqual(response['IdentityPoolName'], self.identity_pool_name) self.assertEqual(response['IdentityPoolId'], self.identity_pool_id) self.assertFalse(response['AllowUnauthenticatedIdentities']) def test_resource_not_found_exception(self): with self.assertRaises(ResourceNotFoundException): # Note the region is us-east-0 which is an invalid region name. self.cognito_identity.describe_identity_pool( identity_pool_id='us-east-0:c09e640-b014-4822-86b9-ec77c40d8d6f' )
bsd-3-clause
AutorestCI/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/troubleshooting_parameters.py
8
1630
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class TroubleshootingParameters(Model): """Parameters that define the resource to troubleshoot. :param target_resource_id: The target resource to troubleshoot. :type target_resource_id: str :param storage_id: The ID for the storage account to save the troubleshoot result. :type storage_id: str :param storage_path: The path to the blob to save the troubleshoot result in. :type storage_path: str """ _validation = { 'target_resource_id': {'required': True}, 'storage_id': {'required': True}, 'storage_path': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, 'storage_id': {'key': 'properties.storageId', 'type': 'str'}, 'storage_path': {'key': 'properties.storagePath', 'type': 'str'}, } def __init__(self, target_resource_id, storage_id, storage_path): super(TroubleshootingParameters, self).__init__() self.target_resource_id = target_resource_id self.storage_id = storage_id self.storage_path = storage_path
mit
atsao72/sympy
sympy/printing/lambdarepr.py
5
7245
from __future__ import print_function, division from .str import StrPrinter from sympy.utilities import default_sort_key class LambdaPrinter(StrPrinter): """ This printer converts expressions into strings that can be used by lambdify. """ def _print_MatrixBase(self, expr): return "%s(%s)" % (expr.__class__.__name__, self._print((expr.tolist()))) _print_SparseMatrix = \ _print_MutableSparseMatrix = \ _print_ImmutableSparseMatrix = \ _print_Matrix = \ _print_DenseMatrix = \ _print_MutableDenseMatrix = \ _print_ImmutableMatrix = \ _print_ImmutableDenseMatrix = \ _print_MatrixBase def _print_Piecewise(self, expr): result = [] i = 0 for arg in expr.args: e = arg.expr c = arg.cond result.append('((') result.append(self._print(e)) result.append(') if (') result.append(self._print(c)) result.append(') else (') i += 1 result = result[:-1] result.append(') else None)') result.append(')'*(2*i - 2)) return ''.join(result) def _print_And(self, expr): result = ['('] for arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' and ') result = result[:-1] result.append(')') return ''.join(result) def _print_Or(self, expr): result = ['('] for arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' or ') result = result[:-1] result.append(')') return ''.join(result) def _print_Not(self, expr): result = ['(', 'not (', self._print(expr.args[0]), '))'] return ''.join(result) def _print_BooleanTrue(self, expr): return "True" def _print_BooleanFalse(self, expr): return "False" class NumPyPrinter(LambdaPrinter): """ Numpy printer which handles vectorized piecewise functions, logical operators, etc. """ _default_settings = { "order": "none", "full_prec": "auto", } def _print_seq(self, seq, delimiter=', '): "General sequence printer: converts to tuple" # Print tuples here instead of lists because numba supports # tuples in nopython mode. return '({},)'.format(delimiter.join(self._print(item) for item in seq)) def _print_MatMul(self, expr): "Matrix multiplication printer" return '({0})'.format(').dot('.join(self._print(i) for i in expr.args)) def _print_Piecewise(self, expr): "Piecewise function printer" # Print tuples here instead of lists because numba may add support # for select in nopython mode; see numba#1313 on github. exprs = '({0},)'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds = '({0},)'.format(','.join(self._print(arg.cond) for arg in expr.args)) # If (default_value, True) is a (expr, cond) tuple in a Piecewise object # it will behave the same as passing the 'default' kwarg to select() # *as long as* it is the last element in expr.args. # If this is not the case, it may be triggered prematurely. return 'select({0}, {1}, default=nan)'.format(conds, exprs) def _print_And(self, expr): "Logical And printer" # We have to override LambdaPrinter because it uses Python 'and' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_and' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_and', ','.join(self._print(i) for i in expr.args)) def _print_Or(self, expr): "Logical Or printer" # We have to override LambdaPrinter because it uses Python 'or' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_or' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_or', ','.join(self._print(i) for i in expr.args)) def _print_Not(self, expr): "Logical Not printer" # We have to override LambdaPrinter because it uses Python 'not' keyword. # If LambdaPrinter didn't define it, we would still have to define our # own because StrPrinter doesn't define it. return '{0}({1})'.format('logical_not', ','.join(self._print(i) for i in expr.args)) # numexpr works by altering the string passed to numexpr.evaluate # rather than by populating a namespace. Thus a special printer... class NumExprPrinter(LambdaPrinter): # key, value pairs correspond to sympy name and numexpr name # functions not appearing in this dict will raise a TypeError _numexpr_functions = { 'sin' : 'sin', 'cos' : 'cos', 'tan' : 'tan', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2' : 'arctan2', 'sinh' : 'sinh', 'cosh' : 'cosh', 'tanh' : 'tanh', 'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh', 'ln' : 'log', 'log': 'log', 'exp': 'exp', 'sqrt' : 'sqrt', 'Abs' : 'abs', 'conjugate' : 'conj', 'im' : 'imag', 're' : 'real', 'where' : 'where', 'complex' : 'complex', 'contains' : 'contains', } def _print_ImaginaryUnit(self, expr): return '1j' def _print_seq(self, seq, delimiter=', '): # simplified _print_seq taken from pretty.py s = [self._print(item) for item in seq] if s: return delimiter.join(s) else: return "" def _print_Function(self, e): func_name = e.func.__name__ nstr = self._numexpr_functions.get(func_name, None) if nstr is None: # check for implemented_function if hasattr(e, '_imp_'): return "(%s)" % self._print(e._imp_(*e.args)) else: raise TypeError("numexpr does not support function '%s'" % func_name) return "%s(%s)" % (nstr, self._print_seq(e.args)) def blacklisted(self, expr): raise TypeError("numexpr cannot be used with %s" % expr.__class__.__name__) # blacklist all Matrix printing _print_SparseMatrix = \ _print_MutableSparseMatrix = \ _print_ImmutableSparseMatrix = \ _print_Matrix = \ _print_DenseMatrix = \ _print_MutableDenseMatrix = \ _print_ImmutableMatrix = \ _print_ImmutableDenseMatrix = \ blacklisted # blacklist some python expressions _print_list = \ _print_tuple = \ _print_Tuple = \ _print_dict = \ _print_Dict = \ blacklisted def doprint(self, expr): lstr = super(NumExprPrinter, self).doprint(expr) return "evaluate('%s')" % lstr def lambdarepr(expr, **settings): """ Returns a string usable for lambdifying. """ return LambdaPrinter(settings).doprint(expr)
bsd-3-clause
xuxiaoxin/micropython
tests/basics/builtin_hash.py
24
1026
# test builtin hash function print(hash(False)) print(hash(True)) print({():1}) # hash tuple print({1 << 66:1}) # hash big int print(hash in {hash:1}) # hash function try: hash([]) except TypeError: print("TypeError") class A: def __hash__(self): return 123 def __repr__(self): return "a instance" print(hash(A())) print({A():1}) # all user-classes have default __hash__ class B: pass hash(B()) # if __eq__ is defined then default __hash__ is not used class C: def __eq__(self, another): return True try: hash(C()) except TypeError: print("TypeError") # __hash__ must return an int class D: def __hash__(self): return None try: hash(D()) except TypeError: print("TypeError") # __hash__ returning a bool should be converted to an int class E: def __hash__(self): return True print(hash(E())) # __hash__ returning a large number should be truncated class F: def __hash__(self): return 1 << 70 | 1 print(hash(F()) != 0)
mit
mvesper/invenio
modules/webaccess/lib/external_authentication_oauth2.py
3
11289
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2012 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ This module contains functions and methods to authenticate with OAuth2 providers. """ __revision__ = \ "$Id$" import requests from urllib import urlencode from rauth.service import process_token_request from invenio.jsonutils import json, json_unicode_to_utf8 from invenio.config import CFG_SITE_URL from invenio.external_authentication import ExternalAuth from invenio.containerutils import get_substructure class ExternalOAuth2(ExternalAuth): """ Contains methods for authenticate with an OAuth2 provider. """ @staticmethod def __init_req(req): req.g['oauth2_provider_name'] = '' req.g['oauth2_debug'] = 0 req.g['oauth2_msg'] = '' req.g['oauth2_debug_msg'] = '' req.g['oauth2_response'] = None def auth_user(self, username, password, req=None): """ Tries to find email and identity of the user from OAuth2 provider. If it doesn't find any of them, returns (None, None) @param username: Isn't used in this function @type username: str @param password: Isn't used in this function @type password: str @param req: request @type req: invenio.webinterface_handler_wsgi.SimulatedModPythonRequest @rtype: str|NoneType, str|NoneType """ from invenio.webinterface_handler import wash_urlargd from invenio.access_control_config import CFG_OAUTH2_CONFIGURATIONS from rauth.service import OAuth2Service from invenio.access_control_config import CFG_OAUTH2_PROVIDERS self.__init_req(req) args = wash_urlargd(req.form, { 'code': (str, ''), 'provider': (str, '') }) req.g['oauth2_provider_name'] = args['provider'] if not req.g['oauth2_provider_name']: # If provider name isn't given req.g['oauth2_msg'] = 21 return None, None # Some providers doesn't construct return uri properly. # Since the callback uri is: # /youraccount/login?login_method=oauth2&provider=something # they may return to: # /youraccount/login?login_method=oauth2&provider=something?code=# # instead of # /youraccount/login?login_method=oauth2&provider=something&code=# if '?' in req.g['oauth2_provider_name']: (req.g['oauth2_provider_name'], args['code']) = \ ( req.g['oauth2_provider_name'][:req.g['oauth2_provider_name'].index('?')], req.g['oauth2_provider_name'][req.g['oauth2_provider_name'].index('?') + 1 + len("code="):] ) if not req.g['oauth2_provider_name'] in CFG_OAUTH2_PROVIDERS: req.g['oauth2_msg'] = 22 return None, None # Load the configurations to construct OAuth2 service config = CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']] req.g['oauth2_debug'] = config.get('debug', 0) provider = OAuth2Service( name = req.g['oauth2_provider_name'], client_id = config['consumer_key'], client_secret = config['consumer_secret'], access_token_url = config['access_token_url'], authorize_url = config['authorize_url']) data = dict(code = args['code'], client_id = config['consumer_key'], client_secret = config['consumer_secret'], grant_type = "authorization_code", # Construct redirect uri without having '/' character at the # left most of SITE_SECURE_URL redirect_uri = CFG_SITE_URL + '/youraccount/login?' + urlencode({'login_method': 'oauth2', 'provider': req.g['oauth2_provider_name']})) headers = dict(Accept = "application/json") kwargs = dict(data = data, headers = headers) # Get the access token r = provider.get_raw_access_token(method='POST', **kwargs) keys = ['access_token', 'orcid'] try: access_token, orcid = process_token_request(r, json.loads, *keys) token_content = {'access_token': access_token, 'orcid': orcid} except: req.g['oauth2_msg'] = 22 return None, None req.g['oauth2_access_token'] = token_content['access_token'] if req.g['oauth2_debug']: req.g['oauth2_debug_msg'] = str(token_content) + "<br/>" if req.g['oauth2_provider_name'] == 'orcid': req.g['oauth2_orcid'] = token_content['orcid'] email, identity = self._get_user_email_and_id_from_orcid(req) else: # Some providers send the user information and access token together. email, identity = self._get_user_email_and_id(token_content, req) if not identity: profile = provider.request('GET', config['request_url'].format( access_token = token_content['access_token'], id=identity)) req.g['oauth2_access_token'] = token_content['access_token'] if req.g['oauth2_debug']: req.g['oauth2_debug_msg'] += str(profile.content) email, identity = self._get_user_email_and_id(profile.content, req) if identity: # If identity is found, add the name of the provider at the # beginning of the identity because different providers may have # different users with same id. identity = "%s:%s" % (req.g['oauth2_provider_name'], identity) else: req.g['oauth2_msg'] = 23 if req.g['oauth2_debug']: req.g['oauth2_msg'] = "<code>%s</code>" % req.g['oauth2_debug_msg'].replace("\n", "<br/>") return None, None return email, identity def fetch_user_nickname(self, username, password=None, req=None): """ Fetches the OAuth2 provider for nickname of the user. If it doesn't find any, returns None. This function doesn't need username, password or req. They are exist just because this class is derived from ExternalAuth @param username: Isn't used in this function @type username: str @param password: Isn't used in this function @type password: str @param req: Isn't used in this function @type req: invenio.webinterface_handler_wsgi.SimulatedModPythonRequest @rtype: str or NoneType """ from invenio.access_control_config import CFG_OAUTH2_CONFIGURATIONS if req.g['oauth2_provider_name'] and req.g['oauth2_response']: path = None if CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']].has_key( 'nickname' ): path = CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']]['nickname'] if path: return get_substructure(req.g['oauth2_response'], path) else: return None @staticmethod def _get_user_email_and_id(container, req): """ Returns external identity and email address together. Since identity is essential for OAuth2 authentication, if it doesn't find external identity returns None, None. @param container: container which contains email and id @type container: list|dict @rtype str|NoneType, str|NoneType """ from invenio.access_control_config import CFG_OAUTH2_CONFIGURATIONS identity = None email = None #if req.g['oauth2_provider_name'] == 'orcid': if CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']].has_key('id'): path = CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']]['id'] identity = get_substructure(container, path) if identity: if CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']].has_key('email'): path = CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']]\ ['email'] email = get_substructure(container, path) req.g['oauth2_response'] = container return email, identity @staticmethod def _get_user_email_and_id_from_orcid(req): """ Since we are dealing with orcid we can fetch tons of information from the user profile. """ from invenio.access_control_config import CFG_OAUTH2_CONFIGURATIONS profile = requests.get(CFG_OAUTH2_CONFIGURATIONS['orcid']['request_url'].format(id=req.g['oauth2_orcid']), headers={'Accept': 'application/orcid+json', 'Authorization': 'Bearer %s' % req.g['oauth2_access_token']}) orcid_record = req.g['orcid_record'] = json_unicode_to_utf8(profile.json())['orcid-profile'] id = orcid_record['orcid']['value'] emails = orcid_record['orcid-bio'].get('contact-details', {}).get('email', []) if emails: return emails[0], id else: return None, id @staticmethod def get_limited_access_data_from_orcid(orcid_id, access_token): """ Since we are dealing with orcid we can fetch tons of information from the user profile. """ from invenio.access_control_config import CFG_OAUTH2_CONFIGURATIONS profile = requests.get(CFG_OAUTH2_CONFIGURATIONS['orcid']['request_url'].format(id=orcid_id), headers={'Accept': 'application/orcid+json', 'Authorization': 'Bearer %s' % access_token}) if profile.status_code != 200: raise NotImplementedError() orcid_data = json_unicode_to_utf8(profile.json())['orcid-profile'] return orcid_data @staticmethod def get_msg(req): return req.g['oauth2_msg'] def fetch_user_preferences(self, username, password=None, req=None): """Fetch user preferences/settings from the SSO account. the external key will be '1' if the account is external to SSO, otherwise 0 @return: a dictionary. Note: for SSO the parameter are discarded and overloaded by Shibboleth variables """ if req and req.g['oauth2_provider_name'] == 'orcid': return req.g.get('orcid_record', {}) else: raise NotImplementedError()
gpl-2.0
daspots/dasapp
lib/sendgrid/helpers/inbound/config.py
2
1603
"""Setup credentials (.env) and application variables (config.yml)""" import os import yaml class Config(object): """All configuration for this app is loaded here""" def __init__(self, **opts): if os.environ.get('ENV') != 'prod': # We are not in Heroku self.init_environment() """Allow variables assigned in config.yml available the following variables via properties""" self.path = opts.get( 'path', os.path.abspath(os.path.dirname(__file__)) ) with open(self.path + '/config.yml') as stream: config = yaml.load(stream) self._debug_mode = config['debug_mode'] self._endpoint = config['endpoint'] self._host = config['host'] self._keys = config['keys'] self._port = config['port'] @staticmethod def init_environment(): """Allow variables assigned in .env available using os.environ.get('VAR_NAME')""" base_path = os.path.abspath(os.path.dirname(__file__)) if os.path.exists(base_path + '/.env'): for line in open(base_path + '/.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] @property def debug_mode(self): return self._debug_mode @property def endpoint(self): return self._endpoint @property def host(self): return self._host @property def keys(self): return self._keys @property def port(self): return self._port
mit
JazzeYoung/VeryDeepAutoEncoder
theano/scan_module/scan_opt.py
1
103543
""" This module provides optimizations for scan. The Optimization provided in this file: local opt: remove_constants_and_unused_inputs_scan, constant_folding_for_scan2, scan_merge_inouts They are wrapped in in2out to create global opt. global opt: ScanInplaceOptimizer, PushOutNonSeqScan, PushOutSeqScan, PushOutDot1, ScanMerge, ScanSaveMem How the are registered: optdb: scan_eqopt1 (.1), scan_eqopt2(1.6), scan_inplace(75) scan_eqopt1 -> scan_seqopt1 scan_seqopt1 -> in2out(remove_constants_and_unused_inputs_scan)(1), PushOutNonSeqScan(2), PushOutSeqScan(3), PushOutDot1(4) scan_eqopt2 -> They are all global optimizer. (in2out convert local to global). This is important, as the order is important and all global optimizer run before local optimizer in the order they where registered. (So don't change the order we register them!) If we convert to local optimizer, we must convert all of them to local optimizer. But: 1) can ScanMerge be made local? Can we keep only this one global? 2) ScanSaveMem assert that we remove all nodes outputs, we need to keep this. 3) It is ScanSaveMem suppose the the others ran before. I added an assert at one place, but didn't looked for other place. 4) Moving this to local opt could speed up significant this opt, as we pass frequently on all nodes in the graph for no good reason. 5) We register remove_constant_* many places, as some opt create them and let this one clean up the mess. Doing it that way, make things simpler for those already complex opt. in2out(constant_folding), in2out(remove_constants_and_unused_inputs_scan1), ScanMerge, in2out(remove_constants_and_unused_inputs_scan2), in2out(scan_merge_inouts), ScanSaveMem, in2out(remove_constants_and_unused_inputs_scan3) """ from __future__ import absolute_import, print_function, division import logging import copy from sys import maxsize import numpy import theano from theano import tensor, scalar from theano.tensor import opt, get_scalar_constant_value, Alloc, AllocEmpty from theano import gof from theano.compat import OrderedDict from six import integer_types, iteritems from six.moves import xrange from theano.compile import optdb from theano.compile.function_module import deep_copy_op from theano.gof import toolbox, DestroyHandler, InconsistencyError from theano.gof.opt import Optimizer from theano.gof.opt import pre_constant_merge, pre_greedy_local_optimizer from theano.scan_module import scan_op from theano.scan_module import scan_utils from theano.scan_module.scan_utils import equal_computations, find_up, scan_args __docformat__ = 'restructedtext en' __authors__ = ("Razvan Pascanu " "Frederic Bastien " "James Bergstra " "Pascal Lamblin " "Arnaud Bergeron ") __copyright__ = "(c) 2010, Universite de Montreal" __contact__ = "Razvan Pascanu <r.pascanu@gmail>" # Logging function for sending warning or info _logger = logging.getLogger('theano.scan_module.scan_opt') list_opt_slice = [tensor.opt.local_abs_merge, tensor.opt.local_mul_switch_sink, tensor.opt.local_upcast_elemwise_constant_inputs, tensor.opt.local_useless_switch, tensor.opt.constant_folding] def warning(*msg): _logger.warning('WARNING theano.scan: ' + ' '.join(msg)) def info(*msg): _logger.info('INFO theano.scan: ' + ' '.join(msg)) @gof.local_optimizer([scan_op.Scan]) def remove_constants_and_unused_inputs_scan(node): """ Move constants into the inner graph, and remove unused inputs. Constants that are in the outer graph are represented by a free symbolic variable in the inner graph. If we move them into the inner graph, constant-folding can happen in the inner graph. This is applied only on sequences and non-sequences, not on initial states. """ if not isinstance(node.op, scan_op.Scan): return False op = node.op # We only need to take care of sequences and other arguments st = op.n_seqs st += int(sum([len(x) for x in op.tap_array[:(op.n_mit_mot + op.n_mit_sot)]])) st += op.n_sit_sot st += op.n_shared_outs op_ins = op.inputs op_outs = op.outputs # Corresponds to the initial states, which should stay untouched. # We put those variables aside, and put them back at the end. out_stuff_inner = op_ins[op.n_seqs:st] non_seqs = op_ins[st:] st = (op.n_seqs + op.n_mit_mot + op.n_mit_sot + op.n_sit_sot + op.n_nit_sot + op.n_shared_outs + 1) outer_non_seqs = node.inputs[st:] out_stuff_outer = node.inputs[1 + op.n_seqs:st] # To replace constants in the outer graph by clones in the inner graph givens = OrderedDict() # All the inputs of the inner graph of the new scan nw_inner = [] # Same for the outer graph, initialized w/ number of steps nw_outer = [node.inputs[0]] all_ins = gof.graph.inputs(op_outs) for idx in xrange(op.n_seqs): node_inp = node.inputs[idx + 1] if (isinstance(node_inp, tensor.TensorConstant) and node_inp.tag.unique_value is not None): try: # This works if input is a constant that has all entries # equal givens[op_ins[idx]] = node_inp.clone()[0] except TypeError: pass elif op_ins[idx] in all_ins: # Check for identical other sequence identical_seqs = [x for x in nw_outer if scan_utils.equal_computations( [x], [node_inp])] if identical_seqs: index = node.inputs.index(identical_seqs[0]) - 1 givens[op_ins[idx]] = op_ins[index] else: nw_inner.append(op_ins[idx]) nw_outer.append(node_inp) nw_n_seqs = len(nw_inner) # Add outputs stuff nw_inner += out_stuff_inner nw_outer += out_stuff_outer # Look through non sequences nw_inner_nonseq = [] nw_outer_nonseq = [] for idx, (nw_in, nw_out) in enumerate(zip(non_seqs, outer_non_seqs)): if isinstance(nw_out, tensor.Constant): givens[nw_in] = nw_out.clone() elif nw_in in all_ins: # Indices of elements of nw_outer_nonseq that are equivalent # to nw_out. identical_nonseq_idx = [ i for (i, x) in enumerate(nw_outer_nonseq) if scan_utils.equal_computations([x], [nw_out])] if identical_nonseq_idx: givens[nw_in] = nw_inner_nonseq[identical_nonseq_idx[0]] else: nw_inner_nonseq.append(nw_in) nw_outer_nonseq.append(nw_out) nw_inner.extend(nw_inner_nonseq) nw_outer.extend(nw_outer_nonseq) if len(nw_inner) != len(op_ins): op_outs = scan_utils.clone(op_outs, replace=givens) nw_info = copy.deepcopy(op.info) nw_info['n_seqs'] = nw_n_seqs # DEBUG CHECK nwScan = scan_op.Scan(nw_inner, op_outs, nw_info) nw_outs = nwScan(*nw_outer, **dict(return_list=True)) return OrderedDict([("remove", [node])] + list(zip(node.outputs, nw_outs))) else: return False # This is a global opt for historical reason # It should be possible to change it to a local opt. class PushOutNonSeqScan(gof.Optimizer): """ A global optimizer for pushing out the variables inside the scan that depend only on non-sequences. """ def __init__(self): gof.Optimizer.__init__(self) def add_requirements(self, fgraph): fgraph.attach_feature(gof.toolbox.ReplaceValidate()) def apply(self, fgraph): nodelist = [x for x in fgraph.toposort() if isinstance(x.op, scan_op.Scan)] for node in nodelist: self.process_node(fgraph, node) def process_node(self, fgraph, node): """ IMPORTANT NOTE: This function uses set and dictionary data structures. By default they are not ordered for efficiency reasons. Take care and make sure of changing them with their Ordered counterparts if you need to iterate over these variables. """ # this flag tells if there was any change during the last iterations clean_inputs, clean_outputs = scan_utils.reconstruct_graph( node.op.inputs, node.op.outputs) local_fgraph_topo = theano.gof.graph.io_toposort(clean_inputs, clean_outputs) local_fgraph_outs_set = set(clean_outputs) local_fgraph_outs_map = dict([(v, k) for k, v in enumerate(clean_outputs)]) to_remove_set = set() to_replace_set = set() to_replace_map = OrderedDict() def add_to_replace(y): to_replace_set.add(y) to_replace_map[y] = add_to_replace.n add_to_replace.n += 1 add_to_replace.n = 0 replace_with_in = [] replace_with_out = [] op = node.op # Construct the list of non_sequences to simplify a few things inner_non_seqs = op.inner_non_seqs(clean_inputs) inner_non_seqs_set = set(inner_non_seqs) inner_non_seqs_map = dict([(v, k) for k, v in enumerate(inner_non_seqs)]) outer_non_seqs = op.outer_non_seqs(node.inputs) inner_seqs = op.inner_seqs(clean_inputs) outer_seqs = op.outer_seqs(node.inputs) assert len(inner_non_seqs) == len(outer_non_seqs) assert len(inner_seqs) == len(outer_seqs) for nd in local_fgraph_topo: if ( # we haven't already looked at this node nd not in to_remove_set and all([((x in inner_non_seqs_set) or (x.owner in to_remove_set) or isinstance(x, tensor.Constant)) for x in nd.inputs]) and # we can do this because the assumption is that a # viewOp or deepCopyOp will be just at the end of the # function and not somewhere in the middle .. not isinstance(nd.op, theano.compile.ViewOp) and not isinstance(nd.op, theano.compile.DeepCopyOp)): # We have a candidate node to removable # Step 1. Reconstruct it on outside to_remove_set.add(nd) outside_ins = [] for x in nd.inputs: if x in inner_non_seqs_set: _idx = inner_non_seqs_map[x] outside_ins.append(outer_non_seqs[_idx]) elif x in to_replace_set: outside_ins.append(replace_with_out[to_replace_map[x]]) elif isinstance(x, theano.Constant): outside_ins.append(x.clone()) else: raise Exception( ('Error in the `scan_pushout_non_seq_' 'operations`. The optimization tries ' 'to move some computation fron scan ' 'which is not allowed to move. Report ' 'this on theano-users list'), x) outside_ins = [x.type.filter_variable(y) for x, y in zip(nd.inputs, outside_ins)] # Do not call make_node for test_value nw_outer_node = nd.op(*outside_ins, **dict(return_list=True))[0].owner # Step 2. Create variables for replacements for idx, y in enumerate(nd.outputs): y_place_holder = scan_utils.safe_new(y, '_replace') add_to_replace(y) replace_with_in.append(y_place_holder) assert isinstance(y, type(nw_outer_node.outputs[idx])) replace_with_out.append(nw_outer_node.outputs[idx]) # We need to check all candidate replacements and choose those that # make sense for us # Step 1. which elements of `to_replace` are used by remaining # components of the inner function clean_to_replace = [] clean_replace_with_in = [] clean_replace_with_out = [] existent_nodes = [nd for nd in local_fgraph_topo if nd not in to_remove_set] existent_nodes_set = set(existent_nodes) to_keep_set = set([]) for nd in existent_nodes: to_keep_set.update(nd.inputs) for out, idx in to_replace_map.items(): if ( # If types are different, conversion Op will be inserted, # and it may trigger an infinite loop. replace_with_in[idx].type == out.type and out in to_keep_set and out.owner not in existent_nodes_set): clean_to_replace.append(out) clean_replace_with_in.append(replace_with_in[idx]) clean_replace_with_out.append(replace_with_out[idx]) if len(clean_to_replace) > 0: # We can finally put an end to all this madness givens = OrderedDict() nw_outer = [] nw_inner = [] for to_repl, repl_in, repl_out in zip(clean_to_replace, clean_replace_with_in, clean_replace_with_out): if isinstance(repl_out, theano.Constant): repl_in = repl_out.clone() else: nw_inner.append(repl_in) nw_outer.append(repl_out) givens[to_repl] = repl_in op_outs = scan_utils.clone(clean_outputs, replace=givens) op_ins = clean_inputs + nw_inner # Reconstruct node nwScan = scan_op.Scan(op_ins, op_outs, op.info) # Do not call make_node for test_value nw_node = nwScan(*(node.inputs + nw_outer), **dict(return_list=True))[0].owner fgraph.replace_all_validate_remove( list(zip(node.outputs, nw_node.outputs)), remove=[node], reason='scanOp_pushout_nonseqs_ops') return True elif not to_keep_set: # Nothing in the inner graph should be kept replace_with = OrderedDict() for out, idx in to_replace_map.items(): if out in local_fgraph_outs_set: x = node.outputs[local_fgraph_outs_map[out]] y = replace_with_out[idx] shape = [shp for shp in y.shape] replace_with[x] = tensor.alloc(y, node.inputs[0], *shape) # We need to add one extra dimension to the outputs # because the scan op expects for a tensor3, to which an # subtensor is applied that takes only the last element if replace_with: if len(node.outputs) == len(replace_with): # Every output of the node has a replacement, the Scan # node can be removed from the graph fgraph.replace_all_validate_remove( replace_with.items(), remove=[node], reason='scanOp_pushout_nonseqs_ops') else: # The node has some outputs for which no replacement has # been established. This can occur for outputs that are # not produced by apply nodes (since the optimizations # only visits apply nodes) such as constants or inputs # passed directly as outputs. The replacements can be # performed but the Scan node can't be removed at this # point. fgraph.replace_all_validate( replace_with.items(), reason='scanOp_pushout_nonseqs_ops') else: return False # This is a global opt for historical reason # It should be possible to change it to a local opt. class PushOutSeqScan(gof.Optimizer): """ A global optimizer for pushing out the variables inside the scan that depend only on constants and sequences. """ def __init__(self): gof.Optimizer.__init__(self) def add_requirements(self, fgraph): fgraph.attach_feature(gof.toolbox.ReplaceValidate()) def apply(self, fgraph): nodelist = [x for x in fgraph.toposort() if isinstance(x.op, scan_op.Scan)] for node in nodelist: self.process_node(fgraph, node) def process_node(self, fgraph, node): """ IMPORTANT NOTE: This function uses set and dictionary data structure. By default they are not ordered for efficiency reasons. Take care and make sure of changing them to Ordered versions if you need to iterate over those variables. """ # this flag tells if there was any change during the last iterations clean_inputs, clean_outputs = scan_utils.reconstruct_graph( node.op.inputs, node.op.outputs) local_fgraph_topo = theano.gof.graph.io_toposort(clean_inputs, clean_outputs) local_fgraph_outs_set = set(clean_outputs) local_fgraph_outs_map = dict([(v, k) for k, v in enumerate(clean_outputs)]) to_remove_set = set() to_replace_set = set() to_replace_map = OrderedDict() def add_to_replace(y): to_replace_set.add(y) to_replace_map[y] = add_to_replace.n add_to_replace.n += 1 add_to_replace.n = 0 replace_with_in = [] replace_with_out = [] op = node.op # Construct the list of non_sequences to simplify a few things inner_non_seqs = op.inner_non_seqs(clean_inputs) inner_non_seqs_set = set(inner_non_seqs) inner_non_seqs_map = dict([(v, k) for k, v in enumerate(inner_non_seqs)]) outer_non_seqs = op.outer_non_seqs(node.inputs) inner_seqs = op.inner_seqs(clean_inputs) inner_seqs_set = set(inner_seqs) inner_seqs_map = dict([(v, k) for k, v in enumerate(inner_seqs)]) outer_seqs = op.outer_seqs(node.inputs) assert len(inner_non_seqs) == len(outer_non_seqs) assert len(inner_seqs) == len(outer_seqs) for nd in local_fgraph_topo: if (nd not in to_remove_set and all([(x in inner_non_seqs_set) or (x.owner in to_remove_set) or isinstance(x, tensor.Constant) or (x in inner_seqs_set) for x in nd.inputs]) and isinstance(nd.op, theano.tensor.Elemwise)): outside_ins = [] depends_on_seqs = False for x in nd.inputs: if x in inner_non_seqs_set: _idx = inner_non_seqs_map[x] outside_ins.append(outer_non_seqs[_idx]) elif x in inner_seqs_set: outside_ins.append(outer_seqs[inner_seqs_map[x]]) depends_on_seqs = True elif x in to_replace_set: outside_ins.append(replace_with_out[ to_replace_map[x]]) depends_on_seqs = True elif isinstance(x, theano.Constant): outside_ins.append(x.clone()) else: raise Exception( ('Error in the `scan_pushout_seq_' 'operations`. The optimization tries ' 'to move some computation fron scan ' 'which is not allowed to move. Report ' 'this on theano-users list'), x) if not depends_on_seqs: # Removing this node from the inner graph of scan # should be handled by the PushOutNonSeqScan # optimization. The current optimization only tries # to pull sequence-dependant computation out of # scan. continue to_remove_set.add(nd) # Do not call make_node for test_value nw_outer_node = nd.op(*outside_ins, **dict(return_list=True))[0].owner # Step 2. Create variables for replacements for idx, y in enumerate(nd.outputs): y_place_holder = scan_utils.safe_new(y, '_replace') add_to_replace(y) replace_with_in.append(y_place_holder) replace_with_out.append(nw_outer_node.outputs[idx]) elif (nd not in to_remove_set and isinstance(nd.op, theano.tensor.DimShuffle) and (nd.inputs[0] in inner_seqs_set or nd.inputs[0].owner in to_remove_set)): to_remove_set.add(nd) x = nd.inputs[0] if x in inner_seqs_set: outside_ins = outer_seqs[inner_seqs_map[x]] elif x in to_replace_set: outside_ins = replace_with_out[to_replace_map[x]] new_ord = (0,) for old_ord in nd.op.new_order: if (old_ord == 'x'): new_ord += (old_ord,) else: new_ord += (old_ord + 1,) new_outer = outside_ins.dimshuffle(new_ord) y = nd.outputs[0] y_place_holder = scan_utils.safe_new(y, '_replace') add_to_replace(y) replace_with_in.append(y_place_holder) replace_with_out.append(new_outer) if hasattr(new_outer.tag, "test_value"): new_sh = new_outer.tag.test_value.shape ref_sh = (outside_ins.tag.test_value.shape[0],) ref_sh += nd.outputs[0].tag.test_value.shape assert new_sh == ref_sh # We need to check all candidate replacements and choose those that # make sense for us # Step 1. which elements of `to_replace` are used by remaining # components of the inner function clean_to_replace = [] clean_replace_with_in = [] clean_replace_with_out = [] existent_nodes = [nd for nd in local_fgraph_topo if nd not in to_remove_set] existent_nodes_set = set(existent_nodes) to_keep_set = set([]) for nd in existent_nodes: to_keep_set.update(nd.inputs) for out, idx in to_replace_map.items(): if (out in to_keep_set and out.owner not in existent_nodes_set and # If types are different, conversion Op will be inserted, # and it may trigger an infinite loop. replace_with_in[idx].type == out.type): clean_to_replace.append(out) clean_replace_with_in.append(replace_with_in[idx]) clean_replace_with_out.append(replace_with_out[idx]) if len(clean_to_replace) > 0: # We can finally put an end to all this madness givens = OrderedDict() nw_outer = [] nw_inner = [] for to_repl, repl_in, repl_out in zip(clean_to_replace, clean_replace_with_in, clean_replace_with_out): if isinstance(repl_out, theano.Constant): repl_in = repl_out.clone() else: nw_inner.append(repl_in) nw_outer.append(repl_out) givens[to_repl] = repl_in op_outs = scan_utils.clone(clean_outputs, replace=givens) op_ins = nw_inner + clean_inputs # Reconstruct node nw_info = op.info.copy() nw_info['n_seqs'] += len(nw_inner) nwScan = scan_op.Scan(op_ins, op_outs, nw_info) # Do not call make_node for test_value nw_node = nwScan(*(node.inputs[:1] + nw_outer + node.inputs[1:]), **dict(return_list=True))[0].owner fgraph.replace_all_validate_remove( list(zip(node.outputs, nw_node.outputs)), remove=[node], reason='scanOp_pushout_seqs_ops') return True elif (not to_keep_set and not op.as_while and not op.outer_mitmot(node)): # Nothing in the inner graph should be kept replace_with = OrderedDict() for out, idx in to_replace_map.items(): if out in local_fgraph_outs_set: x = node.outputs[local_fgraph_outs_map[out]] _y = replace_with_out[idx] ls = clean_outputs if out in op.inner_mitsot_outs(ls): odx = op.inner_mitsot_outs(ls).index(out) inp = op.outer_mitsot(node)[odx] st = abs(numpy.min(op.mitsot_taps())) y = tensor.set_subtensor(inp[st:], _y) elif out in op.inner_sitsot_outs(ls): odx = op.inner_sitsot_outs(ls).index(out) inp = op.outer_sitsot(node)[odx] y = tensor.set_subtensor(inp[1:], _y) elif out in op.inner_nitsot_outs(ls): y = _y else: y = _y[-1] replace_with[x] = y # We need to add one extra dimension to the outputs if replace_with and len(replace_with) == len(node.outputs): fgraph.replace_all_validate_remove( list(replace_with.items()), remove=[node], reason='scanOp_pushout_seqs_ops') return True else: return False class PushOutScanOutput(gof.Optimizer): """ This is an optimization that can push operations performed at the end of the inner graph of scan to outside of scan. """ def __init__(self): gof.Optimizer.__init__(self) def add_requirements(self, fgraph): fgraph.attach_feature(gof.toolbox.ReplaceValidate()) def apply(self, fgraph): # Don't perform the optimization on as_while scans. Because these scans # don't run for a predetermined number of steps, handling them is # more complicated and this optimization doesn't support it at the # moment. nodelist = [x for x in fgraph.toposort() if (isinstance(x.op, scan_op.Scan) and not x.op.as_while)] for node in nodelist: # Process the node as long as something gets optimized while node is not None: node = self.process_node(fgraph, node) def process_node(self, fgraph, node): op = node.op # Use scan_args to parse the inputs and outputs of scan for ease of # use args = scan_args(node.inputs, node.outputs, op.inputs, op.outputs, op.info) new_scan_node = None clients = {} local_fgraph_topo = theano.gof.graph.io_toposort(args.inner_inputs, args.inner_outputs, clients=clients) for nd in local_fgraph_topo: if (isinstance(nd.op, theano.tensor.elemwise.Elemwise) and isinstance(nd.op.scalar_op, scalar.Add) and nd.out in args.inner_out_sit_sot and self.inner_sitsot_only_last_step_used(nd.out, args)): # Ensure that one of the input to the add is the output of # the add from a previous iteration of the inner function sitsot_idx = args.inner_out_sit_sot.index(nd.out) if args.inner_in_sit_sot[sitsot_idx] in nd.inputs: # Ensure that the other input to the add is a dot product # between 2 matrices which will become a tensor3 and a # matrix if pushed outside of the scan. Also make sure # that the output of the Dot is ONLY used by the 'add' # otherwise doing a Dot in the outer graph will only # duplicate computation. sitsot_in_idx = nd.inputs.index(args.inner_in_sit_sot[ sitsot_idx]) # 0 if sitsot_in_idx==1, 1 if sitsot_in_idx==0 dot_in_idx = 1 - sitsot_in_idx dot_input = nd.inputs[dot_in_idx] if (dot_input.owner is not None and isinstance(dot_input.owner.op, theano.tensor.Dot) and len(clients[dot_input]) == 1 and dot_input.owner.inputs[0].ndim == 2 and dot_input.owner.inputs[1].ndim == 2 and self.get_outer_ndim(dot_input.owner.inputs[0], args) == 3 and self.get_outer_ndim(dot_input.owner.inputs[1], args) == 3): # The optimization can be be applied in this case. # Move out of scan the two inputs to the Dot and # perform a dot outside of scan on these two inputs inner_dot_inputs = nd.inputs[dot_in_idx].owner.inputs (outer_dot_inputs, new_scan_node, new_scan_args) = \ self.push_out_inner_vars(fgraph, inner_dot_inputs, node, args) # Collapse some of the dimensions of the tensors # so that they become matrices. This is because a # dot is usually faster on two large matrices than # a bunch of small ones outer_dot_inputs[0] = theano.tensor.flatten( outer_dot_inputs[0].dimshuffle(1, 0, 2), outdim=2) shape_input1 = theano.tensor.shape(outer_dot_inputs[1]) outer_dot_inputs[1] =\ outer_dot_inputs[1].reshape((shape_input1[0] * shape_input1[1], shape_input1[2])) # Perform the dot on the newly obtained matrices and # add the initial value outer_dot_output = theano.tensor.dot(*outer_dot_inputs) init_value = new_scan_args.outer_in_sit_sot[sitsot_idx][0] replacement = outer_dot_output + init_value # Alter the outer graph to use the output of the # external Dot instead of the output of scan # Modify the outer graph to add the outer Dot outer_sitsot = new_scan_args.outer_out_sit_sot[sitsot_idx] subtensor_node = outer_sitsot.clients[0][0] outer_sitsot_last_step = subtensor_node.outputs[0] fgraph.replace_all([ (outer_sitsot_last_step, replacement)], reason="scanOp_pushout_output") break return new_scan_node def inner_sitsot_only_last_step_used(self, var, scan_args): """ Given a inner nit_sot output of scan, return True iff the outer nit_sot output has only one client and that client is a Subtensor instance that takes only the last step (last element along the first axis). """ idx = scan_args.inner_out_sit_sot.index(var) outer_var = scan_args.outer_out_sit_sot[idx] if len(outer_var.clients) == 1: client = outer_var.clients[0][0] if (client != 'output' and isinstance(client.op, theano.tensor.Subtensor)): lst = theano.tensor.subtensor.get_idx_list( client.inputs, client.op.idx_list) if (len(lst) == 1 and theano.tensor.extract_constant(lst[0]) == -1): return True return False def get_outer_ndim(self, var, scan_args): # Given a variable, determine the number of dimension it would have if # it was pushed out of scan if (var in scan_args.inner_in_non_seqs or isinstance(var, theano.Constant)): outer_ndim = var.ndim else: outer_ndim = var.ndim + 1 return outer_ndim def push_out_inner_vars(self, fgraph, inner_vars, old_scan_node, old_scan_args): outer_vars = [None] * len(inner_vars) new_scan_node = old_scan_node new_scan_args = old_scan_args # For the inner_vars that already exist in the outer graph, # simply obtain a reference to them for idx in range(len(inner_vars)): var = inner_vars[idx] if var in old_scan_args.inner_in_seqs: idx_seq = old_scan_args.inner_in_seqs.index(var) outer_vars[idx] = old_scan_args.outer_in_seqs[idx_seq] elif var in old_scan_args.inner_in_non_seqs: idx_non_seq = old_scan_args.inner_in_non_seqs.index(var) outer_vars[idx] = old_scan_args.outer_in_non_seqs[idx_non_seq] elif isinstance(var, theano.Constant): outer_vars[idx] = var.clone() elif var in old_scan_args.inner_out_nit_sot: idx_nitsot = old_scan_args.inner_out_nit_sot.index(var) outer_vars[idx] = old_scan_args.outer_out_nit_sot[idx_nitsot] # For the inner_vars that don't already exist in the outer graph, add # them as new nitsot outputs to the scan node. idx_add_as_nitsots = [i for i in range(len(outer_vars)) if outer_vars[i] is None] add_as_nitsots = [inner_vars[idx] for idx in idx_add_as_nitsots] if len(add_as_nitsots) > 0: new_scan_node = self.add_nitsot_outputs(fgraph, old_scan_node, old_scan_args, add_as_nitsots) new_scan_args = scan_args(new_scan_node.inputs, new_scan_node.outputs, new_scan_node.op.inputs, new_scan_node.op.outputs, new_scan_node.op.info) new_outs = new_scan_args.outer_out_nit_sot[-len(add_as_nitsots):] for i in range(len(new_outs)): outer_vars[idx_add_as_nitsots[i]] = new_outs[i] return outer_vars, new_scan_node, new_scan_args def add_nitsot_outputs(self, fgraph, old_scan_node, old_scan_args, new_outputs_inner): nb_new_outs = len(new_outputs_inner) # Create the initial values for the new nitsot outputs # (the initial value is the nb of steps to store. For a nistot, # it should be the number of steps performed by scan) new_nitsots_initial_value = [old_scan_node.inputs[0] for i in range(nb_new_outs)] # Create the scan_args corresponding to the new scan op to # create new_scan_args = copy.copy(old_scan_args) new_scan_args.inner_out_nit_sot.extend(new_outputs_inner) new_scan_args.outer_in_nit_sot.extend(new_nitsots_initial_value) # Create the scan op from the scan_args new_scan_op = scan_op.Scan(new_scan_args.inner_inputs, new_scan_args.inner_outputs, new_scan_args.info) # Create the Apply node for the scan op new_scan_node = new_scan_op(*new_scan_args.outer_inputs, **dict(return_list=True))[0].owner # Modify the outer graph to make sure the outputs of the new scan are # used instead of the outputs of the old scan new_node_new_outputs_idx = (len(old_scan_args.outer_outputs) - len(old_scan_args.outer_out_shared)) new_node_old_outputs = ( new_scan_node.outputs[:new_node_new_outputs_idx] + new_scan_node.outputs[new_node_new_outputs_idx + nb_new_outs:]) fgraph.replace_all_validate_remove( list(zip(old_scan_node.outputs, new_node_old_outputs)), remove=[old_scan_node], reason='scanOp_pushout_output') return new_scan_node class ScanInplaceOptimizer(Optimizer): """ Graph optimizer for Scan (makes it run inplace). """ def __init__(self, typeInfer=None, gpu_flag=False, gpua_flag=False): Optimizer.__init__(self) self.typeInfer = typeInfer self.gpu_flag = gpu_flag self.gpua_flag = gpua_flag def add_requirements(self, fgraph): fgraph.attach_feature(toolbox.ReplaceValidate()) fgraph.attach_feature(DestroyHandler()) def attempt_scan_inplace(self, fgraph, node, output_indices, alloc_ops): """Attempts to replace a Scan node by one which computes the specified outputs inplace. Parameters ---------- fgraph : FunctionGraph Function graph in which to attempt the replacement node : Apply node Scan node to replace by an inplace version output_indices : list of integers Indices of the outputs to attempt to compute inplace alloc_ops : list of Op classes Classes that represent operation that allocate new memory and that the optimization should duplicate so it can operate inplace on them. """ op = node.op info = copy.deepcopy(op.info) if 'destroy_map' not in info: info['destroy_map'] = OrderedDict() for out_idx in output_indices: info['destroy_map'][out_idx] = [out_idx + 1 + op.info['n_seqs']] # inputs corresponding to sequences and n_steps ls_begin = node.inputs[:1 + op.n_seqs] ls = op.outer_mitmot(node.inputs) ls += op.outer_mitsot(node.inputs) ls += op.outer_sitsot(node.inputs) ls_end = op.outer_shared(node.inputs) ls_end += op.outer_nitsot(node.inputs) ls_end += op.outer_non_seqs(node.inputs) # In `ls`, duplicate any input which has more then one client and is # the output of an eligible allocation op for i in range(len(ls)): inp = ls[i] if (len(inp.clients) > 1 and inp.owner and isinstance(inp.owner.op, alloc_ops)): ls[i] = inp.owner.op(*inp.owner.inputs) n_outs = len(ls) for idx in xrange(n_outs): if ls[idx] in ls[:idx]: ls[idx] = deep_copy_op(ls[idx]) inputs = ls_begin + ls + ls_end if self.typeInfer is None: typeConstructor = None else: typeConstructor = self.typeInfer(node) new_op = scan_op.Scan(op.inputs, op.outputs, info, typeConstructor=typeConstructor) # Do not call make_node for test_value new_outs = new_op(*inputs, **dict(return_list=True)) try: fgraph.replace_all_validate_remove( list(zip(node.outputs, new_outs)), remove=[node], reason='scanOp_make_inplace') return new_outs[0].owner except InconsistencyError: # Failed moving output to be computed inplace return node def apply(self, fgraph): # Depending on the values of gpu_flag and gpua_flag, get the list of # memory allocation ops that the optimization should be able to handle alloc_ops = (Alloc, AllocEmpty) if self.gpu_flag: alloc_ops += (theano.sandbox.cuda.GpuAlloc, theano.sandbox.cuda.GpuAllocEmpty) if self.gpua_flag: # gpuarray might be imported but not its GpuAlloc and # GpuAllopEmpty ops. try: alloc_ops += (theano.gpuarray.GpuAlloc, theano.gpuarray.GpuAllocEmpty) except: pass nodes = fgraph.toposort()[::-1] scan_nodes = [x for x in nodes if (isinstance(x.op, scan_op.Scan) and x.op.info['gpu'] == self.gpu_flag and x.op.info['gpua'] == self.gpua_flag)] for scan_idx in xrange(len(scan_nodes)): # First attempt to make the Scan compute inplace every recurrent # output that seems like it could be computed inplace. If that # fails, go through these outputs individually, trying each of # them. original_node = scan_nodes[scan_idx] op = original_node.op n_outs = (op.info['n_mit_mot'] + op.info['n_mit_sot'] + op.info['n_sit_sot']) # Generate a list of outputs on which the node could potentially # operate inplace. out_indices = [] for out_idx in range(n_outs): inp_idx = 1 + op.n_seqs + out_idx inp = original_node.inputs[inp_idx] # If the input is from an eligible allocation node, attempt to # be inplace on it, even if other nodes are modifying it # inplace. if inp.owner and isinstance(inp.owner.op, alloc_ops): out_indices.append(out_idx) continue # If the input is not from an eligible allocation node, only # attempt to be inplace on it if nothing else is currently # inplace on it. input_used_inplace = False for c in original_node.inputs[inp_idx].clients: client = c[0] # Get the indices of this client's inputs on which it # operates inplace if hasattr(client.op, 'destroy_map'): # This flattens the content of destroy_map.values() # which is a list of lists inplace_inp_indices = sum(client.op.destroy_map.values(), []) inplace_inps = [client.inputs[i] for i in inplace_inp_indices] if original_node.inputs[inp_idx] in inplace_inps: input_used_inplace = True break if not input_used_inplace: out_indices.append(out_idx) node = self.attempt_scan_inplace(fgraph, scan_nodes[scan_idx], out_indices, alloc_ops) if node is original_node: # Making the scan compute all plausible recurrent outputs # inplace has failed. Attempt all plausible recurrent output # individually. for pos in out_indices: node = self.attempt_scan_inplace(fgraph, node, [pos], alloc_ops) class ScanSaveMem(gof.Optimizer): """ Graph Optimizer that reduces scan memory consumption. """ def __init__(self): gof.Optimizer.__init__(self) def add_requirements(self, fgraph): fgraph.attach_feature(gof.toolbox.ReplaceValidate()) def process_node(self, fgraph, node): # helpful functions def select_min(x, y): if x is None: return y if y is None: return x return tensor.minimum(x, y) def select_max(x, y): if x is None: return y if y is None: return x return tensor.maximum(x, y) def sanitize(x): if x is None: return None else: return tensor.as_tensor_variable(x) if hasattr(fgraph, 'shape_feature'): shape_of = node.fgraph.shape_feature.shape_of else: # Each access to shape_of is in a try..except block in order to # use a default version when the variable is not in the shape_of # dictionary. shape_of = OrderedDict() # 1. Initialization of variables # Note 1) We do not actually care about outputs representing shared # variables (those have no intermediate values) so it is safer to # ignore them and not change them in any way. To simplify the # optimizations I construct the variable ``c_outs`` ( that counts # outputs up to those we care) and the list ``init_l`` which for any # output we care says the length of its initial state. Note that # defining ``init_l`` for mit_mot sequences is a bit trickier but # it is safe to set it to 0 op = node.op c_outs = op.n_mit_mot + op.n_mit_sot + op.n_sit_sot + op.n_nit_sot init_l = [0 for x in xrange(op.n_mit_mot)] init_l += [abs(min(v)) for v in op.tap_array[op.n_mit_mot:]] init_l += [0 for x in xrange(op.n_nit_sot)] # 2. Check the clients of each output and see for how many steps # does scan need to run # This comparison checks if there is any uncounted output, which # can only be an output corresponding to a shared variable # 2.1 Initialize # global_nsteps is a dictionary having two fields ( 'real' deals # with int values, 'sym' with symbolic ones) or None # given that a scan op has k outputs o_1, .. o_k and each # output has n_j clients c_1^1, c_1^2, .. c_1^{n_1}, c_2^1, .., # global_nsteps is None if any of the clients is different # from a subtensor or its real and sym field equal to # max(c_i_j.idx_list[0].stop), meaning store up to which maximal # index(step) for any output scan actually needs to compute # In other words n_steps should be equal to this maximal ! # Note: if we have a shared variable that gets updated at every step # of the loop, reducing the number of steps will affect the the # value of the shared variable after the loop so we need not to # change the number of steps in that case. To do this we set # global_nsteps to None which is seen as a flag that nothing needs # to be done assert len(node.outputs) >= c_outs if len(node.outputs) == c_outs: global_nsteps = {'real': -1, 'sym': []} else: global_nsteps = None # Keeps track of the original slices that each client represent slices = [None for o in node.outputs] # A list for each output indicating how many intermediate values # should be stored. If negative it means none of the intermediate # values (i.e. the output can be removed since it is not used # afterwards in the computations), if 0 it means that all # intermediate values are required, otherwise is up to that number # of intermediate values # Note that for mit_mot outputs and shared outputs we can not change # the number of intermediate steps stored without affecting the # result of the op store_steps = [0 for o in xrange(op.n_mit_mot)] store_steps += [-1 for o in node.outputs[op.n_mit_mot:c_outs]] # Flag that says if an input has changed and we need to do something # or not flag_store = False # 2.2 Loop over the clients for i, out in enumerate(node.outputs[:c_outs]): # look at all its clients slices[i] = [] for cl, _ in out.clients: # 2.1 outputs of the function # => output needs all its intermediate values if type(cl) == str: # if the node is actually an output, then # we need to store the entire thing global_nsteps = None slices[i] = None break # 2.2 non-subtensor nodes # => output needs all its intermediate values elif not isinstance(cl.op, tensor.Subtensor): global_nsteps = None slices[i] = None break # 2.3 subtensor nodes # => output might need to store just a subset of its values else: # 2.3.1 extract idx list of subtensor this_slice = tensor.get_idx_list(cl.inputs, cl.op.idx_list) if this_slice is None: # if unable to extract idx_list # => outputs needs all its intermediate values global_nsteps = None slices[i] = None break # 2.3.2 extract the begin/end of the first dimension if i >= op.n_mit_mot: try: length = shape_of[out][0] except KeyError: length = node.inputs[0] + init_l[i] else: try: length = shape_of[out][0] except KeyError: length = out.shape[0] cf_slice = tensor.get_canonical_form_slice( this_slice[0], length) slices[i] += [(cf_slice, this_slice)] if (isinstance(this_slice[0], slice) and this_slice[0].stop is None): global_nsteps = None if isinstance(cf_slice[0], slice): stop = tensor.basic.extract_constant(cf_slice[0].stop) else: stop = tensor.basic.extract_constant(cf_slice[0]) + 1 if stop == maxsize or stop == length: stop = None else: # there is a **gotcha** here ! Namely, scan returns an # array that contains the initial state of the output # as well. Which means that if have a initial state of # length 3, and you look for 5 steps you get an output # y of length 8. If you only use y[:5], this does not # mean that you only need to loop for 5 steps but # actually only for 2 steps ( the first 3 are the # initial state) stop = stop - init_l[i] # 2.3.3 we might get away with less number of steps if stop is not None and global_nsteps is not None: # yes if it is a tensor if isinstance(stop, tensor.Variable): global_nsteps['sym'] += [stop] # not if it is maxsize elif (type(stop) in integer_types and stop == maxsize): global_nsteps = None # yes if it is a int k, 0 < k < maxsize elif (type(stop) in integer_types and global_nsteps['real'] < stop): global_nsteps['real'] = stop # yes if it is a int k, 0 < k < maxsize elif (type(stop) in integer_types and stop > 0): pass # not otherwise else: global_nsteps = None # 2.3. Analyze global_nsteps to figure out for how many steps scan # needs to iterate if global_nsteps is not None: nw_steps = node.inputs[0] # there are some symbolic tensors that limit the number of # steps if len(global_nsteps['sym']) == 0: sym_steps = None else: sym_steps = global_nsteps['sym'][0] for c in global_nsteps['sym'][1:]: sym_steps = tensor.maximum(sym_steps, c) if global_nsteps['real'] >= 0: real_steps = global_nsteps['real'] else: real_steps = None nw_steps = select_min(select_max(sym_steps, real_steps), node.inputs[0]) # Make sure the ScanSaveMem optimization never makes the new # number of steps to be 0 (this could happen, for instance, if # the optimization detects that the outputs of the Scan go through # subtensor nodes that end up taking no elements) because Scan with # 0 iterations are not supported. Make sure the new number of steps # is at least 1. nw_steps = select_max(nw_steps, 1) else: nw_steps = node.inputs[0] global_nsteps = None # 2.4 Loop over the clients again now looking just to see how many # intermediate steps to store for i, out in enumerate(node.outputs[:c_outs]): # look at all its clients for cl, _ in out.clients: if type(cl) == str: store_steps[i] = 0 break elif not isinstance(cl.op, tensor.Subtensor): store_steps[i] = 0 break else: this_slice = tensor.get_idx_list(cl.inputs, cl.op.idx_list) if this_slice is None: store_steps[i] = 0 break if (isinstance(this_slice[0], slice) and this_slice[0].start is None): store_steps[i] = 0 break if i > op.n_mit_mot: length = node.inputs[0] + init_l[i] else: try: length = shape_of[out][0] except KeyError: length = out.shape[0] cf_slice = tensor.get_canonical_form_slice( this_slice[0], length) if isinstance(cf_slice[0], slice): start = tensor.basic.extract_constant( cf_slice[0].start) else: start = tensor.basic.extract_constant(cf_slice[0]) if start == 0 or store_steps[i] == 0: store_steps[i] = 0 else: # The "+ 1" is because of the memory pre-allocation # mechanism used to in the Scan op to reduce overhead. # To prevent aliasing between the inputs and outputs # of recurrent states, it requires that the buffer be # large enough to that, the new state and the oldest # tap needed don't occupy the sample place in the # circular buffer. For now, this only needs to be done # for mitsots and sitsots (because mitmots are not # currently supported by the mechanism) and only if # the pre-allocation mechanism is activated. prealloc_outs = theano.config.scan.allow_output_prealloc first_mitsot_idx = node.op.n_mit_mot last_sitsot_idx = (node.op.n_mit_mot + node.op.n_mit_sot + node.op.n_sit_sot - 1) preallocable_output = (first_mitsot_idx <= i <= last_sitsot_idx) if (prealloc_outs and preallocable_output): pval = select_max(nw_steps - start + init_l[i], init_l[i] + 1) else: pval = select_max(nw_steps - start + init_l[i], init_l[i]) if store_steps[i] != -1: pval = select_max(pval, store_steps[i]) # TODO: Simplify the number of steps needed. # FB: This need good testing, left to later. # call get_scalar_constant_value()? it can # return python/numpy scalar or numpy.ndarray # currently. # pval = pre_greedy_local_optimizer(list_opt_slice, # pval) # pval = pre_constant_merge([pval])[0] # if (isinstance(pval, theano.tensor.TensorConstant) # and # pval.dtype.startswith('int')): # try: # pval = int(pval.data) # except Exception: # pass store_steps[i] = pval flag_store = True orphane_outs = [i for i, x in enumerate(store_steps) if (type(x) is int) and (x < 0)] flag_store = flag_store or (len(orphane_outs) > 0) # 3. is there anything to change ? if (flag_store or global_nsteps is not None): # 3.1 initialize inputs for the new scan old_outputs = [] nw_inputs = list(node.inputs) nw_inputs[0] = nw_steps # 3.2 check orphane outputs to see if we can eliminate any required, not_required = scan_utils.scan_can_remove_outs( node.op, orphane_outs) # 3.3. compose replace pairs for those nodes that need not # to store everything in memory ( or ar orphane and required # by the inner function .. ) replaced_outs = [] offset = 1 + op.n_seqs + op.n_mit_mot for idx, _val in enumerate(store_steps[op.n_mit_mot:]): i = idx + op.n_mit_mot if not(type(_val) is int and _val <= 0 and i not in required): if idx + op.n_mit_mot in required: val = 1 else: val = _val # If the memory for this output has been pre-allocated # before going into the scan op (by an alloc node) if idx < op.n_mit_sot + op.n_sit_sot: # In case the input is still an alloc node, we # actually have two options: # a) the input is a set_subtensor, in that case we # can replace the initial tensor by a slice, # b) it is not, and we simply take a slice of it. # TODO: commit change below with Razvan if (nw_inputs[offset + idx].owner and isinstance(nw_inputs[offset + idx].owner.op, tensor.IncSubtensor) and isinstance( nw_inputs[offset + idx].owner.op.idx_list[0], slice)): assert isinstance(nw_inputs[offset + idx].owner.op, tensor.IncSubtensor) _nw_input = nw_inputs[offset + idx].owner.inputs[1] cval = tensor.as_tensor_variable(val) initl = tensor.as_tensor_variable(init_l[i]) tmp_idx = tensor.switch(cval < initl, cval + initl, cval - initl) tmp = pre_greedy_local_optimizer(list_opt_slice, tmp_idx) tmp = pre_constant_merge([tmp])[0] nw_input = scan_utils.expand_empty(_nw_input, tmp) else: tmp = tensor.as_tensor_variable(val) initl = tensor.as_tensor_variable(init_l[i]) tmp = tensor.maximum(tmp, initl) tmp = pre_greedy_local_optimizer(list_opt_slice, tmp) tmp = pre_constant_merge([tmp])[0] nw_input = nw_inputs[offset + idx][:tmp] nw_inputs[offset + idx] = nw_input replaced_outs.append(op.n_mit_mot + idx) odx = op.n_mit_mot + idx old_outputs += [(odx, [x[0].outputs[0] for x in node.outputs[odx].clients])] # If there is no memory pre-allocated for this output elif idx < op.n_mit_sot + op.n_sit_sot + op.n_nit_sot: pos = (op.n_mit_mot + idx + op.n_seqs + 1 + op.n_shared_outs) if nw_inputs[pos] == node.inputs[0]: nw_inputs[pos] = val odx = op.n_mit_mot + idx replaced_outs.append(odx) old_outputs += [(odx, [x[0].outputs[0] for x in node.outputs[odx].clients])] # 3.4. Recompute inputs for everything else based on the new # number of steps if global_nsteps is not None: for idx, val in enumerate(store_steps[op.n_mit_mot:]): if val == 0: # val == 0 means that we want to keep all intermediate # results for that state, including the initial values. if idx < op.n_mit_sot + op.n_sit_sot: in_idx = offset + idx # Number of steps in the initial state initl = init_l[op.n_mit_mot + idx] # If the initial buffer has the form # inc_subtensor(zeros(...)[...], _nw_input) # we want to make the zeros tensor as small as # possible (nw_steps + initl), and call # inc_subtensor on that instead. # Otherwise, simply take 0:(nw_steps+initl). if ((nw_inputs[in_idx].owner and isinstance(nw_inputs[in_idx].owner.op, tensor.IncSubtensor) and isinstance( nw_inputs[in_idx].owner.op.idx_list[0], slice))): _nw_input = nw_inputs[in_idx].owner.inputs[1] nw_input = scan_utils.expand_empty(_nw_input, nw_steps) nw_inputs[in_idx] = nw_input else: nw_input = nw_inputs[in_idx][:(initl + nw_steps)] elif idx < op.n_mit_sot + op.n_sit_sot + op.n_nit_sot: in_idx = offset + idx + op.n_shared_outs if nw_inputs[in_idx] == node.inputs[0]: nw_inputs[in_idx] = nw_steps # 3.5 Remove unwanted orphane outputs (inps, outs, info, node_ins, compress_map) = \ scan_utils.compress_outs(op, not_required, nw_inputs) inv_compress_map = OrderedDict() for k, v in iteritems(compress_map): inv_compress_map[v] = k node_ins = [pre_greedy_local_optimizer(list_opt_slice, x) for x in node_ins] node_ins = pre_constant_merge(node_ins) # 3.6 Compose the new scan # I need to make sure I'm not reapplying the same optimization # twice since bad things usually happen if I do that # TODO: why not check if save mem was done on any of merged nodes? # That way, if none of them had save mem applied, it would # be applied later. info['_scan_savemem_visited'] = True # TODO: currently we don't support scan with 0 step. So # don't create one. if theano.tensor.extract_constant(node_ins[0]) == 0: return # Do not call make_node for test_value new_outs = scan_op.Scan(inps, outs, info)(*node_ins, **dict(return_list=True)) old_new = [] # 3.7 Get replace pairs for those outputs that do not change # the number of intermediate steps stored for idx, sl in enumerate(slices): if global_nsteps and sl is not None and store_steps[idx] == 0: for hdx, cl in enumerate(node.outputs[idx].clients): cnf_slice, old_slices = sl[hdx] # Sanitize the nw_slice by converting ints back into # constants :) I only need to do this for the first # slice since that is the only slice if isinstance(cnf_slice[0], slice): fslice = slice( sanitize(cnf_slice[0].start), sanitize(cnf_slice[0].stop), sanitize(cnf_slice[0].step)) else: fslice = sanitize(cnf_slice[0]) nw_slice = (fslice,) + tuple(old_slices[1:]) nw_pos = inv_compress_map[idx] subtens = tensor.Subtensor(nw_slice) # slice inputs sl_ins = tensor.Subtensor.collapse( nw_slice, lambda entry: isinstance(entry, tensor.Variable)) new_o = subtens(new_outs[nw_pos], *sl_ins) if new_o.ndim > 0: new_o = new_o[::cnf_slice[1]] replaced_outs.append(idx) old_new += [(cl[0].outputs[0], new_o)] # 3.8. Get replace pairs for those outputs that change # the number of stored intermediate steps for pos, old_outs in old_outputs: if len(old_outs) > 0: nw_pos = compress_map[pos] for k, old in enumerate(old_outs): # Get the correct slice cnf_slice, old_slices = slices[pos][k] if type(cnf_slice[0]) is slice: start = (cnf_slice[0].start - nw_steps - init_l[pos] + store_steps[pos]) if (cnf_slice[0].stop is not None and cnf_slice[0].stop != maxsize): stop = (cnf_slice[0].stop - nw_steps - init_l[pos] + store_steps[pos]) else: stop = None nw_slice = ((slice(sanitize(start), sanitize(stop), sanitize(cnf_slice[0].step)),) + tuple(old_slices[1:])) else: position = (cnf_slice[0] - nw_steps - init_l[pos] + store_steps[pos]) nw_slice = (sanitize(position),) + tuple( old_slices[1:]) subtens = tensor.Subtensor(nw_slice) sl_ins = tensor.Subtensor.collapse( nw_slice, lambda entry: isinstance(entry, tensor.Variable)) new_o = subtens(new_outs[nw_pos], *sl_ins) if new_o.ndim > 0: new_o = new_o[::cnf_slice[1]] old_new += [(old, new_o)] # 3.9. Get replace pairs for all other nodes if flag_store or global_nsteps is not None: for idx, o in enumerate(node.outputs): if not (idx in replaced_outs) and idx not in not_required: nw_pos = compress_map[idx] old_new += [(o, new_outs[nw_pos])] # Check if the new outputs depend on the old scan node old_scan_is_used = [scan_utils.find_up(new.owner, node) for old, new in old_new] if any(old_scan_is_used): return False remove = [old.owner for (old, new) in old_new] # As Fred suggested assert that also the old node is not in # the Graph as that will make things suboptimal remove.append(node) fgraph.replace_all_validate_remove(old_new, remove, reason='scanOp_save_mem') def apply(self, fgraph): nodelist = [x for x in fgraph.toposort() if isinstance(x.op, scan_op.Scan)] for node in nodelist: if not hasattr(node.op, '_scan_savemem_visited'): self.process_node(fgraph, node) class ScanMerge(gof.Optimizer): """ Graph Optimizer that merges different scan ops. """ def add_requirements(self, fgraph): fgraph.attach_feature(gof.toolbox.ReplaceValidate()) def merge(self, nodes): if nodes[0].op.as_while: as_while = True condition = nodes[0].op.outputs[-1] else: as_while = False info = OrderedDict() info['tap_array'] = [] info['n_seqs'] = sum([nd.op.n_seqs for nd in nodes]) info['n_mit_mot'] = sum([nd.op.n_mit_mot for nd in nodes]) info['n_mit_mot_outs'] = sum([nd.op.n_mit_mot_outs for nd in nodes]) info['mit_mot_out_slices'] = [] info['n_mit_sot'] = sum([nd.op.n_mit_sot for nd in nodes]) info['n_sit_sot'] = sum([nd.op.n_sit_sot for nd in nodes]) info['n_shared_outs'] = sum([nd.op.n_shared_outs for nd in nodes]) info['n_nit_sot'] = sum([nd.op.n_nit_sot for nd in nodes]) info['truncate_gradient'] = nodes[0].op.truncate_gradient info['name'] = '&'.join([nd.op.name for nd in nodes]) info['mode'] = nodes[0].op.mode info['gpu'] = False info['as_while'] = as_while info['profile'] = nodes[0].op.profile info['allow_gc'] = nodes[0].op.allow_gc # We keep the inner_ins and inner_outs of each original node separated. # To be able to recombine them in the right order after the clone, # we also need to split them by types (seq, mitmot, ...). # On the other hand, outer_ins, outer_outs and info are held together. inner_ins = [[] for nd in nodes] outer_ins = [] inner_outs = [[] for nd in nodes] outer_outs = [] def rename(ls, suffix): for k in ls: if k.name: k.name += str(suffix) return ls for idx, nd in enumerate(nodes): # Seq inner_ins[idx].append(rename(nd.op.inner_seqs(nd.op.inputs), idx)) outer_ins += rename(nd.op.outer_seqs(nd.inputs), idx) for idx, nd in enumerate(nodes): # MitMot inner_ins[idx].append( rename(nd.op.inner_mitmot(nd.op.inputs), idx)) inner_outs[idx].append(nd.op.inner_mitmot_outs(nd.op.outputs)) info['tap_array'] += nd.op.mitmot_taps() info['mit_mot_out_slices'] += nd.op.mitmot_out_taps() outer_ins += rename(nd.op.outer_mitmot(nd.inputs), idx) outer_outs += nd.op.outer_mitmot_outs(nd.outputs) for idx, nd in enumerate(nodes): # MitSot inner_ins[idx].append( rename(nd.op.inner_mitsot(nd.op.inputs), idx)) inner_outs[idx].append(nd.op.inner_mitsot_outs(nd.op.outputs)) info['tap_array'] += nd.op.mitsot_taps() outer_ins += rename(nd.op.outer_mitsot(nd.inputs), idx) outer_outs += nd.op.outer_mitsot_outs(nd.outputs) for idx, nd in enumerate(nodes): # SitSot inner_ins[idx].append( rename(nd.op.inner_sitsot(nd.op.inputs), idx)) info['tap_array'] += [[-1] for x in xrange(nd.op.n_sit_sot)] inner_outs[idx].append(nd.op.inner_sitsot_outs(nd.op.outputs)) outer_ins += rename(nd.op.outer_sitsot(nd.inputs), idx) outer_outs += nd.op.outer_sitsot_outs(nd.outputs) for idx, nd in enumerate(nodes): # Shared inner_ins[idx].append( rename(nd.op.inner_shared(nd.op.inputs), idx)) outer_ins += rename(nd.op.outer_shared(nd.inputs), idx) for idx, nd in enumerate(nodes): # NitSot inner_outs[idx].append(nd.op.inner_nitsot_outs(nd.op.outputs)) outer_ins += rename(nd.op.outer_nitsot(nd.inputs), idx) outer_outs += nd.op.outer_nitsot_outs(nd.outputs) for idx, nd in enumerate(nodes): # Shared outer_outs += nd.op.outer_shared_outs(nd.outputs) inner_outs[idx].append(nd.op.inner_shared_outs(nd.op.outputs)) for idx, nd in enumerate(nodes): # Non Seqs inner_ins[idx].append( rename(nd.op.inner_non_seqs(nd.op.inputs), idx)) outer_ins += rename(nd.op.outer_non_seqs(nd.inputs), idx) # Add back the number of steps outer_ins = [nodes[0].inputs[0]] + outer_ins if as_while: # add the condition, which was the one of nodes[0] inner_outs[0].append([condition]) # Clone the inner graph of each node independently for idx, nd in enumerate(nodes): # concatenate all inner_ins and inner_outs of nd flat_inner_ins = sum(inner_ins[idx], []) flat_inner_outs = sum(inner_outs[idx], []) # clone flat_inner_ins, flat_inner_outs = scan_utils.reconstruct_graph( flat_inner_ins, flat_inner_outs) # split the new inner variables again in seq, mitmot, etc. new_inner_ins = [] count = 0 for nl in inner_ins[idx]: seq_len = len(nl) new_inner_ins.append(flat_inner_ins[count:(count + seq_len)]) count += seq_len new_inner_outs = [] count = 0 for nl in inner_outs[idx]: seq_len = len(nl) new_inner_outs.append(flat_inner_outs[count:(count + seq_len)]) count += seq_len inner_ins[idx] = new_inner_ins inner_outs[idx] = new_inner_outs # Flatten inner_ins and inner_outs so that all seqs are first, # then mitmot, etc. new_inner_ins = [] new_inner_outs = [] nb_ins_groups = len(inner_ins[0]) nb_outs_groups = len(inner_outs[0]) for idx, nd in enumerate(nodes): # All inner_ins should have the same length assert len(inner_ins[idx]) == nb_ins_groups # All inner_outs should have the same length, except if as_while, # in which case the first one should have one more element if as_while and idx > 0: assert len(inner_outs[idx]) == nb_outs_groups - 1 else: assert len(inner_outs[idx]) == nb_outs_groups for gr_idx in range(nb_ins_groups): for idx, nd in enumerate(nodes): new_inner_ins += inner_ins[idx][gr_idx] for gr_idx in range(nb_outs_groups): for idx, nd in enumerate(nodes): if as_while and idx > 0 and gr_idx == (nb_outs_groups - 1): # There is no condition on that node, skip it pass else: new_inner_outs += inner_outs[idx][gr_idx] new_op = scan_op.Scan(new_inner_ins, new_inner_outs, info) new_outs = new_op(*outer_ins) if not isinstance(new_outs, (list, tuple)): new_outs = [new_outs] return list(zip(outer_outs, new_outs)) def belongs_to_set(self, node, set_nodes): """ This function checks if node `node` belongs to `set_nodes`, in the sense that it can be merged together with every other node in `set_nodes`. In order for two nodes to be mergeable, they have to go over the same number of steps, have the same condition (if any), have the same value for truncate_gradient, and have the same mode. Questionable, we should also consider profile ? """ rep = set_nodes[0] if rep.op.as_while != node.op.as_while: return False nsteps = node.inputs[0] try: nsteps = int(get_scalar_constant_value(nsteps)) except tensor.NotScalarConstantError: pass rep_nsteps = rep.inputs[0] try: rep_nsteps = int(get_scalar_constant_value(rep_nsteps)) except tensor.NotScalarConstantError: pass # Check to see if it is an input of a different node can_add = True for nd in set_nodes: if find_up(node, nd) or find_up(nd, node): can_add = False can_add = can_add and (node.op.truncate_gradient == rep.op.truncate_gradient) can_add = can_add and (node.op.mode == rep.op.mode) if not node.op.as_while: return nsteps == rep_nsteps and can_add cond = node.op.outputs[-1] rep_cond = rep.op.outputs[-1] same_cond = scan_utils.equal_computations([cond], [rep_cond], node.op.inputs, rep.op.inputs) return same_cond and (nsteps == rep_nsteps) and can_add def apply(self, fgraph): # Collect all scan nodes ordered according to toposort scan_nodes = [nd for nd in fgraph.toposort() if isinstance(nd.op, scan_op.Scan)] # All sets of possibly mergeable nodes all_sets = [] for nd in scan_nodes: belongs_to_set_idx = -1 for pos, subset in enumerate(all_sets): if self.belongs_to_set(nd, subset): belongs_to_set_idx = pos # It is possible that nd belongs to more than one subset. # For instance, if we have 3 Scan nodes X, Y and Z, if Z # depends on the output of X, then X and Z are incompatible # and would create different subsets, but Y could be # compatible with both X and Z. We choose the first one. break if belongs_to_set_idx == -1: all_sets.append([nd]) else: all_sets[belongs_to_set_idx].append(nd) for subset in all_sets: if len(subset) > 1: proposal = self.merge(subset) fgraph.replace_all_validate_remove(proposal, remove=subset, reason='scanOp_merge') def has_duplicates(l): """ Returns true if l has any duplicates (according to __eq__). """ return len(set(l)) < len(l) def make_equiv(lo, li): """ Builds a dictionary of equivalences between inner inputs based on the equivalence of their corresponding outer inputs. """ seeno = OrderedDict() left = [] right = [] for o, i in zip(lo, li): if o in seeno: left += [i] right += [o] else: seeno[o] = i return left, right @gof.local_optimizer([scan_op.Scan]) def scan_merge_inouts(node): if not isinstance(node.op, scan_op.Scan): return False # Do a first pass to merge identical external inputs. # Equivalent inputs will be stored in inp_equiv, then a new # scan node created without duplicates. a = scan_args(node.inputs, node.outputs, node.op.inputs, node.op.outputs, node.op.info) inp_equiv = OrderedDict() if has_duplicates(a.outer_in_seqs): new_outer_seqs = [] new_inner_seqs = [] for out_seq, in_seq in zip(a.outer_in_seqs, a.inner_in_seqs): if out_seq in new_outer_seqs: i = new_outer_seqs.index(out_seq) inp_equiv[in_seq] = new_inner_seqs[i] else: new_outer_seqs.append(out_seq) new_inner_seqs.append(in_seq) a.outer_in_seqs = new_outer_seqs a.inner_in_seqs = new_inner_seqs if has_duplicates(a.outer_in_non_seqs): new_outer_nseqs = [] new_inner_nseqs = [] for out_nseq, in_nseq in zip(a.outer_in_non_seqs, a.inner_in_non_seqs): if out_nseq in new_outer_nseqs: i = new_outer_nseqs.index(out_nseq) inp_equiv[in_nseq] = new_inner_nseqs[i] else: new_outer_nseqs.append(out_nseq) new_inner_nseqs.append(in_nseq) a.outer_in_non_seqs = new_outer_nseqs a.inner_in_non_seqs = new_inner_nseqs if len(inp_equiv) > 0: # do the replacement now. The rest will be left to ScanSaveMem inner_inputs = a.inner_inputs outer_inputs = a.outer_inputs info = a.info a_inner_outs = a.inner_outputs inner_outputs = scan_utils.clone(a_inner_outs, replace=inp_equiv) op = scan_op.Scan(inner_inputs, inner_outputs, info) outputs = op(*outer_inputs) if not isinstance(outputs, (list, tuple)): outputs = [outputs] na = scan_args(outer_inputs, outputs, op.inputs, op.outputs, op.info) remove = [node] else: na = a remove = [] # Now that the identical external inputs have been merged, we do a new # loop in order to merge external outputs that compute the same things # from the same inputs. left = [] right = [] if has_duplicates(na.outer_in_shared): _left, _right = make_equiv(na.outer_in_shared, na.inner_in_shared) left += _left right += _right if has_duplicates(na.outer_in_sit_sot): _left, _right = make_equiv(na.outer_in_sit_sot, na.inner_in_sit_sot) left += _left right += _right if has_duplicates(na.outer_in_mit_mot): seen = OrderedDict() for omm, imm, _sl in zip(na.outer_in_mit_mot, na.inner_in_mit_mot, na.mit_mot_in_slices): sl = tuple(_sl) if (omm, sl) in seen: simm = seen[(omm, sl)] left += imm right += simm else: seen[(omm, sl)] = imm if has_duplicates(na.outer_in_mit_sot): seen = OrderedDict() for oms, ims, _sl in zip(na.outer_in_mit_sot, na.inner_in_mit_sot, na.mit_sot_in_slices): sl = tuple(_sl) if (oms, sl) in seen: sims = seen[(oms, sl)] left += ims right += sims else: seen[(oms, sl)] = ims def map_out(outer_i, inner_o, outer_o, seen): # Return the outer input corresponding to an # (outer input, inner output) pair. If we see that pair for the first # time, return the provided outer output. If an equivalent pair had # already been seen, return that one instead. # Note that we need to check that the outer input match as well, # because they could have different sizes, and the corresponding # outer outputs cannot be merged in that case. for s_outer_i, s_inner_o, s_outer_o in seen: if (equal_computations([inner_o], [s_inner_o], left, right) and outer_i == s_outer_i): return s_outer_o seen.append((outer_i, inner_o, outer_o)) return outer_o seen = [] assert len(na.outer_in_nit_sot) == len(na.inner_out_nit_sot) assert len(na.inner_out_nit_sot) == len(na.outer_out_nit_sot) na.outer_out_nit_sot = [ map_out(outer_i, inner_o, outer_o, seen) for outer_i, inner_o, outer_o in zip(na.outer_in_nit_sot, na.inner_out_nit_sot, na.outer_out_nit_sot)] seen = [] assert len(na.outer_in_sit_sot) == len(na.inner_out_sit_sot) assert len(na.inner_out_sit_sot) == len(na.outer_out_sit_sot) na.outer_out_sit_sot = [ map_out(outer_i, inner_o, outer_o, seen) for outer_i, inner_o, outer_o in zip(na.outer_in_sit_sot, na.inner_out_sit_sot, na.outer_out_sit_sot)] seen = [] assert len(na.outer_in_mit_sot) == len(na.inner_out_mit_sot) assert len(na.inner_out_mit_sot) == len(na.outer_out_mit_sot) na.outer_out_mit_sot = [ map_out(outer_i, inner_o, outer_o, seen) for outer_i, inner_o, outer_o in zip(na.outer_in_mit_sot, na.inner_out_mit_sot, na.outer_out_mit_sot)] seen = [] new_outer_out_mit_mot = [] assert len(na.outer_in_mit_mot) == len(na.inner_out_mit_mot) assert len(na.inner_out_mit_mot) == len(na.outer_out_mit_mot) assert len(na.outer_out_mit_mot) == len(na.mit_mot_out_slices) for outer_imm, inner_omm, outer_omm, osl in zip(na.outer_in_mit_mot, na.inner_out_mit_mot, na.outer_out_mit_mot, na.mit_mot_out_slices): for s_outer_imm, s_inner_omm, s_outer_omm, sosl in seen: if (osl == sosl and equal_computations(inner_omm, s_inner_omm, left, right) and outer_imm == s_outer_imm): new_outer_out_mit_mot.append(s_outer_omm) break else: seen.append((outer_imm, inner_omm, outer_omm, osl)) new_outer_out_mit_mot.append(outer_omm) na.outer_out_mit_mot = new_outer_out_mit_mot if remove: return OrderedDict([("remove", remove)] + list(zip(node.outputs, na.outer_outputs))) return na.outer_outputs class PushOutDot1(gof.Optimizer): """ Graph optimizer for Scan(makes it run inplace). """ def __init__(self): Optimizer.__init__(self) def add_requirements(self, fgraph): fgraph.attach_feature(toolbox.ReplaceValidate()) def apply(self, fgraph): nodes = fgraph.toposort() scan_nodes = [x for x in nodes if (isinstance(x.op, scan_op.Scan))] for node in scan_nodes: self.apply_opt(fgraph, node) def apply_opt(self, fgraph, node): # Replace pattern of the form # x[t] = x[t-1] + dot(seq[t], value) # with Sequence.reshape((-1, seq.shape[2])) \dot Value # When seq[t] is a vector/matrix and `value` is a matrix # Note that this works when only you need X[-1] in the end # and assumes dimshuffle are applied to vectors before calling dot op = node.op sitsot_ins = op.inner_sitsot(op.inputs) sitsot_outs = op.inner_sitsot_outs(op.outputs) outer_sitsot = op.outer_sitsot_outs(node) seqs = op.inner_seqs(op.inputs) for inp, out, outer_out in zip(sitsot_ins, sitsot_outs, outer_sitsot): if (out.owner and isinstance(out.owner.op, theano.tensor.Elemwise) and isinstance(out.owner.op.scalar_op, theano.scalar.Add) and inp in out.owner.inputs and len(outer_out.clients) == 1 and not isinstance(outer_out.clients[0][0], str) and isinstance(outer_out.clients[0][0].op, theano.tensor.Subtensor) and outer_out.clients[0][0].op.idx_list == (-1,)): x = out.owner.inputs[0] if x == inp: x = out.owner.inputs[1] # We need to check if x is the result of an outer product if (x.owner and isinstance(x.owner.op, theano.tensor.Dot) and x.owner.inputs[0].ndim == 2 and x.owner.inputs[1].ndim == 2): # We need to check if any of the inputs are a sequence inp1 = x.owner.inputs[0] inp2 = x.owner.inputs[1] if inp1 in seqs or inp2 in seqs: new_scan_out = inp1 if inp1 in seqs: new_scan_out = inp2 idx = sitsot_outs.index(out) # We've found our pattern and need to construct a new # scan node to replace this one. For this we need to # replace the sit_sot output with a nit_sot output # First let us split all arguments according to their # corresponding categories inner_seqs = op.inner_seqs(op.inputs) outer_seqs = op.outer_seqs(node) inner_mitmot = op.inner_mitmot(op.inputs) outer_mitmot = op.outer_mitmot(node) inner_mitmot_outs = op.inner_mitmot_outs(op.outputs) inner_mitsot = op.inner_mitsot(op.inputs) outer_mitsot = op.outer_mitsot(node) inner_mitsot_outs = op.inner_mitsot_outs(op.outputs) inner_sitsot = op.inner_sitsot(op.inputs) outer_sitsot = op.outer_sitsot(node) inner_sitsot_outs = op.inner_sitsot_outs(op.outputs) outer_nitsot = op.outer_nitsot(node) inner_nitsot_outs = op.inner_nitsot_outs(op.outputs) inner_shared = op.inner_shared(op.inputs) outer_shared = op.outer_shared(node) inner_shared_outs = op.inner_shared_outs(op.outputs) inner_non_seqs = op.inner_non_seqs(op.inputs) outer_non_seqs = op.outer_non_seqs(node) new_info = op.info.copy() st = len(op.mitmot_taps()) + len(op.mitsot_taps()) new_info['tap_array'] = ( new_info['tap_array'][:st + idx] + new_info['tap_array'][st + idx + 1:]) new_info['n_sit_sot'] -= 1 new_info['n_nit_sot'] += 1 inner_sitsot = (inner_sitsot[:idx] + inner_sitsot[idx + 1:]) outer_sitsot = (outer_sitsot[:idx] + outer_sitsot[idx + 1:]) inner_sitsot_outs = (inner_sitsot_outs[:idx] + inner_sitsot_outs[idx + 1:]) # add n_steps as the length inner_nitsot_outs.append(new_scan_out) _new_inner_inps = (inner_seqs + inner_mitmot + inner_mitsot + inner_sitsot + inner_shared + inner_non_seqs) _new_inner_outs = (inner_mitmot_outs + inner_mitsot_outs + inner_sitsot_outs + inner_nitsot_outs + inner_shared_outs) new_inner_inps, new_inner_outs =\ scan_utils.reconstruct_graph(_new_inner_inps, _new_inner_outs) new_op = scan_op.Scan(new_inner_inps, new_inner_outs, new_info) _scan_inputs = ([node.inputs[0]] + outer_seqs + outer_mitmot + outer_mitsot + outer_sitsot + outer_shared + outer_nitsot + [node.inputs[0]] + outer_non_seqs) new_outs = new_op(*_scan_inputs) if type(new_outs) not in (list, tuple): new_outs = [new_outs] # We need now to pair correctly the new outputs # with the old ones outer_nitsot_outs = new_op.outer_nitsot_outs(new_outs) _val = outer_nitsot_outs[-1] outer_nitsot_outs = outer_nitsot_outs[:-1] if inp1 in seqs: _out_seq = op.outer_seqs(node)[seqs.index(inp1)] # We need to clip the seq to the number of steps _out_seq = _out_seq[:node.inputs[0]] sh0 = _out_seq.shape[0] sh1 = _out_seq.shape[1] sh2 = _out_seq.shape[2] out_seq = _out_seq.dimshuffle(1, 0, 2) out_seq = out_seq.reshape((sh1, sh0 * sh2)) sh0 = _val.shape[0] sh1 = _val.shape[1] sh2 = _val.shape[2] val = _val.reshape((sh0 * sh1, sh2)) new_out = tensor.dot(out_seq, val) else: _out_seq = op.outer_seqs(node)[seqs.index(inp2)] out_seq = _out_seq.reshape( (_out_seq.shape[0] * _out_seq.shape[1], _out_seq.shape[2])) val = _val.dimshuffle(1, 0, 2).reshape( (_val.shape[1], _val.shape[0] * _val.shape[2])) new_out = tensor.dot(val, out_seq) pos = node.outputs.index(outer_out) old_new = list(zip(node.outputs[:pos], new_outs[:pos])) old = node.outputs[pos].clients[0][0].outputs[0] old_new.append((old, new_out)) old_new += list(zip(node.outputs[pos + 1:], new_outs[pos:])) fgraph.replace_all_validate_remove( old_new, remove=[node], reason='scan_pushout_dot1') # I've added an equilibrium because later scan optimization in the sequence # can make it such that earlier optimizations should apply. However, in # general I do not expect the sequence to run more then once scan_eqopt1 = theano.gof.EquilibriumDB() scan_seqopt1 = theano.gof.SequenceDB() scan_eqopt2 = theano.gof.EquilibriumDB() # scan_eqopt1 before ShapeOpt at 0.1 # This is needed to don't have ShapeFeature trac old Scan that we # don't want to reintroduce. optdb.register('scan_eqopt1', scan_eqopt1, .05, 'fast_run', 'scan') # We run before blas opt at 1.7 and specialize 2.0 # but after stabilize at 1.5. Should we put it before stabilize? optdb.register('scan_eqopt2', scan_eqopt2, 1.6, 'fast_run', 'scan') optdb.register('scanOp_make_inplace', ScanInplaceOptimizer(typeInfer=None, gpu_flag=False), 75, 'fast_run', 'inplace', 'scan') scan_eqopt1.register( 'all_pushout_opt', scan_seqopt1, 1, 'fast_run', 'scan') scan_seqopt1.register('scanOp_remove_constants_and_unused_inputs0', opt.in2out(remove_constants_and_unused_inputs_scan, ignore_newtrees=True), 1, 'remove_constants_and_unused_inputs_scan', 'fast_run', 'scan') scan_seqopt1.register('scanOp_pushout_nonseqs_ops', PushOutNonSeqScan(), 2, 'fast_run', 'scan') scan_seqopt1.register('scanOp_pushout_seqs_ops', PushOutSeqScan(), 3, 'fast_run', 'scan') scan_seqopt1.register('scan_pushout_dot1', PushOutDot1(), 4, 'fast_run', 'more_mem', 'scan') scan_seqopt1.register('scanOp_pushout_output', PushOutScanOutput(), 5, 'fast_run', 'more_mem', 'scan') scan_eqopt2.register('constant_folding_for_scan2', opt.in2out(tensor.opt.constant_folding, ignore_newtrees=True), 1, 'fast_run', 'scan') scan_eqopt2.register('scanOp_remove_constants_and_unused_inputs1', opt.in2out(remove_constants_and_unused_inputs_scan, ignore_newtrees=True), 2, 'remove_constants_and_unused_inputs_scan', 'fast_run', 'scan') # after const merge but before stabilize so that we can have identity # for equivalent nodes but we still have the chance to hoist stuff out # of the scan later. scan_eqopt2.register('scanOp_merge', ScanMerge(), 4, 'fast_run', 'scan') # After Merge optimization scan_eqopt2.register('scanop_remove_constants_and_unused_inputs2', opt.in2out(remove_constants_and_unused_inputs_scan, ignore_newtrees=True), 5, 'remove_constants_and_unused_inputs_scan', 'fast_run', 'scan') scan_eqopt2.register('scanOp_merge_inouts', opt.in2out(scan_merge_inouts, ignore_newtrees=True), 6, 'scan_merge_inouts', 'fast_run', 'scan') # Just before specialize to have the other optimization # like constant folding being applied # This don't introduce inplace. scan_eqopt2.register('scanOp_save_mem', ScanSaveMem(), 7, 'fast_run', 'scan') # After everything else scan_eqopt2.register('scanOp_remove_constants_and_unused_inputs3', opt.in2out(remove_constants_and_unused_inputs_scan, ignore_newtrees=True), 8, 'remove_constants_and_unused_inputs_scan', 'fast_run', 'scan')
bsd-3-clause
hitHlb/googletest
test/gtest_uninitialized_test.py
2901
2480
#!/usr/bin/env python # # Copyright 2008, 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. """Verifies that Google Test warns the user when not initialized properly.""" __author__ = 'wan@google.com (Zhanyong Wan)' import gtest_test_utils COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_') def Assert(condition): if not condition: raise AssertionError def AssertEq(expected, actual): if expected != actual: print 'Expected: %s' % (expected,) print ' Actual: %s' % (actual,) raise AssertionError def TestExitCodeAndOutput(command): """Runs the given command and verifies its exit code and output.""" # Verifies that 'command' exits with code 1. p = gtest_test_utils.Subprocess(command) Assert(p.exited) AssertEq(1, p.exit_code) Assert('InitGoogleTest' in p.output) class GTestUninitializedTest(gtest_test_utils.TestCase): def testExitCodeAndOutput(self): TestExitCodeAndOutput(COMMAND) if __name__ == '__main__': gtest_test_utils.Main()
bsd-3-clause
pranav01/android_kernel_xiaomi_ferrari
tools/perf/scripts/python/syscall-counts-by-pid.py
11180
1927
# system call counts, by pid # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide system call totals, broken down by syscall. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os, sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import syscall_name usage = "perf script -s syscall-counts-by-pid.py [comm]\n"; for_comm = None for_pid = None if len(sys.argv) > 2: sys.exit(usage) if len(sys.argv) > 1: try: for_pid = int(sys.argv[1]) except: for_comm = sys.argv[1] syscalls = autodict() def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): print_syscall_totals() def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): if (for_comm and common_comm != for_comm) or \ (for_pid and common_pid != for_pid ): return try: syscalls[common_comm][common_pid][id] += 1 except TypeError: syscalls[common_comm][common_pid][id] = 1 def print_syscall_totals(): if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events by comm/pid:\n\n", print "%-40s %10s\n" % ("comm [pid]/syscalls", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "----------"), comm_keys = syscalls.keys() for comm in comm_keys: pid_keys = syscalls[comm].keys() for pid in pid_keys: print "\n%s [%d]\n" % (comm, pid), id_keys = syscalls[comm][pid].keys() for id, val in sorted(syscalls[comm][pid].iteritems(), \ key = lambda(k, v): (v, k), reverse = True): print " %-38s %10d\n" % (syscall_name(id), val),
gpl-2.0
flaing/gemrb
gemrb/GUIScripts/ie_stats.py
1
10456
# -*-python-*- # GemRB - Infinity Engine Emulator # Copyright (C) 2003 The GemRB Project # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ie_stats.py - definitions of creature stats codes # !!! NOTE: Keep this file synchronized with gemrb/includes/ie_stats.h !!! # EA values INANIMATE = 1 PC = 2 FAMILIAR = 3 ALLY = 4 CONTROLLED = 5 #charmed is 7 inside the engine??? CHARMED = 7 GOODBUTRED = 28 GOODBUTBLUE = 29 GOODCUTOFF = 30 NOTGOOD = 31 ANYTHING = 126 NEUTRAL = 128 NOTEVIL = 199 EVILCUTOFF = 200 EVILBUTGREEN = 201 EVILBUTBLUE = 202 CHARMEDPC = 254 ENEMY = 255 # state bits (IE_STATE) STATE_BERSERK = 2 STATE_PANIC = 4 STATE_HELPLESS = 1 + 32 STATE_PETRIFIED = 8 + 64 + 128 STATE_DEAD = 2048 STATE_POISONED = 0x4000 MC_WAS_FIGHTER = 0x0008 MC_WAS_MAGE = 0x0010 MC_WAS_CLERIC = 0x0020 MC_WAS_THIEF = 0x0040 MC_WAS_DRUID = 0x0080 MC_WAS_RANGER = 0x0100 MC_WAS_ANY_CLASS = MC_WAS_FIGHTER|MC_WAS_MAGE|MC_WAS_CLERIC|MC_WAS_THIEF|MC_WAS_DRUID|MC_WAS_RANGER MC_FALLEN_PALADIN = 0x200 MC_FALLEN_RANGER = 0x400 MC_EXPORTABLE = 0x800 MC_PLOT_CRITICAL = 0x2000 MC_BEENINPARTY = 0x8000 MC_SEENPARTY = 0x10000 # stats IE_HITPOINTS = 0 IE_MAXHITPOINTS = 1 IE_ARMORCLASS = 2 IE_ACCRUSHINGMOD = 3 IE_ACMISSILEMOD = 4 IE_ACPIERCINGMOD = 5 IE_ACSLASHINGMOD = 6 IE_TOHIT = 7 IE_NUMBEROFATTACKS = 8 IE_SAVEVSDEATH = 9 IE_SAVEVSWANDS = 10 IE_SAVEVSPOLY = 11 IE_SAVEVSBREATH = 12 IE_SAVEVSSPELL = 13 IE_SAVEFORTITUDE = 9 IE_SAVEREFLEX = 10 IE_SAVEWILL = 11 IE_RESISTFIRE = 14 IE_RESISTCOLD = 15 IE_RESISTELECTRICITY = 16 IE_RESISTACID = 17 IE_RESISTMAGIC = 18 IE_RESISTMAGICFIRE = 19 IE_RESISTMAGICCOLD = 20 IE_RESISTSLASHING = 21 IE_RESISTCRUSHING = 22 IE_RESISTPIERCING = 23 IE_RESISTMISSILE = 24 IE_LORE = 25 IE_LOCKPICKING = 26 IE_STEALTH = 27 IE_TRAPS = 28 IE_PICKPOCKET = 29 IE_FATIGUE = 30 IE_INTOXICATION = 31 IE_LUCK = 32 IE_TRACKING = 33 IE_LEVEL = 34 IE_LEVELFIGHTER = 34 # pst, iwd2 IE_SEX = 35 IE_STR = 36 IE_STREXTRA = 37 IE_INT = 38 IE_WIS = 39 IE_DEX = 40 IE_CON = 41 IE_CHR = 42 IE_XPVALUE = 43 IE_XP = 44 IE_GOLD = 45 IE_MORALEBREAK = 46 IE_MORALERECOVERYTIME = 47 IE_REPUTATION = 48 IE_HATEDRACE = 49 IE_DAMAGEBONUS = 50 IE_SPELLFAILUREMAGE = 51 IE_SPELLFAILUREPRIEST = 52 IE_SPELLDURATIONMODMAGE = 53 IE_SPELLDURATIONMODPRIEST = 54 IE_TURNUNDEADLEVEL = 55 IE_BACKSTABDAMAGEMULTIPLIER = 56 IE_LAYONHANDSAMOUNT = 57 IE_HELD = 58 IE_POLYMORPHED = 59 IE_TRANSLUCENT = 60 IE_IDENTIFYMODE = 61 IE_ENTANGLE = 62 IE_SANCTUARY = 63 IE_MINORGLOBE = 64 IE_SHIELDGLOBE = 65 IE_GREASE = 66 IE_WEB = 67 IE_LEVEL2 = 68 IE_LEVELMAGE = 68 # pst, iwd2 IE_LEVEL3 = 69 IE_LEVELTHIEF = 69 # pst, iwd2 IE_CASTERHOLD = 70 IE_ENCUMBRANCE = 71 IE_MISSILEHITBONUS = 72 IE_MAGICDAMAGERESISTANCE = 73 IE_RESISTPOISON = 74 IE_DONOTJUMP = 75 IE_AURACLEANSING = 76 IE_MENTALSPEED = 77 IE_PHYSICALSPEED = 78 IE_CASTINGLEVELBONUSMAGE = 79 IE_CASTINGLEVELBONUSCLERIC = 80 IE_SEEINVISIBLE = 81 IE_IGNOREDIALOGPAUSE = 82 IE_MINHITPOINTS = 83 IE_HITBONUSRIGHT = 84 IE_HITBONUSLEFT = 85 IE_DAMAGEBONUSRIGHT = 86 IE_DAMAGEBONUSLEFT = 87 IE_STONESKINS = 88 IE_FEAT_BOW = 89 IE_FEAT_CROSSBOW = 90 IE_FEAT_SLING = 91 IE_FEAT_AXE = 92 IE_FEAT_MACE = 93 IE_FEAT_FLAIL = 94 IE_FEAT_POLEARM = 95 IE_FEAT_HAMMER = 96 IE_FEAT_STAFF = 97 IE_FEAT_GREAT_SWORD = 98 IE_FEAT_LARGE_SWORD = 99 IE_FEAT_SMALL_SWORD = 100 IE_FEAT_TOUGHNESS = 101 IE_FEAT_ARMORED_ARCANA = 102 IE_FEAT_CLEAVE = 103 IE_FEAT_ARMOUR = 104 IE_FEAT_ENCHANTMENT = 105 IE_FEAT_EVOCATION = 106 IE_FEAT_NECROMANCY = 107 IE_FEAT_TRANSMUTATION = 108 IE_FEAT_SPELL_PENETRATION = 109 IE_FEAT_EXTRA_RAGE = 110 IE_FEAT_EXTRA_SHAPE = 111 IE_FEAT_EXTRA_SMITING = 112 IE_FEAT_EXTRA_TURNING = 113 IE_FEAT_BASTARDSWORD = 114 IE_ALCHEMY = 115 IE_ANIMALS = 116 IE_BLUFF = 117 IE_CONCENTRATION = 118 IE_DIPLOMACY = 119 IE_INTIMIDATE = 120 IE_SEARCH = 121 IE_SPELLCRAFT = 122 IE_MAGICDEVICE = 123 IE_PROFICIENCYBASTARDSWORD = 89 IE_PROFICIENCYLONGSWORD = 90 IE_PROFICIENCYSHORTSWORD = 91 IE_PROFICIENCYAXE = 92 IE_PROFICIENCYTWOHANDEDSWORD = 93 IE_PROFICIENCYKATANA = 94 IE_PROFICIENCYSCIMITARWAKISASHININJATO = 95 IE_PROFICIENCYDAGGER = 96 IE_PROFICIENCYWARHAMMER = 97 IE_PROFICIENCYSPEAR = 98 IE_PROFICIENCYHALBERD = 99 IE_PROFICIENCYFLAILMORNINGSTAR = 100 IE_PROFICIENCYMACE = 101 IE_PROFICIENCYQUARTERSTAFF = 102 IE_PROFICIENCYCROSSBOW = 103 IE_PROFICIENCYLONGBOW = 104 IE_PROFICIENCYSHORTBOW = 105 IE_PROFICIENCYDART = 106 IE_PROFICIENCYSLING = 107 IE_PROFICIENCYBLACKJACK = 108 IE_PROFICIENCYGUN = 109 IE_PROFICIENCYMARTIALARTS = 110 IE_PROFICIENCY2HANDED = 111 IE_PROFICIENCYSWORDANDSHIELD = 112 IE_PROFICIENCYSINGLEWEAPON = 113 IE_PROFICIENCY2WEAPON = 114 IE_EXTRAPROFICIENCY1 = 115 IE_EXTRAPROFICIENCY2 = 116 IE_EXTRAPROFICIENCY3 = 117 IE_EXTRAPROFICIENCY4 = 118 IE_EXTRAPROFICIENCY5 = 119 IE_EXTRAPROFICIENCY6 = 120 IE_EXTRAPROFICIENCY7 = 121 IE_EXTRAPROFICIENCY8 = 122 IE_EXTRAPROFICIENCY9 = 123 IE_EXTRAPROFICIENCY10 = 124 IE_EXTRAPROFICIENCY11 = 125 IE_EXTRAPROFICIENCY12 = 126 IE_EXTRAPROFICIENCY13 = 127 IE_EXTRAPROFICIENCY14 = 128 IE_EXTRAPROFICIENCY15 = 129 IE_EXTRAPROFICIENCY16 = 130 IE_EXTRAPROFICIENCY17 = 131 IE_FEATS1 = 131 IE_EXTRAPROFICIENCY18 = 132 IE_FEATS2 = 132 IE_EXTRAPROFICIENCY19 = 133 IE_FEATS3 = 133 IE_EXTRAPROFICIENCY20 = 134 IE_FREESLOTS = 134 #not an error (PST) IE_HIDEINSHADOWS = 135 IE_DETECTILLUSIONS = 136 IE_SETTRAPS = 137 IE_PUPPETMASTERID = 138 IE_PUPPETMASTERTYPE = 139 IE_PUPPETTYPE = 140 IE_PUPPETID = 141 IE_CHECKFORBERSERK = 142 IE_BERSERKSTAGE1 = 143 IE_BERSERKSTAGE2 = 144 IE_DAMAGELUCK = 145 IE_CRITICALHITBONUS = 146 IE_VISUALRANGE = 147 IE_EXPLORE = 148 IE_THRULLCHARM = 149 IE_SUMMONDISABLE = 150 IE_HITBONUS = 151 IE_KIT = 152 IE_FORCESURGE = 153 IE_SURGEMOD = 154 IE_IMPROVEDHASTE = 155 IE_SCRIPTINGSTATE1 = 156 IE_SCRIPTINGSTATE2 = 157 IE_SCRIPTINGSTATE3 = 158 IE_SCRIPTINGSTATE4 = 159 IE_SCRIPTINGSTATE5 = 160 IE_SCRIPTINGSTATE6 = 161 IE_SCRIPTINGSTATE7 = 162 IE_SCRIPTINGSTATE8 = 163 IE_SCRIPTINGSTATE9 = 164 IE_SCRIPTINGSTATE10 = 165 IE_MELEETOHIT = 166 IE_MELEEDAMAGE = 167 IE_MISSILEDAMAGE = 168 IE_NOCIRCLE = 169 IE_FISTHIT = 170 IE_FISTDAMAGE = 171 IE_TITLE1 = 172 IE_TITLE2 = 173 IE_DISABLEOVERLAY = 174 IE_DISABLEBACKSTAB = 175 #176-182 overwritten by us IE_XP_MAGE = 176 # In PST this stores secondary level exp IE_XP_THIEF = 177 # In PST this stores tertiary level exp IE_DIALOGRANGE = 178 # distance for dialogue IE_MOVEMENTRATE = 179 IE_MORALE = 180 IE_BOUNCE = 181 IE_MIRRORIMAGES = 182 #these are original IE_ENABLEOFFSCREENAI = 183 IE_EXISTANCEDELAY = 184 IE_ATTACKNUMBERDOUBLE = 185 IE_DISABLECHUNKING = 186 IE_NOTURNABLE = 187 #188 was summondisable2 in original IE_STONESKINSGOLEM = 199 IE_LEVELDRAIN = 200 IE_AVATARREMOVAL = 201 #202 is unused # GemRB Specific Defines IE_IMMUNITY = 203 IE_DISABLEDBUTTON = 204 IE_ANIMATION_ID = 205 IE_STATE_ID = 206 IE_EXTSTATE_ID = 207 IE_METAL_COLOR = 208 IE_MINOR_COLOR = 209 IE_MAJOR_COLOR = 210 IE_SKIN_COLOR = 211 IE_LEATHER_COLOR = 212 IE_ARMOR_COLOR = 213 IE_HAIR_COLOR = 214 IE_MC_FLAGS = 215 IE_CLASSLEVELSUM = 216 IE_ALIGNMENT = 217 IE_CASTING = 218 IE_ARMOR_TYPE = 219 IE_TEAM = 220 IE_FACTION = 221 IE_SUBRACE = 222 IE_SPECIES = 223 #pst specific IE_HATEDRACE2 = 224 IE_HATEDRACE3 = 225 IE_HATEDRACE4 = 226 IE_HATEDRACE5 = 227 IE_HATEDRACE6 = 228 IE_HATEDRACE7 = 229 IE_HATEDRACE8 = 230 # These are in original PST, IWD, IWD2, but not as stats IE_RACE = 231 IE_CLASS = 232 IE_GENERAL = 233 IE_EA = 234 IE_SPECIFIC = 235 IE_SAVEDXPOS = 236 IE_SAVEDYPOS = 237 IE_SAVEDFACE = 238 #239 user defined stat IE_LEVELBARBARIAN = 240 IE_LEVELBARD = 241 IE_LEVELCLERIC = 242 IE_LEVELDRUID = 243 IE_LEVELMONK = 244 IE_LEVELPALADIN = 245 IE_LEVELRANGER = 246 IE_LEVELSORCERER = 247 #248 IE_LEVELCLASS12 #249 IE_LEVELCLASS13 #the remaining six stats are spell states IE_SPLSTATE_ID1 = 250 #these stats exist only in PC's (but we access only PCs anyway) IE_EXPERTISE = 0x1003 IE_POWERATTACK = 0x1004 IE_ARTERIAL_STRIKE = 0x1005 IE_HAMSTRING = 0x1006 IE_RAPID_SHOT = 0x1007 # End of file ie_stats.py
gpl-2.0
williamsbdev/zookeeper
src/contrib/rest/src/python/zkrest.py
115
7227
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import urllib2 import urllib import simplejson from contextlib import contextmanager class RequestWithMethod(urllib2.Request): """ Request class that know how to set the method name """ def __init__(self, *args, **kwargs): urllib2.Request.__init__(self, *args, **kwargs) self._method = None def get_method(self): return self._method or \ urllib2.Request.get_method(self) def set_method(self, method): self._method = method class ZooKeeper(object): class Error(Exception): pass class NotFound(Error): pass class ZNodeExists(Error): pass class InvalidSession(Error): pass class WrongVersion(Error): pass def __init__(self, uri = 'http://localhost:9998'): self._base = uri self._session = None def start_session(self, expire=5, id=None): """ Create a session and return the ID """ if id is None: url = "%s/sessions/v1/?op=create&expire=%d" % (self._base, expire) self._session = self._do_post(url)['id'] else: self._session = id return self._session def close_session(self): """ Close the session on the server """ if self._session is not None: url = '%s/sessions/v1/%s' % (self._base, self._session) self._do_delete(url) self._session = None def heartbeat(self): """ Send a heartbeat request. This is needed in order to keep a session alive """ if self._session is not None: url = '%s/sessions/v1/%s' % (self._base, self._session) self._do_put(url, '') @contextmanager def session(self, *args, **kwargs): """ Session handling using a context manager """ yield self.start_session(*args, **kwargs) self.close_session() def get(self, path): """ Get a node """ url = "%s/znodes/v1%s" % (self._base, path) return self._do_get(url) def get_children(self, path): """ Get all the children for a given path. This function creates a generator """ url = "%s/znodes/v1%s?view=children" % (self._base, path) resp = self._do_get(url) for child in resp.get('children', []): try: yield self._do_get(resp['child_uri_template']\ .replace('{child}', urllib2.quote(child))) except ZooKeeper.NotFound: continue def create(self, path, data=None, sequence=False, ephemeral=False): """ Create a new node. By default this call creates a persistent znode. You can also create an ephemeral or a sequential znode. """ ri = path.rindex('/') head, name = path[:ri+1], path[ri+1:] if head != '/': head = head[:-1] flags = { 'null': 'true' if data is None else 'false', 'ephemeral': 'true' if ephemeral else 'false', 'sequence': 'true' if sequence else 'false' } if ephemeral: if self._session: flags['session'] = self._session else: raise ZooKeeper.Error, 'You need a session '\ 'to create an ephemeral node' flags = urllib.urlencode(flags) url = "%s/znodes/v1%s?op=create&name=%s&%s" % \ (self._base, head, name, flags) return self._do_post(url, data) def set(self, path, data=None, version=-1, null=False): """ Set the value of node """ url = "%s/znodes/v1%s?%s" % (self._base, path, \ urllib.urlencode({ 'version': version, 'null': 'true' if null else 'false' })) return self._do_put(url, data) def delete(self, path, version=-1): """ Delete a znode """ if type(path) is list: map(lambda el: self.delete(el, version), path) return url = '%s/znodes/v1%s?%s' % (self._base, path, \ urllib.urlencode({ 'version':version })) try: return self._do_delete(url) except urllib2.HTTPError, e: if e.code == 412: raise ZooKeeper.WrongVersion(path) elif e.code == 404: raise ZooKeeper.NotFound(path) raise def exists(self, path): """ Do a znode exists """ try: self.get(path) return True except ZooKeeper.NotFound: return False def _do_get(self, uri): """ Send a GET request and convert errors to exceptions """ try: req = urllib2.urlopen(uri) resp = simplejson.load(req) if 'Error' in resp: raise ZooKeeper.Error(resp['Error']) return resp except urllib2.HTTPError, e: if e.code == 404: raise ZooKeeper.NotFound(uri) raise def _do_post(self, uri, data=None): """ Send a POST request and convert errors to exceptions """ try: req = urllib2.Request(uri, {}) req.add_header('Content-Type', 'application/octet-stream') if data is not None: req.add_data(data) resp = simplejson.load(urllib2.urlopen(req)) if 'Error' in resp: raise ZooKeeper.Error(resp['Error']) return resp except urllib2.HTTPError, e: if e.code == 201: return True elif e.code == 409: raise ZooKeeper.ZNodeExists(uri) elif e.code == 401: raise ZooKeeper.InvalidSession(uri) raise def _do_delete(self, uri): """ Send a DELETE request """ req = RequestWithMethod(uri) req.set_method('DELETE') req.add_header('Content-Type', 'application/octet-stream') return urllib2.urlopen(req).read() def _do_put(self, uri, data): """ Send a PUT request """ try: req = RequestWithMethod(uri) req.set_method('PUT') req.add_header('Content-Type', 'application/octet-stream') if data is not None: req.add_data(data) return urllib2.urlopen(req).read() except urllib2.HTTPError, e: if e.code == 412: # precondition failed raise ZooKeeper.WrongVersion(uri) raise
apache-2.0
sivel/ansible-modules-extras
windows/win_unzip.py
13
3761
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Phil Schwartz <schwartzmx@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/>. # this is a windows documentation stub. actual code lives in the .ps1 # file of the same name ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: win_unzip version_added: "2.0" short_description: Unzips compressed files and archives on the Windows node description: - Unzips compressed files and archives. For extracting any compression types other than .zip, the PowerShellCommunityExtensions (PSCX) Module is required. This module (in conjunction with PSCX) has the ability to recursively unzip files within the src zip file provided and also functionality for many other compression types. If the destination directory does not exist, it will be created before unzipping the file. Specifying rm parameter will force removal of the src file after extraction. options: src: description: - File to be unzipped (provide absolute path) required: true dest: description: - Destination of zip file (provide absolute path of directory). If it does not exist, the directory will be created. required: true rm: description: - Remove the zip file, after unzipping required: no choices: - true - false - yes - no default: false recurse: description: - Recursively expand zipped files within the src file. required: no default: false choices: - true - false - yes - no creates: description: - If this file or directory exists the specified src will not be extracted. required: no default: null author: Phil Schwartz ''' EXAMPLES = r''' # This unzips a library that was downloaded with win_get_url, and removes the file after extraction $ ansible -i hosts -m win_unzip -a "src=C:\LibraryToUnzip.zip dest=C:\Lib rm=true" all # Playbook example # Simple unzip --- - name: Unzip a bz2 (BZip) file win_unzip: src: "C:\Users\Phil\Logs.bz2" dest: "C:\Users\Phil\OldLogs" creates: "C:\Users\Phil\OldLogs" # This playbook example unzips a .zip file and recursively decompresses the contained .gz files and removes all unneeded compressed files after completion. --- - name: Unzip ApplicationLogs.zip and decompress all GZipped log files hosts: all gather_facts: false tasks: - name: Recursively decompress GZ files in ApplicationLogs.zip win_unzip: src: C:\Downloads\ApplicationLogs.zip dest: C:\Application\Logs recurse: yes rm: true # Install PSCX to use for extracting a gz file - name: Grab PSCX msi win_get_url: url: 'http://download-codeplex.sec.s-msft.com/Download/Release?ProjectName=pscx&DownloadId=923562&FileTime=130585918034470000&Build=20959' dest: 'C:\pscx.msi' - name: Install PSCX win_msi: path: 'C:\pscx.msi' - name: Unzip gz log win_unzip: src: "C:\Logs\application-error-logs.gz" dest: "C:\ExtractedLogs\application-error-logs" '''
gpl-3.0
mdblv2/joatu-django
application/site-packages/django/core/servers/fastcgi.py
241
6638
""" FastCGI (or SCGI, or AJP1.3 ...) server that implements the WSGI protocol. Uses the flup python package: http://www.saddi.com/software/flup/ This is a adaptation of the flup package to add FastCGI server support to run Django apps from Web servers that support the FastCGI protocol. This module can be run standalone or from the django-admin / manage.py scripts using the "runfcgi" directive. Run with the extra option "help" for a list of additional options you can pass to this server. """ import os import sys from django.utils import importlib __version__ = "0.1" __all__ = ["runfastcgi"] FASTCGI_OPTIONS = { 'protocol': 'fcgi', 'host': None, 'port': None, 'socket': None, 'method': 'fork', 'daemonize': None, 'workdir': '/', 'pidfile': None, 'maxspare': 5, 'minspare': 2, 'maxchildren': 50, 'maxrequests': 0, 'debug': None, 'outlog': None, 'errlog': None, 'umask': None, } FASTCGI_HELP = r""" Run this project as a fastcgi (or some other protocol supported by flup) application. To do this, the flup package from http://www.saddi.com/software/flup/ is required. runfcgi [options] [fcgi settings] Optional Fcgi settings: (setting=value) protocol=PROTOCOL fcgi, scgi, ajp, ... (default %(protocol)s) host=HOSTNAME hostname to listen on. port=PORTNUM port to listen on. socket=FILE UNIX socket to listen on. method=IMPL prefork or threaded (default %(method)s). maxrequests=NUMBER number of requests a child handles before it is killed and a new child is forked (0 = no limit). maxspare=NUMBER max number of spare processes / threads (default %(maxspare)s). minspare=NUMBER min number of spare processes / threads (default %(minspare)s). maxchildren=NUMBER hard limit number of processes / threads (default %(maxchildren)s). daemonize=BOOL whether to detach from terminal. pidfile=FILE write the spawned process-id to this file. workdir=DIRECTORY change to this directory when daemonizing (default %(workdir)s). debug=BOOL set to true to enable flup tracebacks. outlog=FILE write stdout to this file. errlog=FILE write stderr to this file. umask=UMASK umask to use when daemonizing, in octal notation (default 022). Examples: Run a "standard" fastcgi process on a file-descriptor (for Web servers which spawn your processes for you) $ manage.py runfcgi method=threaded Run a scgi server on a TCP host/port $ manage.py runfcgi protocol=scgi method=prefork host=127.0.0.1 port=8025 Run a fastcgi server on a UNIX domain socket (posix platforms only) $ manage.py runfcgi method=prefork socket=/tmp/fcgi.sock Run a fastCGI as a daemon and write the spawned PID in a file $ manage.py runfcgi socket=/tmp/fcgi.sock method=prefork \ daemonize=true pidfile=/var/run/django-fcgi.pid """ % FASTCGI_OPTIONS def fastcgi_help(message=None): print(FASTCGI_HELP) if message: print(message) return False def runfastcgi(argset=[], **kwargs): options = FASTCGI_OPTIONS.copy() options.update(kwargs) for x in argset: if "=" in x: k, v = x.split('=', 1) else: k, v = x, True options[k.lower()] = v if "help" in options: return fastcgi_help() try: import flup except ImportError as e: sys.stderr.write("ERROR: %s\n" % e) sys.stderr.write(" Unable to load the flup package. In order to run django\n") sys.stderr.write(" as a FastCGI application, you will need to get flup from\n") sys.stderr.write(" http://www.saddi.com/software/flup/ If you've already\n") sys.stderr.write(" installed flup, then make sure you have it in your PYTHONPATH.\n") return False flup_module = 'server.' + options['protocol'] if options['method'] in ('prefork', 'fork'): wsgi_opts = { 'maxSpare': int(options["maxspare"]), 'minSpare': int(options["minspare"]), 'maxChildren': int(options["maxchildren"]), 'maxRequests': int(options["maxrequests"]), } flup_module += '_fork' elif options['method'] in ('thread', 'threaded'): wsgi_opts = { 'maxSpare': int(options["maxspare"]), 'minSpare': int(options["minspare"]), 'maxThreads': int(options["maxchildren"]), } else: return fastcgi_help("ERROR: Implementation must be one of prefork or " "thread.") wsgi_opts['debug'] = options['debug'] is not None try: module = importlib.import_module('.%s' % flup_module, 'flup') WSGIServer = module.WSGIServer except Exception: print("Can't import flup." + flup_module) return False # Prep up and go from django.core.servers.basehttp import get_internal_wsgi_application if options["host"] and options["port"] and not options["socket"]: wsgi_opts['bindAddress'] = (options["host"], int(options["port"])) elif options["socket"] and not options["host"] and not options["port"]: wsgi_opts['bindAddress'] = options["socket"] elif not options["socket"] and not options["host"] and not options["port"]: wsgi_opts['bindAddress'] = None else: return fastcgi_help("Invalid combination of host, port, socket.") if options["daemonize"] is None: # Default to daemonizing if we're running on a socket/named pipe. daemonize = (wsgi_opts['bindAddress'] is not None) else: if options["daemonize"].lower() in ('true', 'yes', 't'): daemonize = True elif options["daemonize"].lower() in ('false', 'no', 'f'): daemonize = False else: return fastcgi_help("ERROR: Invalid option for daemonize " "parameter.") daemon_kwargs = {} if options['outlog']: daemon_kwargs['out_log'] = options['outlog'] if options['errlog']: daemon_kwargs['err_log'] = options['errlog'] if options['umask']: daemon_kwargs['umask'] = int(options['umask'], 8) if daemonize: from django.utils.daemonize import become_daemon become_daemon(our_home_dir=options["workdir"], **daemon_kwargs) if options["pidfile"]: with open(options["pidfile"], "w") as fp: fp.write("%d\n" % os.getpid()) WSGIServer(get_internal_wsgi_application(), **wsgi_opts).run() if __name__ == '__main__': runfastcgi(sys.argv[1:])
apache-2.0
agilgur5/LTLMoP
dist/gitUtils.py
7
1917
import subprocess import time import sys import os def ensureGitBash(script_path): # If on Windows, use Git Bash for the shell if sys.platform in ['win32', 'cygwin']: # Check if we have access to bash cmd = subprocess.Popen(["bash", "--version"],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) # Wait for subprocess to finish while cmd.returncode is None: cmd.poll() time.sleep(0.01) if cmd.returncode != 0: print "Trying to use Git Bash..." bash_path = None for ev in ["ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"]: if ev not in os.environ: continue bp = os.path.join(os.environ[ev], 'Git', 'bin', 'bash.exe') if os.path.exists(bp): bash_path = bp break if bash_path is None: print "Couldn't find Git Bash. Please install Git for Windows." print "(See http://code.google.com/p/msysgit/)" print print "Press [Enter] to quit..." raw_input() sys.exit(1) print "Found Git Bash at %s" % bash_path cmd = subprocess.Popen([bash_path, "--login", "-i", "-c", '"%s" "%s"' % (sys.executable, os.path.abspath(script_path))]) # Wait for subprocess to finish try: while cmd.returncode is None: cmd.poll() time.sleep(0.01) except KeyboardInterrupt: cmd.kill() sys.exit(0) if __name__ == "__main__": ensureGitBash(__file__) cmd = subprocess.Popen(["git", "status"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False) print cmd.communicate()[0] raw_input("Press any key to quit...")
gpl-3.0
unaizalakain/django
tests/template_tests/filter_tests/test_rjust.py
521
1030
from django.template.defaultfilters import rjust from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class RjustTests(SimpleTestCase): @setup({'rjust01': '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}'}) def test_rjust01(self): output = self.engine.render_to_string('rjust01', {"a": "a&b", "b": mark_safe("a&b")}) self.assertEqual(output, ". a&b. . a&b.") @setup({'rjust02': '.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'}) def test_rjust02(self): output = self.engine.render_to_string('rjust02', {"a": "a&b", "b": mark_safe("a&b")}) self.assertEqual(output, ". a&amp;b. . a&b.") class FunctionTests(SimpleTestCase): def test_rjust(self): self.assertEqual(rjust('test', 10), ' test') def test_less_than_string_length(self): self.assertEqual(rjust('test', 3), 'test') def test_non_string_input(self): self.assertEqual(rjust(123, 4), ' 123')
bsd-3-clause
markeTIC/OCB
addons/stock/tests/test_resupply.py
214
2457
# -*- coding: utf-8 -*- from openerp.addons.stock.tests.common import TestStockCommon from openerp.tools import mute_logger, float_round class TestResupply(TestStockCommon): def setUp(self): super(TestResupply, self).setUp() self.Warehouse = self.env['stock.warehouse'] # create 2 WH, BIG and SMALL # SMALL resupplies from BIG self.bigwh = self.Warehouse.create({'name': 'BIG', 'code': 'B'}) self.smallwh = self.Warehouse.create({'name': 'SMALL', 'code': 'S', 'default_resupply_wh_id': self.bigwh.id, 'resupply_wh_ids': [(6, 0, [self.bigwh.id])], }) # minimum stock rule for Product A on SMALL Orderpoint = self.env['stock.warehouse.orderpoint'] Orderpoint.create({'warehouse_id': self.smallwh.id, 'location_id': self.smallwh.lot_stock_id.id, 'product_id': self.productA.id, 'product_min_qty': 100, 'product_max_qty': 200, 'product_uom': self.uom_unit.id, }) # create some stock on BIG Wiz = self.env['stock.change.product.qty'] wiz = Wiz.create({'product_id': self.productA.id, 'new_quantity': 1000, 'location_id': self.bigwh.lot_stock_id.id, }) wiz.change_product_qty() def test_resupply_from_wh(self): sched = self.env['procurement.order'] sched.run_scheduler() # we generated 2 procurements for product A: one on small wh and the # other one on the transit location procs = sched.search([('product_id', '=', self.productA.id)]) self.assertEqual(len(procs), 2) proc1 = sched.search([('product_id', '=', self.productA.id), ('warehouse_id', '=', self.smallwh.id)]) self.assertEqual(proc1.state, 'running') proc2 = sched.search([('product_id', '=', self.productA.id), ('warehouse_id', '=', self.bigwh.id)]) self.assertEqual(proc2.location_id.usage, 'transit') self.assertNotEqual(proc2.state, 'exception') proc2.run() self.assertEqual(proc2.state, 'running') self.assertTrue(proc2.rule_id)
agpl-3.0
thedep2/CouchPotatoServer
libs/requests/packages/chardet/jpcntx.py
949
19104
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # 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 ######################### from .compat import wrap_ord NUM_OF_CATEGORY = 6 DONT_KNOW = -1 ENOUGH_REL_THRESHOLD = 100 MAX_REL_THRESHOLD = 1000 MINIMUM_DATA_THRESHOLD = 4 # This is hiragana 2-char sequence table, the number in each cell represents its frequency category jp2CharContext = ( (0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1), (2,4,0,4,0,3,0,4,0,3,4,4,4,2,4,3,3,4,3,2,3,3,4,2,3,3,3,2,4,1,4,3,3,1,5,4,3,4,3,4,3,5,3,0,3,5,4,2,0,3,1,0,3,3,0,3,3,0,1,1,0,4,3,0,3,3,0,4,0,2,0,3,5,5,5,5,4,0,4,1,0,3,4), (0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2), (0,4,0,5,0,5,0,4,0,4,5,4,4,3,5,3,5,1,5,3,4,3,4,4,3,4,3,3,4,3,5,4,4,3,5,5,3,5,5,5,3,5,5,3,4,5,5,3,1,3,2,0,3,4,0,4,2,0,4,2,1,5,3,2,3,5,0,4,0,2,0,5,4,4,5,4,5,0,4,0,0,4,4), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,3,0,4,0,3,0,3,0,4,5,4,3,3,3,3,4,3,5,4,4,3,5,4,4,3,4,3,4,4,4,4,5,3,4,4,3,4,5,5,4,5,5,1,4,5,4,3,0,3,3,1,3,3,0,4,4,0,3,3,1,5,3,3,3,5,0,4,0,3,0,4,4,3,4,3,3,0,4,1,1,3,4), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,4,0,3,0,3,0,4,0,3,4,4,3,2,2,1,2,1,3,1,3,3,3,3,3,4,3,1,3,3,5,3,3,0,4,3,0,5,4,3,3,5,4,4,3,4,4,5,0,1,2,0,1,2,0,2,2,0,1,0,0,5,2,2,1,4,0,3,0,1,0,4,4,3,5,4,3,0,2,1,0,4,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,3,0,5,0,4,0,2,1,4,4,2,4,1,4,2,4,2,4,3,3,3,4,3,3,3,3,1,4,2,3,3,3,1,4,4,1,1,1,4,3,3,2,0,2,4,3,2,0,3,3,0,3,1,1,0,0,0,3,3,0,4,2,2,3,4,0,4,0,3,0,4,4,5,3,4,4,0,3,0,0,1,4), (1,4,0,4,0,4,0,4,0,3,5,4,4,3,4,3,5,4,3,3,4,3,5,4,4,4,4,3,4,2,4,3,3,1,5,4,3,2,4,5,4,5,5,4,4,5,4,4,0,3,2,2,3,3,0,4,3,1,3,2,1,4,3,3,4,5,0,3,0,2,0,4,5,5,4,5,4,0,4,0,0,5,4), (0,5,0,5,0,4,0,3,0,4,4,3,4,3,3,3,4,0,4,4,4,3,4,3,4,3,3,1,4,2,4,3,4,0,5,4,1,4,5,4,4,5,3,2,4,3,4,3,2,4,1,3,3,3,2,3,2,0,4,3,3,4,3,3,3,4,0,4,0,3,0,4,5,4,4,4,3,0,4,1,0,1,3), (0,3,1,4,0,3,0,2,0,3,4,4,3,1,4,2,3,3,4,3,4,3,4,3,4,4,3,2,3,1,5,4,4,1,4,4,3,5,4,4,3,5,5,4,3,4,4,3,1,2,3,1,2,2,0,3,2,0,3,1,0,5,3,3,3,4,3,3,3,3,4,4,4,4,5,4,2,0,3,3,2,4,3), (0,2,0,3,0,1,0,1,0,0,3,2,0,0,2,0,1,0,2,1,3,3,3,1,2,3,1,0,1,0,4,2,1,1,3,3,0,4,3,3,1,4,3,3,0,3,3,2,0,0,0,0,1,0,0,2,0,0,0,0,0,4,1,0,2,3,2,2,2,1,3,3,3,4,4,3,2,0,3,1,0,3,3), (0,4,0,4,0,3,0,3,0,4,4,4,3,3,3,3,3,3,4,3,4,2,4,3,4,3,3,2,4,3,4,5,4,1,4,5,3,5,4,5,3,5,4,0,3,5,5,3,1,3,3,2,2,3,0,3,4,1,3,3,2,4,3,3,3,4,0,4,0,3,0,4,5,4,4,5,3,0,4,1,0,3,4), (0,2,0,3,0,3,0,0,0,2,2,2,1,0,1,0,0,0,3,0,3,0,3,0,1,3,1,0,3,1,3,3,3,1,3,3,3,0,1,3,1,3,4,0,0,3,1,1,0,3,2,0,0,0,0,1,3,0,1,0,0,3,3,2,0,3,0,0,0,0,0,3,4,3,4,3,3,0,3,0,0,2,3), (2,3,0,3,0,2,0,1,0,3,3,4,3,1,3,1,1,1,3,1,4,3,4,3,3,3,0,0,3,1,5,4,3,1,4,3,2,5,5,4,4,4,4,3,3,4,4,4,0,2,1,1,3,2,0,1,2,0,0,1,0,4,1,3,3,3,0,3,0,1,0,4,4,4,5,5,3,0,2,0,0,4,4), (0,2,0,1,0,3,1,3,0,2,3,3,3,0,3,1,0,0,3,0,3,2,3,1,3,2,1,1,0,0,4,2,1,0,2,3,1,4,3,2,0,4,4,3,1,3,1,3,0,1,0,0,1,0,0,0,1,0,0,0,0,4,1,1,1,2,0,3,0,0,0,3,4,2,4,3,2,0,1,0,0,3,3), (0,1,0,4,0,5,0,4,0,2,4,4,2,3,3,2,3,3,5,3,3,3,4,3,4,2,3,0,4,3,3,3,4,1,4,3,2,1,5,5,3,4,5,1,3,5,4,2,0,3,3,0,1,3,0,4,2,0,1,3,1,4,3,3,3,3,0,3,0,1,0,3,4,4,4,5,5,0,3,0,1,4,5), (0,2,0,3,0,3,0,0,0,2,3,1,3,0,4,0,1,1,3,0,3,4,3,2,3,1,0,3,3,2,3,1,3,0,2,3,0,2,1,4,1,2,2,0,0,3,3,0,0,2,0,0,0,1,0,0,0,0,2,2,0,3,2,1,3,3,0,2,0,2,0,0,3,3,1,2,4,0,3,0,2,2,3), (2,4,0,5,0,4,0,4,0,2,4,4,4,3,4,3,3,3,1,2,4,3,4,3,4,4,5,0,3,3,3,3,2,0,4,3,1,4,3,4,1,4,4,3,3,4,4,3,1,2,3,0,4,2,0,4,1,0,3,3,0,4,3,3,3,4,0,4,0,2,0,3,5,3,4,5,2,0,3,0,0,4,5), (0,3,0,4,0,1,0,1,0,1,3,2,2,1,3,0,3,0,2,0,2,0,3,0,2,0,0,0,1,0,1,1,0,0,3,1,0,0,0,4,0,3,1,0,2,1,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,2,2,3,1,0,3,0,0,0,1,4,4,4,3,0,0,4,0,0,1,4), (1,4,1,5,0,3,0,3,0,4,5,4,4,3,5,3,3,4,4,3,4,1,3,3,3,3,2,1,4,1,5,4,3,1,4,4,3,5,4,4,3,5,4,3,3,4,4,4,0,3,3,1,2,3,0,3,1,0,3,3,0,5,4,4,4,4,4,4,3,3,5,4,4,3,3,5,4,0,3,2,0,4,4), (0,2,0,3,0,1,0,0,0,1,3,3,3,2,4,1,3,0,3,1,3,0,2,2,1,1,0,0,2,0,4,3,1,0,4,3,0,4,4,4,1,4,3,1,1,3,3,1,0,2,0,0,1,3,0,0,0,0,2,0,0,4,3,2,4,3,5,4,3,3,3,4,3,3,4,3,3,0,2,1,0,3,3), (0,2,0,4,0,3,0,2,0,2,5,5,3,4,4,4,4,1,4,3,3,0,4,3,4,3,1,3,3,2,4,3,0,3,4,3,0,3,4,4,2,4,4,0,4,5,3,3,2,2,1,1,1,2,0,1,5,0,3,3,2,4,3,3,3,4,0,3,0,2,0,4,4,3,5,5,0,0,3,0,2,3,3), (0,3,0,4,0,3,0,1,0,3,4,3,3,1,3,3,3,0,3,1,3,0,4,3,3,1,1,0,3,0,3,3,0,0,4,4,0,1,5,4,3,3,5,0,3,3,4,3,0,2,0,1,1,1,0,1,3,0,1,2,1,3,3,2,3,3,0,3,0,1,0,1,3,3,4,4,1,0,1,2,2,1,3), (0,1,0,4,0,4,0,3,0,1,3,3,3,2,3,1,1,0,3,0,3,3,4,3,2,4,2,0,1,0,4,3,2,0,4,3,0,5,3,3,2,4,4,4,3,3,3,4,0,1,3,0,0,1,0,0,1,0,0,0,0,4,2,3,3,3,0,3,0,0,0,4,4,4,5,3,2,0,3,3,0,3,5), (0,2,0,3,0,0,0,3,0,1,3,0,2,0,0,0,1,0,3,1,1,3,3,0,0,3,0,0,3,0,2,3,1,0,3,1,0,3,3,2,0,4,2,2,0,2,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,2,1,2,0,1,0,1,0,0,0,1,3,1,2,0,0,0,1,0,0,1,4), (0,3,0,3,0,5,0,1,0,2,4,3,1,3,3,2,1,1,5,2,1,0,5,1,2,0,0,0,3,3,2,2,3,2,4,3,0,0,3,3,1,3,3,0,2,5,3,4,0,3,3,0,1,2,0,2,2,0,3,2,0,2,2,3,3,3,0,2,0,1,0,3,4,4,2,5,4,0,3,0,0,3,5), (0,3,0,3,0,3,0,1,0,3,3,3,3,0,3,0,2,0,2,1,1,0,2,0,1,0,0,0,2,1,0,0,1,0,3,2,0,0,3,3,1,2,3,1,0,3,3,0,0,1,0,0,0,0,0,2,0,0,0,0,0,2,3,1,2,3,0,3,0,1,0,3,2,1,0,4,3,0,1,1,0,3,3), (0,4,0,5,0,3,0,3,0,4,5,5,4,3,5,3,4,3,5,3,3,2,5,3,4,4,4,3,4,3,4,5,5,3,4,4,3,4,4,5,4,4,4,3,4,5,5,4,2,3,4,2,3,4,0,3,3,1,4,3,2,4,3,3,5,5,0,3,0,3,0,5,5,5,5,4,4,0,4,0,1,4,4), (0,4,0,4,0,3,0,3,0,3,5,4,4,2,3,2,5,1,3,2,5,1,4,2,3,2,3,3,4,3,3,3,3,2,5,4,1,3,3,5,3,4,4,0,4,4,3,1,1,3,1,0,2,3,0,2,3,0,3,0,0,4,3,1,3,4,0,3,0,2,0,4,4,4,3,4,5,0,4,0,0,3,4), (0,3,0,3,0,3,1,2,0,3,4,4,3,3,3,0,2,2,4,3,3,1,3,3,3,1,1,0,3,1,4,3,2,3,4,4,2,4,4,4,3,4,4,3,2,4,4,3,1,3,3,1,3,3,0,4,1,0,2,2,1,4,3,2,3,3,5,4,3,3,5,4,4,3,3,0,4,0,3,2,2,4,4), (0,2,0,1,0,0,0,0,0,1,2,1,3,0,0,0,0,0,2,0,1,2,1,0,0,1,0,0,0,0,3,0,0,1,0,1,1,3,1,0,0,0,1,1,0,1,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,1,2,2,0,3,4,0,0,0,1,1,0,0,1,0,0,0,0,0,1,1), (0,1,0,0,0,1,0,0,0,0,4,0,4,1,4,0,3,0,4,0,3,0,4,0,3,0,3,0,4,1,5,1,4,0,0,3,0,5,0,5,2,0,1,0,0,0,2,1,4,0,1,3,0,0,3,0,0,3,1,1,4,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0), (1,4,0,5,0,3,0,2,0,3,5,4,4,3,4,3,5,3,4,3,3,0,4,3,3,3,3,3,3,2,4,4,3,1,3,4,4,5,4,4,3,4,4,1,3,5,4,3,3,3,1,2,2,3,3,1,3,1,3,3,3,5,3,3,4,5,0,3,0,3,0,3,4,3,4,4,3,0,3,0,2,4,3), (0,1,0,4,0,0,0,0,0,1,4,0,4,1,4,2,4,0,3,0,1,0,1,0,0,0,0,0,2,0,3,1,1,1,0,3,0,0,0,1,2,1,0,0,1,1,1,1,0,1,0,0,0,1,0,0,3,0,0,0,0,3,2,0,2,2,0,1,0,0,0,2,3,2,3,3,0,0,0,0,2,1,0), (0,5,1,5,0,3,0,3,0,5,4,4,5,1,5,3,3,0,4,3,4,3,5,3,4,3,3,2,4,3,4,3,3,0,3,3,1,4,4,3,4,4,4,3,4,5,5,3,2,3,1,1,3,3,1,3,1,1,3,3,2,4,5,3,3,5,0,4,0,3,0,4,4,3,5,3,3,0,3,4,0,4,3), (0,5,0,5,0,3,0,2,0,4,4,3,5,2,4,3,3,3,4,4,4,3,5,3,5,3,3,1,4,0,4,3,3,0,3,3,0,4,4,4,4,5,4,3,3,5,5,3,2,3,1,2,3,2,0,1,0,0,3,2,2,4,4,3,1,5,0,4,0,3,0,4,3,1,3,2,1,0,3,3,0,3,3), (0,4,0,5,0,5,0,4,0,4,5,5,5,3,4,3,3,2,5,4,4,3,5,3,5,3,4,0,4,3,4,4,3,2,4,4,3,4,5,4,4,5,5,0,3,5,5,4,1,3,3,2,3,3,1,3,1,0,4,3,1,4,4,3,4,5,0,4,0,2,0,4,3,4,4,3,3,0,4,0,0,5,5), (0,4,0,4,0,5,0,1,1,3,3,4,4,3,4,1,3,0,5,1,3,0,3,1,3,1,1,0,3,0,3,3,4,0,4,3,0,4,4,4,3,4,4,0,3,5,4,1,0,3,0,0,2,3,0,3,1,0,3,1,0,3,2,1,3,5,0,3,0,1,0,3,2,3,3,4,4,0,2,2,0,4,4), (2,4,0,5,0,4,0,3,0,4,5,5,4,3,5,3,5,3,5,3,5,2,5,3,4,3,3,4,3,4,5,3,2,1,5,4,3,2,3,4,5,3,4,1,2,5,4,3,0,3,3,0,3,2,0,2,3,0,4,1,0,3,4,3,3,5,0,3,0,1,0,4,5,5,5,4,3,0,4,2,0,3,5), (0,5,0,4,0,4,0,2,0,5,4,3,4,3,4,3,3,3,4,3,4,2,5,3,5,3,4,1,4,3,4,4,4,0,3,5,0,4,4,4,4,5,3,1,3,4,5,3,3,3,3,3,3,3,0,2,2,0,3,3,2,4,3,3,3,5,3,4,1,3,3,5,3,2,0,0,0,0,4,3,1,3,3), (0,1,0,3,0,3,0,1,0,1,3,3,3,2,3,3,3,0,3,0,0,0,3,1,3,0,0,0,2,2,2,3,0,0,3,2,0,1,2,4,1,3,3,0,0,3,3,3,0,1,0,0,2,1,0,0,3,0,3,1,0,3,0,0,1,3,0,2,0,1,0,3,3,1,3,3,0,0,1,1,0,3,3), (0,2,0,3,0,2,1,4,0,2,2,3,1,1,3,1,1,0,2,0,3,1,2,3,1,3,0,0,1,0,4,3,2,3,3,3,1,4,2,3,3,3,3,1,0,3,1,4,0,1,1,0,1,2,0,1,1,0,1,1,0,3,1,3,2,2,0,1,0,0,0,2,3,3,3,1,0,0,0,0,0,2,3), (0,5,0,4,0,5,0,2,0,4,5,5,3,3,4,3,3,1,5,4,4,2,4,4,4,3,4,2,4,3,5,5,4,3,3,4,3,3,5,5,4,5,5,1,3,4,5,3,1,4,3,1,3,3,0,3,3,1,4,3,1,4,5,3,3,5,0,4,0,3,0,5,3,3,1,4,3,0,4,0,1,5,3), (0,5,0,5,0,4,0,2,0,4,4,3,4,3,3,3,3,3,5,4,4,4,4,4,4,5,3,3,5,2,4,4,4,3,4,4,3,3,4,4,5,5,3,3,4,3,4,3,3,4,3,3,3,3,1,2,2,1,4,3,3,5,4,4,3,4,0,4,0,3,0,4,4,4,4,4,1,0,4,2,0,2,4), (0,4,0,4,0,3,0,1,0,3,5,2,3,0,3,0,2,1,4,2,3,3,4,1,4,3,3,2,4,1,3,3,3,0,3,3,0,0,3,3,3,5,3,3,3,3,3,2,0,2,0,0,2,0,0,2,0,0,1,0,0,3,1,2,2,3,0,3,0,2,0,4,4,3,3,4,1,0,3,0,0,2,4), (0,0,0,4,0,0,0,0,0,0,1,0,1,0,2,0,0,0,0,0,1,0,2,0,1,0,0,0,0,0,3,1,3,0,3,2,0,0,0,1,0,3,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,0,2,0,0,0,0,0,0,2), (0,2,1,3,0,2,0,2,0,3,3,3,3,1,3,1,3,3,3,3,3,3,4,2,2,1,2,1,4,0,4,3,1,3,3,3,2,4,3,5,4,3,3,3,3,3,3,3,0,1,3,0,2,0,0,1,0,0,1,0,0,4,2,0,2,3,0,3,3,0,3,3,4,2,3,1,4,0,1,2,0,2,3), (0,3,0,3,0,1,0,3,0,2,3,3,3,0,3,1,2,0,3,3,2,3,3,2,3,2,3,1,3,0,4,3,2,0,3,3,1,4,3,3,2,3,4,3,1,3,3,1,1,0,1,1,0,1,0,1,0,1,0,0,0,4,1,1,0,3,0,3,1,0,2,3,3,3,3,3,1,0,0,2,0,3,3), (0,0,0,0,0,0,0,0,0,0,3,0,2,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,3,0,3,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,2,0,2,3,0,0,0,0,0,0,0,0,3), (0,2,0,3,1,3,0,3,0,2,3,3,3,1,3,1,3,1,3,1,3,3,3,1,3,0,2,3,1,1,4,3,3,2,3,3,1,2,2,4,1,3,3,0,1,4,2,3,0,1,3,0,3,0,0,1,3,0,2,0,0,3,3,2,1,3,0,3,0,2,0,3,4,4,4,3,1,0,3,0,0,3,3), (0,2,0,1,0,2,0,0,0,1,3,2,2,1,3,0,1,1,3,0,3,2,3,1,2,0,2,0,1,1,3,3,3,0,3,3,1,1,2,3,2,3,3,1,2,3,2,0,0,1,0,0,0,0,0,0,3,0,1,0,0,2,1,2,1,3,0,3,0,0,0,3,4,4,4,3,2,0,2,0,0,2,4), (0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,3,1,0,0,0,0,0,0,0,3), (0,3,0,3,0,2,0,3,0,3,3,3,2,3,2,2,2,0,3,1,3,3,3,2,3,3,0,0,3,0,3,2,2,0,2,3,1,4,3,4,3,3,2,3,1,5,4,4,0,3,1,2,1,3,0,3,1,1,2,0,2,3,1,3,1,3,0,3,0,1,0,3,3,4,4,2,1,0,2,1,0,2,4), (0,1,0,3,0,1,0,2,0,1,4,2,5,1,4,0,2,0,2,1,3,1,4,0,2,1,0,0,2,1,4,1,1,0,3,3,0,5,1,3,2,3,3,1,0,3,2,3,0,1,0,0,0,0,0,0,1,0,0,0,0,4,0,1,0,3,0,2,0,1,0,3,3,3,4,3,3,0,0,0,0,2,3), (0,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,0,0,1,0,0,0,0,0,3), (0,1,0,3,0,4,0,3,0,2,4,3,1,0,3,2,2,1,3,1,2,2,3,1,1,1,2,1,3,0,1,2,0,1,3,2,1,3,0,5,5,1,0,0,1,3,2,1,0,3,0,0,1,0,0,0,0,0,3,4,0,1,1,1,3,2,0,2,0,1,0,2,3,3,1,2,3,0,1,0,1,0,4), (0,0,0,1,0,3,0,3,0,2,2,1,0,0,4,0,3,0,3,1,3,0,3,0,3,0,1,0,3,0,3,1,3,0,3,3,0,0,1,2,1,1,1,0,1,2,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,2,2,1,2,0,0,2,0,0,0,0,2,3,3,3,3,0,0,0,0,1,4), (0,0,0,3,0,3,0,0,0,0,3,1,1,0,3,0,1,0,2,0,1,0,0,0,0,0,0,0,1,0,3,0,2,0,2,3,0,0,2,2,3,1,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,2,0,0,0,0,2,3), (2,4,0,5,0,5,0,4,0,3,4,3,3,3,4,3,3,3,4,3,4,4,5,4,5,5,5,2,3,0,5,5,4,1,5,4,3,1,5,4,3,4,4,3,3,4,3,3,0,3,2,0,2,3,0,3,0,0,3,3,0,5,3,2,3,3,0,3,0,3,0,3,4,5,4,5,3,0,4,3,0,3,4), (0,3,0,3,0,3,0,3,0,3,3,4,3,2,3,2,3,0,4,3,3,3,3,3,3,3,3,0,3,2,4,3,3,1,3,4,3,4,4,4,3,4,4,3,2,4,4,1,0,2,0,0,1,1,0,2,0,0,3,1,0,5,3,2,1,3,0,3,0,1,2,4,3,2,4,3,3,0,3,2,0,4,4), (0,3,0,3,0,1,0,0,0,1,4,3,3,2,3,1,3,1,4,2,3,2,4,2,3,4,3,0,2,2,3,3,3,0,3,3,3,0,3,4,1,3,3,0,3,4,3,3,0,1,1,0,1,0,0,0,4,0,3,0,0,3,1,2,1,3,0,4,0,1,0,4,3,3,4,3,3,0,2,0,0,3,3), (0,3,0,4,0,1,0,3,0,3,4,3,3,0,3,3,3,1,3,1,3,3,4,3,3,3,0,0,3,1,5,3,3,1,3,3,2,5,4,3,3,4,5,3,2,5,3,4,0,1,0,0,0,0,0,2,0,0,1,1,0,4,2,2,1,3,0,3,0,2,0,4,4,3,5,3,2,0,1,1,0,3,4), (0,5,0,4,0,5,0,2,0,4,4,3,3,2,3,3,3,1,4,3,4,1,5,3,4,3,4,0,4,2,4,3,4,1,5,4,0,4,4,4,4,5,4,1,3,5,4,2,1,4,1,1,3,2,0,3,1,0,3,2,1,4,3,3,3,4,0,4,0,3,0,4,4,4,3,3,3,0,4,2,0,3,4), (1,4,0,4,0,3,0,1,0,3,3,3,1,1,3,3,2,2,3,3,1,0,3,2,2,1,2,0,3,1,2,1,2,0,3,2,0,2,2,3,3,4,3,0,3,3,1,2,0,1,1,3,1,2,0,0,3,0,1,1,0,3,2,2,3,3,0,3,0,0,0,2,3,3,4,3,3,0,1,0,0,1,4), (0,4,0,4,0,4,0,0,0,3,4,4,3,1,4,2,3,2,3,3,3,1,4,3,4,0,3,0,4,2,3,3,2,2,5,4,2,1,3,4,3,4,3,1,3,3,4,2,0,2,1,0,3,3,0,0,2,0,3,1,0,4,4,3,4,3,0,4,0,1,0,2,4,4,4,4,4,0,3,2,0,3,3), (0,0,0,1,0,4,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,3,2,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,2), (0,2,0,3,0,4,0,4,0,1,3,3,3,0,4,0,2,1,2,1,1,1,2,0,3,1,1,0,1,0,3,1,0,0,3,3,2,0,1,1,0,0,0,0,0,1,0,2,0,2,2,0,3,1,0,0,1,0,1,1,0,1,2,0,3,0,0,0,0,1,0,0,3,3,4,3,1,0,1,0,3,0,2), (0,0,0,3,0,5,0,0,0,0,1,0,2,0,3,1,0,1,3,0,0,0,2,0,0,0,1,0,0,0,1,1,0,0,4,0,0,0,2,3,0,1,4,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,3,0,0,0,0,0,3), (0,2,0,5,0,5,0,1,0,2,4,3,3,2,5,1,3,2,3,3,3,0,4,1,2,0,3,0,4,0,2,2,1,1,5,3,0,0,1,4,2,3,2,0,3,3,3,2,0,2,4,1,1,2,0,1,1,0,3,1,0,1,3,1,2,3,0,2,0,0,0,1,3,5,4,4,4,0,3,0,0,1,3), (0,4,0,5,0,4,0,4,0,4,5,4,3,3,4,3,3,3,4,3,4,4,5,3,4,5,4,2,4,2,3,4,3,1,4,4,1,3,5,4,4,5,5,4,4,5,5,5,2,3,3,1,4,3,1,3,3,0,3,3,1,4,3,4,4,4,0,3,0,4,0,3,3,4,4,5,0,0,4,3,0,4,5), (0,4,0,4,0,3,0,3,0,3,4,4,4,3,3,2,4,3,4,3,4,3,5,3,4,3,2,1,4,2,4,4,3,1,3,4,2,4,5,5,3,4,5,4,1,5,4,3,0,3,2,2,3,2,1,3,1,0,3,3,3,5,3,3,3,5,4,4,2,3,3,4,3,3,3,2,1,0,3,2,1,4,3), (0,4,0,5,0,4,0,3,0,3,5,5,3,2,4,3,4,0,5,4,4,1,4,4,4,3,3,3,4,3,5,5,2,3,3,4,1,2,5,5,3,5,5,2,3,5,5,4,0,3,2,0,3,3,1,1,5,1,4,1,0,4,3,2,3,5,0,4,0,3,0,5,4,3,4,3,0,0,4,1,0,4,4), (1,3,0,4,0,2,0,2,0,2,5,5,3,3,3,3,3,0,4,2,3,4,4,4,3,4,0,0,3,4,5,4,3,3,3,3,2,5,5,4,5,5,5,4,3,5,5,5,1,3,1,0,1,0,0,3,2,0,4,2,0,5,2,3,2,4,1,3,0,3,0,4,5,4,5,4,3,0,4,2,0,5,4), (0,3,0,4,0,5,0,3,0,3,4,4,3,2,3,2,3,3,3,3,3,2,4,3,3,2,2,0,3,3,3,3,3,1,3,3,3,0,4,4,3,4,4,1,1,4,4,2,0,3,1,0,1,1,0,4,1,0,2,3,1,3,3,1,3,4,0,3,0,1,0,3,1,3,0,0,1,0,2,0,0,4,4), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,3,0,3,0,2,0,3,0,1,5,4,3,3,3,1,4,2,1,2,3,4,4,2,4,4,5,0,3,1,4,3,4,0,4,3,3,3,2,3,2,5,3,4,3,2,2,3,0,0,3,0,2,1,0,1,2,0,0,0,0,2,1,1,3,1,0,2,0,4,0,3,4,4,4,5,2,0,2,0,0,1,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,4,2,1,1,0,1,0,3,2,0,0,3,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,1,0,0,0,2,0,0,0,1,4,0,4,2,1,0,0,0,0,0,1), (0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,3,1,0,0,0,2,0,2,1,0,0,1,2,1,0,1,1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,1,3,1,0,0,0,0,0,1,0,0,2,1,0,0,0,0,0,0,0,0,2), (0,4,0,4,0,4,0,3,0,4,4,3,4,2,4,3,2,0,4,4,4,3,5,3,5,3,3,2,4,2,4,3,4,3,1,4,0,2,3,4,4,4,3,3,3,4,4,4,3,4,1,3,4,3,2,1,2,1,3,3,3,4,4,3,3,5,0,4,0,3,0,4,3,3,3,2,1,0,3,0,0,3,3), (0,4,0,3,0,3,0,3,0,3,5,5,3,3,3,3,4,3,4,3,3,3,4,4,4,3,3,3,3,4,3,5,3,3,1,3,2,4,5,5,5,5,4,3,4,5,5,3,2,2,3,3,3,3,2,3,3,1,2,3,2,4,3,3,3,4,0,4,0,2,0,4,3,2,2,1,2,0,3,0,0,4,1), ) class JapaneseContextAnalysis: def __init__(self): self.reset() def reset(self): self._mTotalRel = 0 # total sequence received # category counters, each interger counts sequence in its category self._mRelSample = [0] * NUM_OF_CATEGORY # if last byte in current buffer is not the last byte of a character, # we need to know how many bytes to skip in next buffer self._mNeedToSkipCharNum = 0 self._mLastCharOrder = -1 # The order of previous char # If this flag is set to True, detection is done and conclusion has # been made self._mDone = False def feed(self, aBuf, aLen): if self._mDone: return # The buffer we got is byte oriented, and a character may span in more than one # buffers. In case the last one or two byte in last buffer is not # complete, we record how many byte needed to complete that character # and skip these bytes here. We can choose to record those bytes as # well and analyse the character once it is complete, but since a # character will not make much difference, by simply skipping # this character will simply our logic and improve performance. i = self._mNeedToSkipCharNum while i < aLen: order, charLen = self.get_order(aBuf[i:i + 2]) i += charLen if i > aLen: self._mNeedToSkipCharNum = i - aLen self._mLastCharOrder = -1 else: if (order != -1) and (self._mLastCharOrder != -1): self._mTotalRel += 1 if self._mTotalRel > MAX_REL_THRESHOLD: self._mDone = True break self._mRelSample[jp2CharContext[self._mLastCharOrder][order]] += 1 self._mLastCharOrder = order def got_enough_data(self): return self._mTotalRel > ENOUGH_REL_THRESHOLD def get_confidence(self): # This is just one way to calculate confidence. It works well for me. if self._mTotalRel > MINIMUM_DATA_THRESHOLD: return (self._mTotalRel - self._mRelSample[0]) / self._mTotalRel else: return DONT_KNOW def get_order(self, aBuf): return -1, 1 class SJISContextAnalysis(JapaneseContextAnalysis): def get_order(self, aBuf): if not aBuf: return -1, 1 # find out current char's byte length first_char = wrap_ord(aBuf[0]) if ((0x81 <= first_char <= 0x9F) or (0xE0 <= first_char <= 0xFC)): charLen = 2 else: charLen = 1 # return its order if it is hiragana if len(aBuf) > 1: second_char = wrap_ord(aBuf[1]) if (first_char == 202) and (0x9F <= second_char <= 0xF1): return second_char - 0x9F, charLen return -1, charLen class EUCJPContextAnalysis(JapaneseContextAnalysis): def get_order(self, aBuf): if not aBuf: return -1, 1 # find out current char's byte length first_char = wrap_ord(aBuf[0]) if (first_char == 0x8E) or (0xA1 <= first_char <= 0xFE): charLen = 2 elif first_char == 0x8F: charLen = 3 else: charLen = 1 # return its order if it is hiragana if len(aBuf) > 1: second_char = wrap_ord(aBuf[1]) if (first_char == 0xA4) and (0xA1 <= second_char <= 0xF3): return second_char - 0xA1, charLen return -1, charLen # flake8: noqa
gpl-3.0
Kriechi/mitmproxy
mitmproxy/flowfilter.py
1
14038
""" The following operators are understood: ~q Request ~s Response Headers: Patterns are matched against "name: value" strings. Field names are all-lowercase. ~a Asset content-type in response. Asset content types are: text/javascript application/x-javascript application/javascript text/css image/* application/x-shockwave-flash ~h rex Header line in either request or response ~hq rex Header in request ~hs rex Header in response ~b rex Expression in the body of either request or response ~bq rex Expression in the body of request ~bs rex Expression in the body of response ~t rex Shortcut for content-type header. ~d rex Request domain ~m rex Method ~u rex URL ~c CODE Response code. rex Equivalent to ~u rex """ import functools import re import sys from typing import Callable, ClassVar, Optional, Sequence, Type import pyparsing as pp from mitmproxy import flow, http, tcp, websocket from mitmproxy.net.websocket import check_handshake def only(*types): def decorator(fn): @functools.wraps(fn) def filter_types(self, flow): if isinstance(flow, types): return fn(self, flow) return False return filter_types return decorator class _Token: def dump(self, indent=0, fp=sys.stdout): print("{spacing}{name}{expr}".format( spacing="\t" * indent, name=self.__class__.__name__, expr=getattr(self, "expr", "") ), file=fp) class _Action(_Token): code: ClassVar[str] help: ClassVar[str] @classmethod def make(klass, s, loc, toks): return klass(*toks[1:]) class FErr(_Action): code = "e" help = "Match error" def __call__(self, f): return True if f.error else False class FMarked(_Action): code = "marked" help = "Match marked flows" def __call__(self, f): return f.marked class FHTTP(_Action): code = "http" help = "Match HTTP flows" @only(http.HTTPFlow) def __call__(self, f): return True class FWebSocket(_Action): code = "websocket" help = "Match WebSocket flows (and HTTP-WebSocket handshake flows)" @only(http.HTTPFlow, websocket.WebSocketFlow) def __call__(self, f): m = ( (isinstance(f, http.HTTPFlow) and f.request and check_handshake(f.request.headers)) or isinstance(f, websocket.WebSocketFlow) ) return m class FTCP(_Action): code = "tcp" help = "Match TCP flows" @only(tcp.TCPFlow) def __call__(self, f): return True class FReq(_Action): code = "q" help = "Match request with no response" @only(http.HTTPFlow) def __call__(self, f): if not f.response: return True class FResp(_Action): code = "s" help = "Match response" @only(http.HTTPFlow) def __call__(self, f): return bool(f.response) class _Rex(_Action): flags = 0 is_binary = True def __init__(self, expr): self.expr = expr if self.is_binary: expr = expr.encode() try: self.re = re.compile(expr, self.flags) except Exception: raise ValueError("Cannot compile expression.") def _check_content_type(rex, message): return any( name.lower() == b"content-type" and rex.search(value) for name, value in message.headers.fields ) class FAsset(_Action): code = "a" help = "Match asset in response: CSS, Javascript, Flash, images." ASSET_TYPES = [re.compile(x) for x in [ b"text/javascript", b"application/x-javascript", b"application/javascript", b"text/css", b"image/.*", b"application/x-shockwave-flash" ]] @only(http.HTTPFlow) def __call__(self, f): if f.response: for i in self.ASSET_TYPES: if _check_content_type(i, f.response): return True return False class FContentType(_Rex): code = "t" help = "Content-type header" @only(http.HTTPFlow) def __call__(self, f): if _check_content_type(self.re, f.request): return True elif f.response and _check_content_type(self.re, f.response): return True return False class FContentTypeRequest(_Rex): code = "tq" help = "Request Content-Type header" @only(http.HTTPFlow) def __call__(self, f): return _check_content_type(self.re, f.request) class FContentTypeResponse(_Rex): code = "ts" help = "Response Content-Type header" @only(http.HTTPFlow) def __call__(self, f): if f.response: return _check_content_type(self.re, f.response) return False class FHead(_Rex): code = "h" help = "Header" flags = re.MULTILINE @only(http.HTTPFlow) def __call__(self, f): if f.request and self.re.search(bytes(f.request.headers)): return True if f.response and self.re.search(bytes(f.response.headers)): return True return False class FHeadRequest(_Rex): code = "hq" help = "Request header" flags = re.MULTILINE @only(http.HTTPFlow) def __call__(self, f): if f.request and self.re.search(bytes(f.request.headers)): return True class FHeadResponse(_Rex): code = "hs" help = "Response header" flags = re.MULTILINE @only(http.HTTPFlow) def __call__(self, f): if f.response and self.re.search(bytes(f.response.headers)): return True class FBod(_Rex): code = "b" help = "Body" flags = re.DOTALL @only(http.HTTPFlow, websocket.WebSocketFlow, tcp.TCPFlow) def __call__(self, f): if isinstance(f, http.HTTPFlow): if f.request and f.request.raw_content: if self.re.search(f.request.get_content(strict=False)): return True if f.response and f.response.raw_content: if self.re.search(f.response.get_content(strict=False)): return True elif isinstance(f, websocket.WebSocketFlow) or isinstance(f, tcp.TCPFlow): for msg in f.messages: if self.re.search(msg.content): return True return False class FBodRequest(_Rex): code = "bq" help = "Request body" flags = re.DOTALL @only(http.HTTPFlow, websocket.WebSocketFlow, tcp.TCPFlow) def __call__(self, f): if isinstance(f, http.HTTPFlow): if f.request and f.request.raw_content: if self.re.search(f.request.get_content(strict=False)): return True elif isinstance(f, websocket.WebSocketFlow) or isinstance(f, tcp.TCPFlow): for msg in f.messages: if msg.from_client and self.re.search(msg.content): return True class FBodResponse(_Rex): code = "bs" help = "Response body" flags = re.DOTALL @only(http.HTTPFlow, websocket.WebSocketFlow, tcp.TCPFlow) def __call__(self, f): if isinstance(f, http.HTTPFlow): if f.response and f.response.raw_content: if self.re.search(f.response.get_content(strict=False)): return True elif isinstance(f, websocket.WebSocketFlow) or isinstance(f, tcp.TCPFlow): for msg in f.messages: if not msg.from_client and self.re.search(msg.content): return True class FMethod(_Rex): code = "m" help = "Method" flags = re.IGNORECASE @only(http.HTTPFlow) def __call__(self, f): return bool(self.re.search(f.request.data.method)) class FDomain(_Rex): code = "d" help = "Domain" flags = re.IGNORECASE is_binary = False @only(http.HTTPFlow, websocket.WebSocketFlow) def __call__(self, f): if isinstance(f, websocket.WebSocketFlow): f = f.handshake_flow return bool( self.re.search(f.request.host) or self.re.search(f.request.pretty_host) ) class FUrl(_Rex): code = "u" help = "URL" is_binary = False # FUrl is special, because it can be "naked". @classmethod def make(klass, s, loc, toks): if len(toks) > 1: toks = toks[1:] return klass(*toks) @only(http.HTTPFlow, websocket.WebSocketFlow) def __call__(self, f): if isinstance(f, websocket.WebSocketFlow): f = f.handshake_flow if not f or not f.request: return False return self.re.search(f.request.pretty_url) class FSrc(_Rex): code = "src" help = "Match source address" is_binary = False def __call__(self, f): if not f.client_conn or not f.client_conn.peername: return False r = "{}:{}".format(f.client_conn.peername[0], f.client_conn.peername[1]) return f.client_conn.peername and self.re.search(r) class FDst(_Rex): code = "dst" help = "Match destination address" is_binary = False def __call__(self, f): if not f.server_conn or not f.server_conn.address: return False r = "{}:{}".format(f.server_conn.address[0], f.server_conn.address[1]) return f.server_conn.address and self.re.search(r) class _Int(_Action): def __init__(self, num): self.num = int(num) class FCode(_Int): code = "c" help = "HTTP response code" @only(http.HTTPFlow) def __call__(self, f): if f.response and f.response.status_code == self.num: return True class FAnd(_Token): def __init__(self, lst): self.lst = lst def dump(self, indent=0, fp=sys.stdout): super().dump(indent, fp) for i in self.lst: i.dump(indent + 1, fp) def __call__(self, f): return all(i(f) for i in self.lst) class FOr(_Token): def __init__(self, lst): self.lst = lst def dump(self, indent=0, fp=sys.stdout): super().dump(indent, fp) for i in self.lst: i.dump(indent + 1, fp) def __call__(self, f): return any(i(f) for i in self.lst) class FNot(_Token): def __init__(self, itm): self.itm = itm[0] def dump(self, indent=0, fp=sys.stdout): super().dump(indent, fp) self.itm.dump(indent + 1, fp) def __call__(self, f): return not self.itm(f) filter_unary: Sequence[Type[_Action]] = [ FAsset, FErr, FHTTP, FMarked, FReq, FResp, FTCP, FWebSocket, ] filter_rex: Sequence[Type[_Rex]] = [ FBod, FBodRequest, FBodResponse, FContentType, FContentTypeRequest, FContentTypeResponse, FDomain, FDst, FHead, FHeadRequest, FHeadResponse, FMethod, FSrc, FUrl, ] filter_int = [ FCode ] def _make(): # Order is important - multi-char expressions need to come before narrow # ones. parts = [] for cls in filter_unary: f = pp.Literal(f"~{cls.code}") + pp.WordEnd() f.setParseAction(cls.make) parts.append(f) # This is a bit of a hack to simulate Word(pyparsing_unicode.printables), # which has a horrible performance with len(pyparsing.pyparsing_unicode.printables) == 1114060 unicode_words = pp.CharsNotIn("()~'\"" + pp.ParserElement.DEFAULT_WHITE_CHARS) unicode_words.skipWhitespace = True regex = ( unicode_words | pp.QuotedString('"', escChar='\\') | pp.QuotedString("'", escChar='\\') ) for cls in filter_rex: f = pp.Literal(f"~{cls.code}") + pp.WordEnd() + regex.copy() f.setParseAction(cls.make) parts.append(f) for cls in filter_int: f = pp.Literal(f"~{cls.code}") + pp.WordEnd() + pp.Word(pp.nums) f.setParseAction(cls.make) parts.append(f) # A naked rex is a URL rex: f = regex.copy() f.setParseAction(FUrl.make) parts.append(f) atom = pp.MatchFirst(parts) expr = pp.infixNotation( atom, [(pp.Literal("!").suppress(), 1, pp.opAssoc.RIGHT, lambda x: FNot(*x)), (pp.Literal("&").suppress(), 2, pp.opAssoc.LEFT, lambda x: FAnd(*x)), (pp.Literal("|").suppress(), 2, pp.opAssoc.LEFT, lambda x: FOr(*x)), ]) expr = pp.OneOrMore(expr) return expr.setParseAction(lambda x: FAnd(x) if len(x) != 1 else x) bnf = _make() TFilter = Callable[[flow.Flow], bool] def parse(s: str) -> Optional[TFilter]: try: flt = bnf.parseString(s, parseAll=True)[0] flt.pattern = s return flt except pp.ParseException: return None except ValueError: return None def match(flt, flow): """ Matches a flow against a compiled filter expression. Returns True if matched, False if not. If flt is a string, it will be compiled as a filter expression. If the expression is invalid, ValueError is raised. """ if isinstance(flt, str): flt = parse(flt) if not flt: raise ValueError("Invalid filter expression.") if flt: return flt(flow) return True help = [] for a in filter_unary: help.append( (f"~{a.code}", a.help) ) for b in filter_rex: help.append( (f"~{b.code} regex", b.help) ) for c in filter_int: help.append( (f"~{c.code} int", c.help) ) help.sort() help.extend( [ ("!", "unary not"), ("&", "and"), ("|", "or"), ("(...)", "grouping"), ] )
mit
tsuberi/kid-watch-app
Server/twilio/rest/resources/trunking/trunks.py
24
1570
from .. import NextGenInstanceResource, NextGenListResource class Trunk(NextGenInstanceResource): """ A Trunk resource. See the `TaskRouter API reference <https://www.twilio.com/docs/sip-trunking/rest/trunks>_` for more information. .. attribute:: sid The unique ID for this Trunk. """ def delete(self): """ Deletes a Trunk. """ return self.parent.delete_instance(self.name) def update(self, **kwargs): """ Updates a Trunk. """ return self.parent.update_instance(self.name, **kwargs) class Trunks(NextGenListResource): """ A list of Trunk resources """ name = "Trunks" instance = Trunk key = "trunks" def list(self, **kwargs): """ Retrieve the list of Trunk resources. :param Page: The subset of results that needs to be fetched :param PageSize: The size of the Page that needs to be fetched """ return super(Trunks, self).list(**kwargs) def create(self, **kwargs): """ Creates a Trunk. """ return self.create_instance(kwargs) def update(self, sid, body): """ Updates a Trunk. :param sid: A human readable 34 character unique identifier :param body: Request body """ return self.update_instance(sid, body) def delete(self, sid): """ Deletes a Trunk. :param sid: A human readable 34 character unique identifier """ return self.delete_instance(sid)
mit
waseem18/oh-mainline
mysite/profile/migrations/0053_switch_project_exp_to_citations_and_portfolio_entry.py
17
13740
# This file is part of OpenHatch. # Copyright (C) 2009 OpenHatch, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from south.db import db from django.db import models from mysite.profile.models import * class Migration: # This is a data migration, so no_dry_run = True def forwards(self, orm): "Write your forwards migration here" for project_exp in orm['profile.projectexp'].objects.all(): if project_exp.person is None: continue portfolio_entry, _ = orm['profile.portfolioentry'].objects.get_or_create( project=project_exp.project, person=project_exp.person) citation = orm['profile.citation']() citation.portfolio_entry = portfolio_entry citation.data_import_attempt = project_exp.data_import_attempt citation.old_summary = project_exp.description citation.url = project_exp.url citation.distinct_months = project_exp.man_months # gend0r citation.languages = project_exp.primary_language citation.contributor_role = project_exp.person_role citation.is_published = True citation.save() project_exp.delete() def backwards(self, orm): "Write your backwards migration here" models = { 'auth.group': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)"}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'profile.citation': { 'contributor_role': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'data_import_attempt': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.DataImportAttempt']", 'null': 'True'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2009, 10, 28, 19, 35, 11, 602812)'}), 'distinct_months': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'first_commit_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'languages': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'portfolio_entry': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.PortfolioEntry']"}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'}) }, 'profile.dataimportattempt': { 'completed': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'failed': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Person']"}), 'query': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '2'}) }, 'profile.link_person_tag': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Person']"}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Tag']"}) }, 'profile.link_project_tag': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['search.Project']"}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Tag']"}) }, 'profile.link_projectexp_tag': { 'Meta': {'unique_together': "[('tag', 'project_exp', 'source')]"}, 'favorite': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'project_exp': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.ProjectExp']"}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Tag']"}) }, 'profile.link_sf_proj_dude_fm': { 'Meta': {'unique_together': "[('person', 'project')]"}, 'date_collected': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_admin': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.SourceForgePerson']"}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.SourceForgeProject']"}) }, 'profile.person': { 'gotten_name_from_ohloh': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'interested_in_working_on': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024'}), 'last_polled': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(1970, 1, 1, 0, 0)'}), 'photo': ('django.db.models.fields.files.ImageField', [], {'default': "''", 'max_length': '100'}), 'show_email': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'profile.portfolioentry': { 'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2009, 10, 28, 19, 35, 11, 779211)'}), 'experience_description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Person']"}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['search.Project']"}), 'project_description': ('django.db.models.fields.TextField', [], {}) }, 'profile.projectexp': { 'data_import_attempt': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.DataImportAttempt']", 'null': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'man_months': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}), 'modified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.Person']", 'null': 'True'}), 'person_role': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'primary_language': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['search.Project']"}), 'should_show_this': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'}) }, 'profile.sourceforgeperson': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'profile.sourceforgeproject': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'unixname': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'profile.tag': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tag_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profile.TagType']"}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'profile.tagtype': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'prefix': ('django.db.models.fields.CharField', [], {'max_length': '20'}) }, 'search.project': { 'date_icon_was_fetched_from_ohloh': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True'}), 'icon': ('django.db.models.fields.files.ImageField', [], {'default': 'None', 'max_length': '100', 'null': 'True'}), 'icon_smaller_for_badge': ('django.db.models.fields.files.ImageField', [], {'default': 'None', 'max_length': '100', 'null': 'True'}), 'icon_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}) } } complete_apps = ['profile']
agpl-3.0
rafalh/openfaction
vendor/freetype/src/tools/docmaker/sources.py
106
10770
# Sources (c) 2002-2004, 2006-2009, 2012 # David Turner <david@freetype.org> # # # this file contains definitions of classes needed to decompose # C sources files into a series of multi-line "blocks". There are # two kinds of blocks: # # - normal blocks, which contain source code or ordinary comments # # - documentation blocks, which have restricted formatting, and # whose text always start with a documentation markup tag like # "<Function>", "<Type>", etc.. # # the routines used to process the content of documentation blocks # are not contained here, but in "content.py" # # the classes and methods found here only deal with text parsing # and basic documentation block extraction # import fileinput, re, sys, os, string ################################################################ ## ## BLOCK FORMAT PATTERN ## ## A simple class containing compiled regular expressions used ## to detect potential documentation format block comments within ## C source code ## ## note that the 'column' pattern must contain a group that will ## be used to "unbox" the content of documentation comment blocks ## class SourceBlockFormat: def __init__( self, id, start, column, end ): """create a block pattern, used to recognize special documentation blocks""" self.id = id self.start = re.compile( start, re.VERBOSE ) self.column = re.compile( column, re.VERBOSE ) self.end = re.compile( end, re.VERBOSE ) # # format 1 documentation comment blocks look like the following: # # /************************************/ # /* */ # /* */ # /* */ # /************************************/ # # we define a few regular expressions here to detect them # start = r''' \s* # any number of whitespace /\*{2,}/ # followed by '/' and at least two asterisks then '/' \s*$ # probably followed by whitespace ''' column = r''' \s* # any number of whitespace /\*{1} # followed by '/' and precisely one asterisk ([^*].*) # followed by anything (group 1) \*{1}/ # followed by one asterisk and a '/' \s*$ # probably followed by whitespace ''' re_source_block_format1 = SourceBlockFormat( 1, start, column, start ) # # format 2 documentation comment blocks look like the following: # # /************************************ (at least 2 asterisks) # * # * # * # * # **/ (1 or more asterisks at the end) # # we define a few regular expressions here to detect them # start = r''' \s* # any number of whitespace /\*{2,} # followed by '/' and at least two asterisks \s*$ # probably followed by whitespace ''' column = r''' \s* # any number of whitespace \*{1}(?!/) # followed by precisely one asterisk not followed by `/' (.*) # then anything (group1) ''' end = r''' \s* # any number of whitespace \*+/ # followed by at least one asterisk, then '/' ''' re_source_block_format2 = SourceBlockFormat( 2, start, column, end ) # # the list of supported documentation block formats, we could add new ones # relatively easily # re_source_block_formats = [re_source_block_format1, re_source_block_format2] # # the following regular expressions corresponds to markup tags # within the documentation comment blocks. they're equivalent # despite their different syntax # # notice how each markup tag _must_ begin a new line # re_markup_tag1 = re.compile( r'''\s*<((?:\w|-)*)>''' ) # <xxxx> format re_markup_tag2 = re.compile( r'''\s*@((?:\w|-)*):''' ) # @xxxx: format # # the list of supported markup tags, we could add new ones relatively # easily # re_markup_tags = [re_markup_tag1, re_markup_tag2] # # used to detect a cross-reference, after markup tags have been stripped # re_crossref = re.compile( r'@((?:\w|-)*)(.*)' ) # # used to detect italic and bold styles in paragraph text # re_italic = re.compile( r"_(\w(\w|')*)_(.*)" ) # _italic_ re_bold = re.compile( r"\*(\w(\w|')*)\*(.*)" ) # *bold* # # used to detect the end of commented source lines # re_source_sep = re.compile( r'\s*/\*\s*\*/' ) # # used to perform cross-reference within source output # re_source_crossref = re.compile( r'(\W*)(\w*)' ) # # a list of reserved source keywords # re_source_keywords = re.compile( '''\\b ( typedef | struct | enum | union | const | char | int | short | long | void | signed | unsigned | \#include | \#define | \#undef | \#if | \#ifdef | \#ifndef | \#else | \#endif ) \\b''', re.VERBOSE ) ################################################################ ## ## SOURCE BLOCK CLASS ## ## A SourceProcessor is in charge of reading a C source file ## and decomposing it into a series of different "SourceBlocks". ## each one of these blocks can be made of the following data: ## ## - A documentation comment block that starts with "/**" and ## whose exact format will be discussed later ## ## - normal sources lines, including comments ## ## the important fields in a text block are the following ones: ## ## self.lines : a list of text lines for the corresponding block ## ## self.content : for documentation comment blocks only, this is the ## block content that has been "unboxed" from its ## decoration. This is None for all other blocks ## (i.e. sources or ordinary comments with no starting ## markup tag) ## class SourceBlock: def __init__( self, processor, filename, lineno, lines ): self.processor = processor self.filename = filename self.lineno = lineno self.lines = lines[:] self.format = processor.format self.content = [] if self.format == None: return words = [] # extract comment lines lines = [] for line0 in self.lines: m = self.format.column.match( line0 ) if m: lines.append( m.group( 1 ) ) # now, look for a markup tag for l in lines: l = string.strip( l ) if len( l ) > 0: for tag in re_markup_tags: if tag.match( l ): self.content = lines return def location( self ): return "(" + self.filename + ":" + repr( self.lineno ) + ")" # debugging only - not used in normal operations def dump( self ): if self.content: print "{{{content start---" for l in self.content: print l print "---content end}}}" return fmt = "" if self.format: fmt = repr( self.format.id ) + " " for line in self.lines: print line ################################################################ ## ## SOURCE PROCESSOR CLASS ## ## The SourceProcessor is in charge of reading a C source file ## and decomposing it into a series of different "SourceBlock" ## objects. ## ## each one of these blocks can be made of the following data: ## ## - A documentation comment block that starts with "/**" and ## whose exact format will be discussed later ## ## - normal sources lines, include comments ## ## class SourceProcessor: def __init__( self ): """initialize a source processor""" self.blocks = [] self.filename = None self.format = None self.lines = [] def reset( self ): """reset a block processor, clean all its blocks""" self.blocks = [] self.format = None def parse_file( self, filename ): """parse a C source file, and add its blocks to the processor's list""" self.reset() self.filename = filename fileinput.close() self.format = None self.lineno = 0 self.lines = [] for line in fileinput.input( filename ): # strip trailing newlines, important on Windows machines! if line[-1] == '\012': line = line[0:-1] if self.format == None: self.process_normal_line( line ) else: if self.format.end.match( line ): # that's a normal block end, add it to 'lines' and # create a new block self.lines.append( line ) self.add_block_lines() elif self.format.column.match( line ): # that's a normal column line, add it to 'lines' self.lines.append( line ) else: # humm.. this is an unexpected block end, # create a new block, but don't process the line self.add_block_lines() # we need to process the line again self.process_normal_line( line ) # record the last lines self.add_block_lines() def process_normal_line( self, line ): """process a normal line and check whether it is the start of a new block""" for f in re_source_block_formats: if f.start.match( line ): self.add_block_lines() self.format = f self.lineno = fileinput.filelineno() self.lines.append( line ) def add_block_lines( self ): """add the current accumulated lines and create a new block""" if self.lines != []: block = SourceBlock( self, self.filename, self.lineno, self.lines ) self.blocks.append( block ) self.format = None self.lines = [] # debugging only, not used in normal operations def dump( self ): """print all blocks in a processor""" for b in self.blocks: b.dump() # eof
gpl-3.0
PredictiveScienceLab/GPy
GPy/inference/mcmc/samplers.py
8
3031
# ## Copyright (c) 2014, Zhenwen Dai # Licensed under the BSD 3-clause license (see LICENSE.txt) from __future__ import print_function import numpy as np import sys try: #In Python 2, cPickle is faster. It does not exist in Python 3 but the underlying code is always used #if available import cPickle as pickle except ImportError: import pickle class Metropolis_Hastings: def __init__(self,model,cov=None): """Metropolis Hastings, with tunings according to Gelman et al. """ self.model = model current = self.model.optimizer_array self.D = current.size self.chains = [] if cov is None: self.cov = np.eye(self.D) else: self.cov = cov self.scale = 2.4/np.sqrt(self.D) self.new_chain(current) def new_chain(self, start=None): self.chains.append([]) if start is None: self.model.randomize() else: self.model.optimizer_array = start def sample(self, Ntotal=10000, Nburn=1000, Nthin=10, tune=True, tune_throughout=False, tune_interval=400): current = self.model.optimizer_array fcurrent = self.model.log_likelihood() + self.model.log_prior() + \ self.model._log_det_jacobian() accepted = np.zeros(Ntotal,dtype=np.bool) for it in range(Ntotal): print("sample %d of %d\r"%(it,Ntotal),end="\t") sys.stdout.flush() prop = np.random.multivariate_normal(current, self.cov*self.scale*self.scale) self.model.optimizer_array = prop fprop = self.model.log_likelihood() + self.model.log_prior() + \ self.model._log_det_jacobian() if fprop>fcurrent:#sample accepted, going 'uphill' accepted[it] = True current = prop fcurrent = fprop else: u = np.random.rand() if np.exp(fprop-fcurrent)>u:#sample accepted downhill accepted[it] = True current = prop fcurrent = fprop #store current value if (it > Nburn) & ((it%Nthin)==0): self.chains[-1].append(current) #tuning! if it & ((it%tune_interval)==0) & tune & ((it<Nburn) | (tune_throughout)): pc = np.mean(accepted[it-tune_interval:it]) self.cov = np.cov(np.vstack(self.chains[-1][-tune_interval:]).T) if pc > .25: self.scale *= 1.1 if pc < .15: self.scale /= 1.1 def predict(self,function,args): """Make a prediction for the function, to which we will pass the additional arguments""" param = self.model.param_array fs = [] for p in self.chain: self.model.param_array = p fs.append(function(*args)) # reset model to starting state self.model.param_array = param return fs
bsd-3-clause
sameetb-cuelogic/edx-platform-test
common/lib/xmodule/xmodule/modulestore/xml_exporter.py
3
20697
""" Methods for exporting course data to XML """ import logging from abc import abstractmethod import lxml.etree from xblock.fields import Scope, Reference, ReferenceList, ReferenceValueDict from xmodule.contentstore.content import StaticContent from xmodule.exceptions import NotFoundError from xmodule.assetstore import AssetMetadata from xmodule.modulestore import EdxJSONEncoder, ModuleStoreEnum from xmodule.modulestore.inheritance import own_metadata from xmodule.modulestore.store_utilities import draft_node_constructor, get_draft_subtree_roots from xmodule.modulestore import LIBRARY_ROOT from fs.osfs import OSFS from json import dumps import json import os from path import path import shutil from xmodule.modulestore.draft_and_published import DIRECT_ONLY_CATEGORIES from opaque_keys.edx.locator import CourseLocator, LibraryLocator DRAFT_DIR = "drafts" PUBLISHED_DIR = "published" EXPORT_VERSION_FILE = "format.json" EXPORT_VERSION_KEY = "export_format" DEFAULT_CONTENT_FIELDS = ['metadata', 'data'] def _export_drafts(modulestore, course_key, export_fs, xml_centric_course_key): """ Exports course drafts. """ # NOTE: we need to explicitly implement the logic for setting the vertical's parent # and index here since the XML modulestore cannot load draft modules with modulestore.branch_setting(ModuleStoreEnum.Branch.draft_preferred, course_key): draft_modules = modulestore.get_items( course_key, qualifiers={'category': {'$nin': DIRECT_ONLY_CATEGORIES}}, revision=ModuleStoreEnum.RevisionOption.draft_only ) if draft_modules: draft_course_dir = export_fs.makeopendir(DRAFT_DIR) # accumulate tuples of draft_modules and their parents in # this list: draft_node_list = [] for draft_module in draft_modules: parent_loc = modulestore.get_parent_location( draft_module.location, revision=ModuleStoreEnum.RevisionOption.draft_preferred ) # if module has no parent, set its parent_url to `None` parent_url = None if parent_loc is not None: parent_url = parent_loc.to_deprecated_string() draft_node = draft_node_constructor( draft_module, location=draft_module.location, url=draft_module.location.to_deprecated_string(), parent_location=parent_loc, parent_url=parent_url, ) draft_node_list.append(draft_node) for draft_node in get_draft_subtree_roots(draft_node_list): # only export the roots of the draft subtrees # since export_from_xml (called by `add_xml_to_node`) # exports a whole tree # ensure module has "xml_attributes" attr if not hasattr(draft_node.module, 'xml_attributes'): draft_node.module.xml_attributes = {} # Don't try to export orphaned items # and their descendents if draft_node.parent_location is None: continue logging.debug('parent_loc = %s', draft_node.parent_location) draft_node.module.xml_attributes['parent_url'] = draft_node.parent_url parent = modulestore.get_item(draft_node.parent_location) index = parent.children.index(draft_node.module.location) draft_node.module.xml_attributes['index_in_children_list'] = str(index) draft_node.module.runtime.export_fs = draft_course_dir adapt_references(draft_node.module, xml_centric_course_key, draft_course_dir) # pylint: disable=no-member node = lxml.etree.Element('unknown') draft_node.module.add_xml_to_node(node) class ExportManager(object): """ Manages XML exporting for courselike objects. """ def __init__(self, modulestore, contentstore, courselike_key, root_dir, target_dir): """ Export all modules from `modulestore` and content from `contentstore` as xml to `root_dir`. `modulestore`: A `ModuleStore` object that is the source of the modules to export `contentstore`: A `ContentStore` object that is the source of the content to export, can be None `courselike_key`: The Locator of the Descriptor to export `root_dir`: The directory to write the exported xml to `target_dir`: The name of the directory inside `root_dir` to write the content to """ self.modulestore = modulestore self.contentstore = contentstore self.courselike_key = courselike_key self.root_dir = root_dir self.target_dir = target_dir @abstractmethod def get_key(self): """ Get the courselike locator key """ raise NotImplementedError def process_root(self, root, export_fs): """ Perform any additional tasks to the root XML node. """ def process_extra(self, root, courselike, root_courselike_dir, xml_centric_courselike_key, export_fs): """ Process additional content, like static assets. """ def post_process(self, root, export_fs): """ Perform any final processing after the other export tasks are done. """ @abstractmethod def get_courselike(self): """ Get the target courselike object for this export. """ def export(self): """ Perform the export given the parameters handed to this class at init. """ with self.modulestore.bulk_operations(self.courselike_key): # depth = None: Traverses down the entire course structure. # lazy = False: Loads and caches all block definitions during traversal for fast access later # -and- to eliminate many round-trips to read individual definitions. # Why these parameters? Because a course export needs to access all the course block information # eventually. Accessing it all now at the beginning increases performance of the export. fsm = OSFS(self.root_dir) courselike = self.get_courselike() export_fs = courselike.runtime.export_fs = fsm.makeopendir(self.target_dir) root_courselike_dir = self.root_dir + '/' + self.target_dir root = lxml.etree.Element('unknown') # pylint: disable=no-member # export only the published content with self.modulestore.branch_setting(ModuleStoreEnum.Branch.published_only, self.courselike_key): # change all of the references inside the course to use the xml expected key type w/o version & branch xml_centric_courselike_key = self.get_key() adapt_references(courselike, xml_centric_courselike_key, export_fs) courselike.add_xml_to_node(root) # Make any needed adjustments to the root node. self.process_root(root, export_fs) # Process extra items-- drafts, assets, etc self.process_extra(root, courselike, root_courselike_dir, xml_centric_courselike_key, export_fs) # Any last pass adjustments self.post_process(root, export_fs) class CourseExportManager(ExportManager): """ Export manager for courses. """ def get_key(self): return CourseLocator( self.courselike_key.org, self.courselike_key.course, self.courselike_key.run, deprecated=True ) def get_courselike(self): return self.modulestore.get_course(self.courselike_key, depth=None, lazy=False) def process_root(self, root, export_fs): with export_fs.open('course.xml', 'w') as course_xml: lxml.etree.ElementTree(root).write(course_xml) # pylint: disable=no-member def process_extra(self, root, courselike, root_courselike_dir, xml_centric_courselike_key, export_fs): # Export the modulestore's asset metadata. asset_dir = root_courselike_dir + '/' + AssetMetadata.EXPORTED_ASSET_DIR + '/' if not os.path.isdir(asset_dir): os.makedirs(asset_dir) asset_root = lxml.etree.Element(AssetMetadata.ALL_ASSETS_XML_TAG) course_assets = self.modulestore.get_all_asset_metadata(self.courselike_key, None) for asset_md in course_assets: # All asset types are exported using the "asset" tag - but their asset type is specified in each asset key. asset = lxml.etree.SubElement(asset_root, AssetMetadata.ASSET_XML_TAG) # pylint: disable=no-member asset_md.to_xml(asset) with OSFS(asset_dir).open(AssetMetadata.EXPORTED_ASSET_FILENAME, 'w') as asset_xml_file: lxml.etree.ElementTree(asset_root).write(asset_xml_file) # pylint: disable=no-member # export the static assets policies_dir = export_fs.makeopendir('policies') if self.contentstore: self.contentstore.export_all_for_course( self.courselike_key, root_courselike_dir + '/static/', root_courselike_dir + '/policies/assets.json', ) # If we are using the default course image, export it to the # legacy location to support backwards compatibility. if courselike.course_image == courselike.fields['course_image'].default: try: course_image = self.contentstore.find( StaticContent.compute_location( courselike.id, courselike.course_image ), ) except NotFoundError: pass else: output_dir = root_courselike_dir + '/static/images/' if not os.path.isdir(output_dir): os.makedirs(output_dir) with OSFS(output_dir).open('course_image.jpg', 'wb') as course_image_file: course_image_file.write(course_image.data) # export the static tabs export_extra_content( export_fs, self.modulestore, self.courselike_key, xml_centric_courselike_key, 'static_tab', 'tabs', '.html' ) # export the custom tags export_extra_content( export_fs, self.modulestore, self.courselike_key, xml_centric_courselike_key, 'custom_tag_template', 'custom_tags' ) # export the course updates export_extra_content( export_fs, self.modulestore, self.courselike_key, xml_centric_courselike_key, 'course_info', 'info', '.html' ) # export the 'about' data (e.g. overview, etc.) export_extra_content( export_fs, self.modulestore, self.courselike_key, xml_centric_courselike_key, 'about', 'about', '.html' ) # export the grading policy course_run_policy_dir = policies_dir.makeopendir(courselike.location.run) with course_run_policy_dir.open('grading_policy.json', 'w') as grading_policy: grading_policy.write(dumps(courselike.grading_policy, cls=EdxJSONEncoder, sort_keys=True, indent=4)) # export all of the course metadata in policy.json with course_run_policy_dir.open('policy.json', 'w') as course_policy: policy = {'course/' + courselike.location.name: own_metadata(courselike)} course_policy.write(dumps(policy, cls=EdxJSONEncoder, sort_keys=True, indent=4)) # xml backed courses don't support drafts! if courselike.runtime.modulestore.get_modulestore_type() != ModuleStoreEnum.Type.xml: _export_drafts(self.modulestore, self.courselike_key, export_fs, xml_centric_courselike_key) class LibraryExportManager(ExportManager): """ Export manager for Libraries """ def get_key(self): """ Get the library locator for the current library key. """ return LibraryLocator( self.courselike_key.org, self.courselike_key.library ) def get_courselike(self): """ Get the library from the modulestore. """ return self.modulestore.get_library(self.courselike_key, depth=None, lazy=False) def process_root(self, root, export_fs): """ Add extra attributes to the root XML file. """ root.set('org', self.courselike_key.org) root.set('library', self.courselike_key.library) def process_extra(self, root, courselike, root_courselike_dir, xml_centric_courselike_key, export_fs): """ Notionally, libraries may have assets. This is currently unsupported, but the structure is here to ease in duck typing during import. This may be expanded as a useful feature eventually. """ # export the static assets export_fs.makeopendir('policies') if self.contentstore: self.contentstore.export_all_for_course( self.courselike_key, self.root_dir + '/' + self.target_dir + '/static/', self.root_dir + '/' + self.target_dir + '/policies/assets.json', ) def post_process(self, root, export_fs): """ Because Libraries are XBlocks, they aren't exported in the same way Course Modules are, but instead use the standard XBlock serializers. Accordingly, we need to create our own index file to act as the equivalent to the root course.xml file, called library.xml. """ # Create the Library.xml file, which acts as the index of all library contents. xml_file = export_fs.open(LIBRARY_ROOT, 'w') # pylint: disable=no-member xml_file.write(lxml.etree.tostring(root, pretty_print=True, encoding='utf-8')) xml_file.close() def export_course_to_xml(modulestore, contentstore, course_key, root_dir, course_dir): """ Thin wrapper for the Course Export Manager. See ExportManager for details. """ CourseExportManager(modulestore, contentstore, course_key, root_dir, course_dir).export() def export_library_to_xml(modulestore, contentstore, library_key, root_dir, library_dir): """ Thin wrapper for the Library Export Manager. See ExportManager for details. """ LibraryExportManager(modulestore, contentstore, library_key, root_dir, library_dir).export() def adapt_references(subtree, destination_course_key, export_fs): """ Map every reference in the subtree into destination_course_key and set it back into the xblock fields """ subtree.runtime.export_fs = export_fs # ensure everything knows where it's going! for field_name, field in subtree.fields.iteritems(): if field.is_set_on(subtree): if isinstance(field, Reference): value = field.read_from(subtree) if value is not None: field.write_to(subtree, field.read_from(subtree).map_into_course(destination_course_key)) elif field_name == 'children': # don't change the children field but do recurse over the children [adapt_references(child, destination_course_key, export_fs) for child in subtree.get_children()] elif isinstance(field, ReferenceList): field.write_to( subtree, [ele.map_into_course(destination_course_key) for ele in field.read_from(subtree)] ) elif isinstance(field, ReferenceValueDict): field.write_to( subtree, { key: ele.map_into_course(destination_course_key) for key, ele in field.read_from(subtree).iteritems() } ) def _export_field_content(xblock_item, item_dir): """ Export all fields related to 'xblock_item' other than 'metadata' and 'data' to json file in provided directory """ module_data = xblock_item.get_explicitly_set_fields_by_scope(Scope.content) if isinstance(module_data, dict): for field_name in module_data: if field_name not in DEFAULT_CONTENT_FIELDS: # filename format: {dirname}.{field_name}.json with item_dir.open('{0}.{1}.{2}'.format(xblock_item.location.name, field_name, 'json'), 'w') as field_content_file: field_content_file.write(dumps(module_data.get(field_name, {}), cls=EdxJSONEncoder, sort_keys=True, indent=4)) def export_extra_content(export_fs, modulestore, source_course_key, dest_course_key, category_type, dirname, file_suffix=''): items = modulestore.get_items(source_course_key, qualifiers={'category': category_type}) if len(items) > 0: item_dir = export_fs.makeopendir(dirname) for item in items: adapt_references(item, dest_course_key, export_fs) with item_dir.open(item.location.name + file_suffix, 'w') as item_file: item_file.write(item.data.encode('utf8')) # export content fields other then metadata and data in json format in current directory _export_field_content(item, item_dir) def convert_between_versions(source_dir, target_dir): """ Converts a version 0 export format to version 1, and vice versa. @param source_dir: the directory structure with the course export that should be converted. The contents of source_dir will not be altered. @param target_dir: the directory where the converted export should be written. @return: the version number of the converted export. """ def convert_to_version_1(): """ Convert a version 0 archive to version 0 """ os.mkdir(copy_root) with open(copy_root / EXPORT_VERSION_FILE, 'w') as f: f.write('{{"{export_key}": 1}}\n'.format(export_key=EXPORT_VERSION_KEY)) # If a drafts folder exists, copy it over. copy_drafts() # Now copy everything into the published directory published_dir = copy_root / PUBLISHED_DIR shutil.copytree(path(source_dir) / course_name, published_dir) # And delete the nested drafts directory, if it exists. nested_drafts_dir = published_dir / DRAFT_DIR if nested_drafts_dir.isdir(): shutil.rmtree(nested_drafts_dir) def convert_to_version_0(): """ Convert a version 1 archive to version 0 """ # Copy everything in "published" up to the top level. published_dir = path(source_dir) / course_name / PUBLISHED_DIR if not published_dir.isdir(): raise ValueError("a version 1 archive must contain a published branch") shutil.copytree(published_dir, copy_root) # If there is a DRAFT branch, copy it. All other branches are ignored. copy_drafts() def copy_drafts(): """ Copy drafts directory from the old archive structure to the new. """ draft_dir = path(source_dir) / course_name / DRAFT_DIR if draft_dir.isdir(): shutil.copytree(draft_dir, copy_root / DRAFT_DIR) root = os.listdir(source_dir) if len(root) != 1 or (path(source_dir) / root[0]).isfile(): raise ValueError("source archive does not have single course directory at top level") course_name = root[0] # For this version of the script, we simply convert back and forth between version 0 and 1. original_version = get_version(path(source_dir) / course_name) if original_version not in [0, 1]: raise ValueError("unknown version: " + str(original_version)) desired_version = 1 if original_version is 0 else 0 copy_root = path(target_dir) / course_name if desired_version == 1: convert_to_version_1() else: convert_to_version_0() return desired_version def get_version(course_path): """ Return the export format version number for the given archive directory structure (represented as a path instance). If the archived file does not correspond to a known export format, None will be returned. """ format_file = course_path / EXPORT_VERSION_FILE if not format_file.isfile(): return 0 with open(format_file, "r") as f: data = json.load(f) if EXPORT_VERSION_KEY in data: return data[EXPORT_VERSION_KEY] return None
agpl-3.0
kxliugang/edx-platform
openedx/core/djangoapps/user_api/accounts/tests/test_views.py
37
33316
# -*- coding: utf-8 -*- import datetime from copy import deepcopy import ddt import hashlib import json from mock import patch from pytz import UTC import unittest from django.conf import settings from django.core.urlresolvers import reverse from django.test.testcases import TransactionTestCase from django.test.utils import override_settings from rest_framework.test import APITestCase, APIClient from student.tests.factories import UserFactory from student.models import UserProfile, LanguageProficiency, PendingEmailChange from openedx.core.djangoapps.user_api.accounts import ACCOUNT_VISIBILITY_PREF_KEY from openedx.core.djangoapps.user_api.preferences.api import set_user_preference from .. import PRIVATE_VISIBILITY, ALL_USERS_VISIBILITY TEST_PROFILE_IMAGE_UPLOADED_AT = datetime.datetime(2002, 1, 9, 15, 43, 01, tzinfo=UTC) # this is used in one test to check the behavior of profile image url # generation with a relative url in the config. TEST_PROFILE_IMAGE_BACKEND = deepcopy(settings.PROFILE_IMAGE_BACKEND) TEST_PROFILE_IMAGE_BACKEND['options']['base_url'] = '/profile-images/' class UserAPITestCase(APITestCase): """ The base class for all tests of the User API """ test_password = "test" def setUp(self): super(UserAPITestCase, self).setUp() self.anonymous_client = APIClient() self.different_user = UserFactory.create(password=self.test_password) self.different_client = APIClient() self.staff_user = UserFactory(is_staff=True, password=self.test_password) self.staff_client = APIClient() self.user = UserFactory.create(password=self.test_password) # will be assigned to self.client by default def login_client(self, api_client, user): """Helper method for getting the client and user and logging in. Returns client. """ client = getattr(self, api_client) user = getattr(self, user) client.login(username=user.username, password=self.test_password) return client def send_patch(self, client, json_data, content_type="application/merge-patch+json", expected_status=204): """ Helper method for sending a patch to the server, defaulting to application/merge-patch+json content_type. Verifies the expected status and returns the response. """ # pylint: disable=no-member response = client.patch(self.url, data=json.dumps(json_data), content_type=content_type) self.assertEqual(expected_status, response.status_code) return response def send_get(self, client, query_parameters=None, expected_status=200): """ Helper method for sending a GET to the server. Verifies the expected status and returns the response. """ url = self.url + '?' + query_parameters if query_parameters else self.url # pylint: disable=no-member response = client.get(url) self.assertEqual(expected_status, response.status_code) return response def send_put(self, client, json_data, content_type="application/json", expected_status=204): """ Helper method for sending a PUT to the server. Verifies the expected status and returns the response. """ response = client.put(self.url, data=json.dumps(json_data), content_type=content_type) self.assertEqual(expected_status, response.status_code) return response def send_delete(self, client, expected_status=204): """ Helper method for sending a DELETE to the server. Verifies the expected status and returns the response. """ response = client.delete(self.url) self.assertEqual(expected_status, response.status_code) return response def create_mock_profile(self, user): """ Helper method that creates a mock profile for the specified user :return: """ legacy_profile = UserProfile.objects.get(id=user.id) legacy_profile.country = "US" legacy_profile.level_of_education = "m" legacy_profile.year_of_birth = 2000 legacy_profile.goals = "world peace" legacy_profile.mailing_address = "Park Ave" legacy_profile.gender = "f" legacy_profile.bio = "Tired mother of twins" legacy_profile.profile_image_uploaded_at = TEST_PROFILE_IMAGE_UPLOADED_AT legacy_profile.language_proficiencies.add(LanguageProficiency(code='en')) legacy_profile.save() @ddt.ddt @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Account APIs are only supported in LMS') @patch('openedx.core.djangoapps.user_api.accounts.image_helpers._PROFILE_IMAGE_SIZES', [50, 10]) @patch.dict( 'openedx.core.djangoapps.user_api.accounts.image_helpers.PROFILE_IMAGE_SIZES_MAP', {'full': 50, 'small': 10}, clear=True ) class TestAccountAPI(UserAPITestCase): """ Unit tests for the Account API. """ def setUp(self): super(TestAccountAPI, self).setUp() self.url = reverse("accounts_api", kwargs={'username': self.user.username}) def _verify_profile_image_data(self, data, has_profile_image): """ Verify the profile image data in a GET response for self.user corresponds to whether the user has or hasn't set a profile image. """ template = '{root}/{filename}_{{size}}.{extension}' if has_profile_image: url_root = 'http://example-storage.com/profile-images' filename = hashlib.md5('secret' + self.user.username).hexdigest() file_extension = 'jpg' template += '?v={}'.format(TEST_PROFILE_IMAGE_UPLOADED_AT.strftime("%s")) else: url_root = 'http://testserver/static' filename = 'default' file_extension = 'png' template = template.format(root=url_root, filename=filename, extension=file_extension) self.assertEqual( data['profile_image'], { 'has_image': has_profile_image, 'image_url_full': template.format(size=50), 'image_url_small': template.format(size=10), } ) def _verify_full_shareable_account_response(self, response): """ Verify that the shareable fields from the account are returned """ data = response.data self.assertEqual(6, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual("US", data["country"]) self._verify_profile_image_data(data, True) self.assertIsNone(data["time_zone"]) self.assertEqual([{"code": "en"}], data["language_proficiencies"]) self.assertEqual("Tired mother of twins", data["bio"]) def _verify_private_account_response(self, response, requires_parental_consent=False): """ Verify that only the public fields are returned if a user does not want to share account fields """ data = response.data self.assertEqual(2, len(data)) self.assertEqual(self.user.username, data["username"]) self._verify_profile_image_data(data, not requires_parental_consent) def _verify_full_account_response(self, response, requires_parental_consent=False): """ Verify that all account fields are returned (even those that are not shareable). """ data = response.data self.assertEqual(15, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"]) self.assertEqual("US", data["country"]) self.assertEqual("f", data["gender"]) self.assertEqual(2000, data["year_of_birth"]) self.assertEqual("m", data["level_of_education"]) self.assertEqual("world peace", data["goals"]) self.assertEqual("Park Ave", data['mailing_address']) self.assertEqual(self.user.email, data["email"]) self.assertTrue(data["is_active"]) self.assertIsNotNone(data["date_joined"]) self.assertEqual("Tired mother of twins", data["bio"]) self._verify_profile_image_data(data, not requires_parental_consent) self.assertEquals(requires_parental_consent, data["requires_parental_consent"]) self.assertEqual([{"code": "en"}], data["language_proficiencies"]) def test_anonymous_access(self): """ Test that an anonymous client (not logged in) cannot call GET or PATCH. """ self.send_get(self.anonymous_client, expected_status=401) self.send_patch(self.anonymous_client, {}, expected_status=401) def test_unsupported_methods(self): """ Test that DELETE, POST, and PUT are not supported. """ self.client.login(username=self.user.username, password=self.test_password) self.assertEqual(405, self.client.put(self.url).status_code) self.assertEqual(405, self.client.post(self.url).status_code) self.assertEqual(405, self.client.delete(self.url).status_code) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_get_account_unknown_user(self, api_client, user): """ Test that requesting a user who does not exist returns a 404. """ client = self.login_client(api_client, user) response = client.get(reverse("accounts_api", kwargs={'username': "does_not_exist"})) self.assertEqual(403 if user == "staff_user" else 404, response.status_code) # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "all_users"}) def test_get_account_different_user_visible(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "all_users". """ self.different_client.login(username=self.different_user.username, password=self.test_password) self.create_mock_profile(self.user) response = self.send_get(self.different_client) self._verify_full_shareable_account_response(response) # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "private"}) def test_get_account_different_user_private(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "private". """ self.different_client.login(username=self.different_user.username, password=self.test_password) self.create_mock_profile(self.user) response = self.send_get(self.different_client) self._verify_private_account_response(response) @ddt.data( ("client", "user", PRIVATE_VISIBILITY), ("different_client", "different_user", PRIVATE_VISIBILITY), ("staff_client", "staff_user", PRIVATE_VISIBILITY), ("client", "user", ALL_USERS_VISIBILITY), ("different_client", "different_user", ALL_USERS_VISIBILITY), ("staff_client", "staff_user", ALL_USERS_VISIBILITY), ) @ddt.unpack def test_get_account_private_visibility(self, api_client, requesting_username, preference_visibility): """ Test the return from GET based on user visibility setting. """ def verify_fields_visible_to_all_users(response): if preference_visibility == PRIVATE_VISIBILITY: self._verify_private_account_response(response) else: self._verify_full_shareable_account_response(response) client = self.login_client(api_client, requesting_username) # Update user account visibility setting. set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, preference_visibility) self.create_mock_profile(self.user) response = self.send_get(client) if requesting_username == "different_user": verify_fields_visible_to_all_users(response) else: self._verify_full_account_response(response) # Verify how the view parameter changes the fields that are returned. response = self.send_get(client, query_parameters='view=shared') verify_fields_visible_to_all_users(response) def test_get_account_default(self): """ Test that a client (logged in) can get her own account information (using default legacy profile information, as created by the test UserFactory). """ def verify_get_own_information(): response = self.send_get(self.client) data = response.data self.assertEqual(15, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"]) for empty_field in ("year_of_birth", "level_of_education", "mailing_address", "bio"): self.assertIsNone(data[empty_field]) self.assertIsNone(data["country"]) self.assertEqual("m", data["gender"]) self.assertEqual("Learn a lot", data["goals"]) self.assertEqual(self.user.email, data["email"]) self.assertIsNotNone(data["date_joined"]) self.assertEqual(self.user.is_active, data["is_active"]) self._verify_profile_image_data(data, False) self.assertTrue(data["requires_parental_consent"]) self.assertEqual([], data["language_proficiencies"]) self.client.login(username=self.user.username, password=self.test_password) verify_get_own_information() # Now make sure that the user can get the same information, even if not active self.user.is_active = False self.user.save() verify_get_own_information() def test_get_account_empty_string(self): """ Test the conversion of empty strings to None for certain fields. """ legacy_profile = UserProfile.objects.get(id=self.user.id) legacy_profile.country = "" legacy_profile.level_of_education = "" legacy_profile.gender = "" legacy_profile.bio = "" legacy_profile.save() self.client.login(username=self.user.username, password=self.test_password) response = self.send_get(self.client) for empty_field in ("level_of_education", "gender", "country", "bio"): self.assertIsNone(response.data[empty_field]) @ddt.data( ("different_client", "different_user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_disallowed_user(self, api_client, user): """ Test that a client cannot call PATCH on a different client's user account (even with is_staff access). """ client = self.login_client(api_client, user) self.send_patch(client, {}, expected_status=403 if user == "staff_user" else 404) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_unknown_user(self, api_client, user): """ Test that trying to update a user who does not exist returns a 404. """ client = self.login_client(api_client, user) response = client.patch( reverse("accounts_api", kwargs={'username': "does_not_exist"}), data=json.dumps({}), content_type="application/merge-patch+json" ) self.assertEqual(404, response.status_code) @ddt.data( ("gender", "f", "not a gender", u"Select a valid choice. not a gender is not one of the available choices."), ("level_of_education", "none", u"ȻħȺɍłɇs", u"Select a valid choice. ȻħȺɍłɇs is not one of the available choices."), ("country", "GB", "XY", u"Select a valid choice. XY is not one of the available choices."), ("year_of_birth", 2009, "not_an_int", u"Enter a whole number."), ("name", "bob", "z" * 256, u"Ensure this value has at most 255 characters (it has 256)."), ("name", u"ȻħȺɍłɇs", "z ", u"The name field must be at least 2 characters long."), ("goals", "Smell the roses"), ("mailing_address", "Sesame Street"), # Note that we store the raw data, so it is up to client to escape the HTML. ("bio", u"<html>Lacrosse-playing superhero 壓是進界推日不復女</html>", "z" * 3001, u"Ensure this value has at most 3000 characters (it has 3001)."), # Note that email is tested below, as it is not immediately updated. # Note that language_proficiencies is tested below as there are multiple error and success conditions. ) @ddt.unpack def test_patch_account(self, field, value, fails_validation_value=None, developer_validation_message=None): """ Test the behavior of patch, when using the correct content_type. """ client = self.login_client("client", "user") self.send_patch(client, {field: value}) get_response = self.send_get(client) self.assertEqual(value, get_response.data[field]) if fails_validation_value: error_response = self.send_patch(client, {field: fails_validation_value}, expected_status=400) self.assertEqual( u'This value is invalid.', error_response.data["field_errors"][field]["user_message"] ) self.assertEqual( u"Value '{value}' is not valid for field '{field}': {messages}".format( value=fails_validation_value, field=field, messages=[developer_validation_message] ), error_response.data["field_errors"][field]["developer_message"] ) else: # If there are no values that would fail validation, then empty string should be supported. self.send_patch(client, {field: ""}) get_response = self.send_get(client) self.assertEqual("", get_response.data[field]) def test_patch_inactive_user(self): """ Verify that a user can patch her own account, even if inactive. """ self.client.login(username=self.user.username, password=self.test_password) self.user.is_active = False self.user.save() self.send_patch(self.client, {"goals": "to not activate account"}) get_response = self.send_get(self.client) self.assertEqual("to not activate account", get_response.data["goals"]) @ddt.unpack def test_patch_account_noneditable(self): """ Tests the behavior of patch when a read-only field is attempted to be edited. """ client = self.login_client("client", "user") def verify_error_response(field_name, data): self.assertEqual( "This field is not editable via this API", data["field_errors"][field_name]["developer_message"] ) self.assertEqual( "The '{0}' field cannot be edited.".format(field_name), data["field_errors"][field_name]["user_message"] ) for field_name in ["username", "date_joined", "is_active", "profile_image", "requires_parental_consent"]: response = self.send_patch(client, {field_name: "will_error", "gender": "o"}, expected_status=400) verify_error_response(field_name, response.data) # Make sure that gender did not change. response = self.send_get(client) self.assertEqual("m", response.data["gender"]) # Test error message with multiple read-only items response = self.send_patch(client, {"username": "will_error", "date_joined": "xx"}, expected_status=400) self.assertEqual(2, len(response.data["field_errors"])) verify_error_response("username", response.data) verify_error_response("date_joined", response.data) def test_patch_bad_content_type(self): """ Test the behavior of patch when an incorrect content_type is specified. """ self.client.login(username=self.user.username, password=self.test_password) self.send_patch(self.client, {}, content_type="application/json", expected_status=415) self.send_patch(self.client, {}, content_type="application/xml", expected_status=415) def test_patch_account_empty_string(self): """ Tests the behavior of patch when attempting to set fields with a select list of options to the empty string. Also verifies the behaviour when setting to None. """ self.client.login(username=self.user.username, password=self.test_password) for field_name in ["gender", "level_of_education", "country"]: self.send_patch(self.client, {field_name: ""}) response = self.send_get(self.client) # Although throwing a 400 might be reasonable, the default DRF behavior with ModelSerializer # is to convert to None, which also seems acceptable (and is difficult to override). self.assertIsNone(response.data[field_name]) # Verify that the behavior is the same for sending None. self.send_patch(self.client, {field_name: ""}) response = self.send_get(self.client) self.assertIsNone(response.data[field_name]) def test_patch_name_metadata(self): """ Test the metadata stored when changing the name field. """ def get_name_change_info(expected_entries): legacy_profile = UserProfile.objects.get(id=self.user.id) name_change_info = legacy_profile.get_meta()["old_names"] self.assertEqual(expected_entries, len(name_change_info)) return name_change_info def verify_change_info(change_info, old_name, requester, new_name): self.assertEqual(3, len(change_info)) self.assertEqual(old_name, change_info[0]) self.assertEqual("Name change requested through account API by {}".format(requester), change_info[1]) self.assertIsNotNone(change_info[2]) # Verify the new name was also stored. get_response = self.send_get(self.client) self.assertEqual(new_name, get_response.data["name"]) self.client.login(username=self.user.username, password=self.test_password) legacy_profile = UserProfile.objects.get(id=self.user.id) self.assertEqual({}, legacy_profile.get_meta()) old_name = legacy_profile.name # First change the name as the user and verify meta information. self.send_patch(self.client, {"name": "Mickey Mouse"}) name_change_info = get_name_change_info(1) verify_change_info(name_change_info[0], old_name, self.user.username, "Mickey Mouse") # Now change the name again and verify meta information. self.send_patch(self.client, {"name": "Donald Duck"}) name_change_info = get_name_change_info(2) verify_change_info(name_change_info[0], old_name, self.user.username, "Donald Duck",) verify_change_info(name_change_info[1], "Mickey Mouse", self.user.username, "Donald Duck") def test_patch_email(self): """ Test that the user can request an email change through the accounts API. Full testing of the helper method used (do_email_change_request) exists in the package with the code. Here just do minimal smoke testing. """ client = self.login_client("client", "user") old_email = self.user.email new_email = "newemail@example.com" self.send_patch(client, {"email": new_email, "goals": "change my email"}) # Since request is multi-step, the email won't change on GET immediately (though goals will update). get_response = self.send_get(client) self.assertEqual(old_email, get_response.data["email"]) self.assertEqual("change my email", get_response.data["goals"]) # Now call the method that will be invoked with the user clicks the activation key in the received email. # First we must get the activation key that was sent. pending_change = PendingEmailChange.objects.filter(user=self.user) self.assertEqual(1, len(pending_change)) activation_key = pending_change[0].activation_key confirm_change_url = reverse( "student.views.confirm_email_change", kwargs={'key': activation_key} ) response = self.client.post(confirm_change_url) self.assertEqual(200, response.status_code) get_response = self.send_get(client) self.assertEqual(new_email, get_response.data["email"]) @ddt.data( ("not_an_email",), ("",), (None,), ) @ddt.unpack def test_patch_invalid_email(self, bad_email): """ Test a few error cases for email validation (full test coverage lives with do_email_change_request). """ client = self.login_client("client", "user") # Try changing to an invalid email to make sure error messages are appropriately returned. error_response = self.send_patch(client, {"email": bad_email}, expected_status=400) field_errors = error_response.data["field_errors"] self.assertEqual( "Error thrown from validate_new_email: 'Valid e-mail address required.'", field_errors["email"]["developer_message"] ) self.assertEqual("Valid e-mail address required.", field_errors["email"]["user_message"]) def test_patch_language_proficiencies(self): """ Verify that patching the language_proficiencies field of the user profile completely overwrites the previous value. """ client = self.login_client("client", "user") # Patching language_proficiencies exercises the # `LanguageProficiencySerializer.get_identity` method, which compares # identifies language proficiencies based on their language code rather # than django model id. for proficiencies in ([{"code": "en"}, {"code": "fr"}, {"code": "es"}], [{"code": "fr"}], [{"code": "aa"}], []): self.send_patch(client, {"language_proficiencies": proficiencies}) response = self.send_get(client) self.assertItemsEqual(response.data["language_proficiencies"], proficiencies) @ddt.data( (u"not_a_list", [{u'non_field_errors': [u'Expected a list of items.']}]), ([u"not_a_JSON_object"], [{u'non_field_errors': [u'Invalid data']}]), ([{}], [{"code": [u"This field is required."]}]), ([{u"code": u"invalid_language_code"}], [{'code': [u'Select a valid choice. invalid_language_code is not one of the available choices.']}]), ([{u"code": u"kw"}, {u"code": u"el"}, {u"code": u"kw"}], [u'The language_proficiencies field must consist of unique languages']), ) @ddt.unpack def test_patch_invalid_language_proficiencies(self, patch_value, expected_error_message): """ Verify we handle error cases when patching the language_proficiencies field. """ client = self.login_client("client", "user") response = self.send_patch(client, {"language_proficiencies": patch_value}, expected_status=400) self.assertEqual( response.data["field_errors"]["language_proficiencies"]["developer_message"], u"Value '{patch_value}' is not valid for field 'language_proficiencies': {error_message}".format(patch_value=patch_value, error_message=expected_error_message) ) @patch('openedx.core.djangoapps.user_api.accounts.serializers.AccountUserSerializer.save') def test_patch_serializer_save_fails(self, serializer_save): """ Test that AccountUpdateErrors are passed through to the response. """ serializer_save.side_effect = [Exception("bummer"), None] self.client.login(username=self.user.username, password=self.test_password) error_response = self.send_patch(self.client, {"goals": "save an account field"}, expected_status=400) self.assertEqual( "Error thrown when saving account updates: 'bummer'", error_response.data["developer_message"] ) self.assertIsNone(error_response.data["user_message"]) @override_settings(PROFILE_IMAGE_BACKEND=TEST_PROFILE_IMAGE_BACKEND) def test_convert_relative_profile_url(self): """ Test that when TEST_PROFILE_IMAGE_BACKEND['base_url'] begins with a '/', the API generates the full URL to profile images based on the URL of the request. """ self.client.login(username=self.user.username, password=self.test_password) response = self.send_get(self.client) self.assertEqual( response.data["profile_image"], { "has_image": False, "image_url_full": "http://testserver/static/default_50.png", "image_url_small": "http://testserver/static/default_10.png" } ) @ddt.data( ("client", "user", True), ("different_client", "different_user", False), ("staff_client", "staff_user", True), ) @ddt.unpack def test_parental_consent(self, api_client, requesting_username, has_full_access): """ Verifies that under thirteens never return a public profile. """ client = self.login_client(api_client, requesting_username) # Set the user to be ten years old with a public profile legacy_profile = UserProfile.objects.get(id=self.user.id) current_year = datetime.datetime.now().year legacy_profile.year_of_birth = current_year - 10 legacy_profile.save() set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, ALL_USERS_VISIBILITY) # Verify that the default view is still private (except for clients with full access) response = self.send_get(client) if has_full_access: data = response.data self.assertEqual(15, len(data)) self.assertEqual(self.user.username, data["username"]) self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"]) self.assertEqual(self.user.email, data["email"]) self.assertEqual(current_year - 10, data["year_of_birth"]) for empty_field in ("country", "level_of_education", "mailing_address", "bio"): self.assertIsNone(data[empty_field]) self.assertEqual("m", data["gender"]) self.assertEqual("Learn a lot", data["goals"]) self.assertTrue(data["is_active"]) self.assertIsNotNone(data["date_joined"]) self._verify_profile_image_data(data, False) self.assertTrue(data["requires_parental_consent"]) else: self._verify_private_account_response(response, requires_parental_consent=True) # Verify that the shared view is still private response = self.send_get(client, query_parameters='view=shared') self._verify_private_account_response(response, requires_parental_consent=True) @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class TestAccountAPITransactions(TransactionTestCase): """ Tests the transactional behavior of the account API """ test_password = "test" def setUp(self): super(TestAccountAPITransactions, self).setUp() self.client = APIClient() self.user = UserFactory.create(password=self.test_password) self.url = reverse("accounts_api", kwargs={'username': self.user.username}) @patch('student.views.do_email_change_request') def test_update_account_settings_rollback(self, mock_email_change): """ Verify that updating account settings is transactional when a failure happens. """ # Send a PATCH request with updates to both profile information and email. # Throw an error from the method that is used to process the email change request # (this is the last thing done in the api method). Verify that the profile did not change. mock_email_change.side_effect = [ValueError, "mock value error thrown"] self.client.login(username=self.user.username, password=self.test_password) old_email = self.user.email json_data = {"email": "foo@bar.com", "gender": "o"} response = self.client.patch(self.url, data=json.dumps(json_data), content_type="application/merge-patch+json") self.assertEqual(400, response.status_code) # Verify that GET returns the original preferences response = self.client.get(self.url) data = response.data self.assertEqual(old_email, data["email"]) self.assertEqual(u"m", data["gender"])
agpl-3.0
MarcosCommunity/odoo
addons/l10n_be_intrastat/wizard/xml_decl.py
17
17731
# -*- encoding: utf-8 -*- ############################################################################## # # Odoo, Open Source Business Applications # Copyright (C) 2014-2015 Odoo S.A. <http://www.odoo.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/>. # ############################################################################## import base64 import xml.etree.ElementTree as ET from collections import namedtuple from datetime import datetime from openerp import exceptions, SUPERUSER_ID, tools from openerp.osv import fields, osv from openerp.tools.translate import _ INTRASTAT_XMLNS = 'http://www.onegate.eu/2010-01-01' class xml_decl(osv.TransientModel): """ Intrastat XML Declaration """ _name = "l10n_be_intrastat_xml.xml_decl" _description = 'Intrastat XML Declaration' def _get_tax_code(self, cr, uid, context=None): obj_tax_code = self.pool.get('account.tax.code') obj_user = self.pool.get('res.users') company_id = obj_user.browse(cr, uid, uid, context=context).company_id.id tax_code_ids = obj_tax_code.search(cr, uid, [('company_id', '=', company_id), ('parent_id', '=', False)], context=context) return tax_code_ids and tax_code_ids[0] or False def _get_def_monthyear(self, cr, uid, context=None): td = datetime.strptime(fields.date.context_today(self, cr, uid, context=context), tools.DEFAULT_SERVER_DATE_FORMAT).date() return td.strftime('%Y'), td.strftime('%m') def _get_def_month(self, cr, uid, context=None): return self._get_def_monthyear(cr, uid, context=context)[1] def _get_def_year(self, cr, uid, context=None): return self._get_def_monthyear(cr, uid, context=context)[0] _columns = { 'name': fields.char('File Name'), 'month': fields.selection([('01','January'), ('02','February'), ('03','March'), ('04','April'), ('05','May'), ('06','June'), ('07','July'), ('08','August'), ('09','September'), ('10','October'), ('11','November'), ('12','December')], 'Month', required=True), 'year': fields.char('Year', size=4, required=True), 'tax_code_id': fields.many2one('account.tax.code', 'Company Tax Chart', domain=[('parent_id', '=', False)], required=True), 'arrivals': fields.selection([('be-exempt', 'Exempt'), ('be-standard', 'Standard'), ('be-extended', 'Extended')], 'Arrivals', required=True), 'dispatches': fields.selection([('be-exempt', 'Exempt'), ('be-standard', 'Standard'), ('be-extended', 'Extended')], 'Dispatches', required=True), 'file_save': fields.binary('Intrastat Report File', readonly=True), 'state': fields.selection([('draft', 'Draft'), ('download', 'Download')], string="State"), } _defaults = { 'arrivals': 'be-standard', 'dispatches': 'be-standard', 'name': 'intrastat.xml', 'tax_code_id': _get_tax_code, 'month': _get_def_month, 'year': _get_def_year, 'state': 'draft', } def _company_warning(self, cr, uid, translated_msg, context=None): """ Raise a error with custom message, asking user to configure company settings """ xmlid_mod = self.pool['ir.model.data'] action_id = xmlid_mod.xmlid_to_res_id(cr, uid, 'base.action_res_company_form') raise exceptions.RedirectWarning( translated_msg, action_id, _('Go to company configuration screen')) def create_xml(self, cr, uid, ids, context=None): """Creates xml that is to be exported and sent to estate for partner vat intra. :return: Value for next action. :rtype: dict """ decl_datas = self.browse(cr, uid, ids[0]) company = decl_datas.tax_code_id.company_id if not (company.partner_id and company.partner_id.country_id and company.partner_id.country_id.id): self._company_warning( cr, uid, _('The country of your company is not set, ' 'please make sure to configure it first.'), context=context) kbo = company.company_registry if not kbo: self._company_warning( cr, uid, _('The registry number of your company is not set, ' 'please make sure to configure it first.'), context=context) if len(decl_datas.year) != 4: raise exceptions.Warning(_('Year must be 4 digits number (YYYY)')) #Create root declaration decl = ET.Element('DeclarationReport') decl.set('xmlns', INTRASTAT_XMLNS) #Add Administration elements admin = ET.SubElement(decl, 'Administration') fromtag = ET.SubElement(admin, 'From') fromtag.text = kbo fromtag.set('declarerType', 'KBO') ET.SubElement(admin, 'To').text = "NBB" ET.SubElement(admin, 'Domain').text = "SXX" if decl_datas.arrivals == 'be-standard': decl.append(self._get_lines(cr, SUPERUSER_ID, ids, decl_datas, company, dispatchmode=False, extendedmode=False, context=context)) elif decl_datas.arrivals == 'be-extended': decl.append(self._get_lines(cr, SUPERUSER_ID, ids, decl_datas, company, dispatchmode=False, extendedmode=True, context=context)) if decl_datas.dispatches == 'be-standard': decl.append(self._get_lines(cr, SUPERUSER_ID, ids, decl_datas, company, dispatchmode=True, extendedmode=False, context=context)) elif decl_datas.dispatches == 'be-extended': decl.append(self._get_lines(cr, SUPERUSER_ID, ids, decl_datas, company, dispatchmode=True, extendedmode=True, context=context)) #Get xml string with declaration data_file = ET.tostring(decl, encoding='UTF-8', method='xml') #change state of the wizard self.write(cr, uid, ids, {'name': 'intrastat_%s%s.xml' % (decl_datas.year, decl_datas.month), 'file_save': base64.encodestring(data_file), 'state': 'download'}, context=context) return { 'name': _('Save'), 'context': context, 'view_type': 'form', 'view_mode': 'form', 'res_model': 'l10n_be_intrastat_xml.xml_decl', 'type': 'ir.actions.act_window', 'target': 'new', 'res_id': ids[0], } def _get_lines(self, cr, uid, ids, decl_datas, company, dispatchmode=False, extendedmode=False, context=None): intrastatcode_mod = self.pool['report.intrastat.code'] invoiceline_mod = self.pool['account.invoice.line'] product_mod = self.pool['product.product'] region_mod = self.pool['l10n_be_intrastat.region'] warehouse_mod = self.pool['stock.warehouse'] if dispatchmode: mode1 = 'out_invoice' mode2 = 'in_refund' declcode = "29" else: mode1 = 'in_invoice' mode2 = 'out_refund' declcode = "19" decl = ET.Element('Report') if not extendedmode: decl.set('code', 'EX%sS' % declcode) else: decl.set('code', 'EX%sE' % declcode) decl.set('date', '%s-%s' % (decl_datas.year, decl_datas.month)) datas = ET.SubElement(decl, 'Data') if not extendedmode: datas.set('form', 'EXF%sS' % declcode) else: datas.set('form', 'EXF%sE' % declcode) datas.set('close', 'true') intrastatkey = namedtuple("intrastatkey", ['EXTRF', 'EXCNT', 'EXTTA', 'EXREG', 'EXGO', 'EXTPC', 'EXDELTRM']) entries = {} sqlreq = """ select inv_line.id from account_invoice_line inv_line join account_invoice inv on inv_line.invoice_id=inv.id left join res_country on res_country.id = inv.intrastat_country_id left join res_partner on res_partner.id = inv.partner_id left join res_country countrypartner on countrypartner.id = res_partner.country_id join product_product on inv_line.product_id=product_product.id join product_template on product_product.product_tmpl_id=product_template.id left join account_period on account_period.id=inv.period_id where inv.state in ('open','paid') and inv.company_id=%s and not product_template.type='service' and (res_country.intrastat=true or (inv.intrastat_country_id is null and countrypartner.intrastat=true)) and ((res_country.code is not null and not res_country.code=%s) or (res_country.code is null and countrypartner.code is not null and not countrypartner.code=%s)) and inv.type in (%s, %s) and to_char(account_period.date_start, 'YYYY')=%s and to_char(account_period.date_start, 'MM')=%s """ cr.execute(sqlreq, (company.id, company.partner_id.country_id.code, company.partner_id.country_id.code, mode1, mode2, decl_datas.year, decl_datas.month)) lines = cr.fetchall() invoicelines_ids = [rec[0] for rec in lines] invoicelines = invoiceline_mod.browse(cr, uid, invoicelines_ids, context=context) for inv_line in invoicelines: #Check type of transaction if inv_line.invoice_id.intrastat_transaction_id: extta = inv_line.invoice_id.intrastat_transaction_id.code else: extta = "1" #Check country if inv_line.invoice_id.intrastat_country_id: excnt = inv_line.invoice_id.intrastat_country_id.code else: excnt = inv_line.invoice_id.partner_id.country_id.code #Check region #If purchase, comes from purchase order, linked to a location, #which is linked to the warehouse #if sales, the sale order is linked to the warehouse #if sales, from a delivery order, linked to a location, #which is linked to the warehouse #If none found, get the company one. exreg = None if inv_line.invoice_id.type in ('in_invoice', 'in_refund'): #comes from purchase POL = self.pool['purchase.order.line'] poline_ids = POL.search( cr, uid, [('invoice_lines', 'in', inv_line.id)], context=context) if poline_ids: purchaseorder = POL.browse(cr, uid, poline_ids[0], context=context).order_id region_id = warehouse_mod.get_regionid_from_locationid( cr, uid, purchaseorder.location_id.id, context=context) if region_id: exreg = region_mod.browse(cr, uid, region_id).code elif inv_line.invoice_id.type in ('out_invoice', 'out_refund'): #comes from sales soline_ids = self.pool['sale.order.line'].search( cr, uid, [('invoice_lines', 'in', inv_line.id)], context=context) if soline_ids: saleorder = self.pool['sale.order.line'].browse( cr, uid, soline_ids[0], context=context).order_id if saleorder and saleorder.warehouse_id and saleorder.warehouse_id.region_id: exreg = region_mod.browse( cr, uid, saleorder.warehouse_id.region_id.id, context=context).code if not exreg: if company.region_id: exreg = company.region_id.code else: self._company_warning( cr, uid, _('The Intrastat Region of the selected company is not set, ' 'please make sure to configure it first.'), context=context) #Check commodity codes intrastat_id = product_mod.get_intrastat_recursively( cr, uid, inv_line.product_id.id, context=context) if intrastat_id: exgo = intrastatcode_mod.browse(cr, uid, intrastat_id, context=context).name else: raise exceptions.Warning( _('Product "%s" has no intrastat code, please configure it') % inv_line.product_id.display_name) #In extended mode, 2 more fields required if extendedmode: #Check means of transport if inv_line.invoice_id.transport_mode_id: extpc = inv_line.invoice_id.transport_mode_id.code elif company.transport_mode_id: extpc = company.transport_mode_id.code else: self._company_warning( cr, uid, _('The default Intrastat transport mode of your company ' 'is not set, please make sure to configure it first.'), context=context) #Check incoterm if inv_line.invoice_id.incoterm_id: exdeltrm = inv_line.invoice_id.incoterm_id.code elif company.incoterm_id: exdeltrm = company.incoterm_id.code else: self._company_warning( cr, uid, _('The default Incoterm of your company is not set, ' 'please make sure to configure it first.'), context=context) else: extpc = "" exdeltrm = "" linekey = intrastatkey(EXTRF=declcode, EXCNT=excnt, EXTTA=extta, EXREG=exreg, EXGO=exgo, EXTPC=extpc, EXDELTRM=exdeltrm) #We have the key #calculate amounts if inv_line.price_unit and inv_line.quantity: amount = inv_line.price_unit * inv_line.quantity else: amount = 0 weight = (inv_line.product_id.weight_net or 0.0) * \ self.pool.get('product.uom')._compute_qty(cr, uid, inv_line.uos_id.id, inv_line.quantity, inv_line.product_id.uom_id.id) if (not inv_line.uos_id.category_id or not inv_line.product_id.uom_id.category_id or inv_line.uos_id.category_id.id != inv_line.product_id.uom_id.category_id.id): supply_units = inv_line.quantity else: supply_units = inv_line.quantity * inv_line.uos_id.factor amounts = entries.setdefault(linekey, (0, 0, 0)) amounts = (amounts[0] + amount, amounts[1] + weight, amounts[2] + supply_units) entries[linekey] = amounts numlgn = 0 for linekey in entries: numlgn += 1 amounts = entries[linekey] item = ET.SubElement(datas, 'Item') self._set_Dim(item, 'EXSEQCODE', unicode(numlgn)) self._set_Dim(item, 'EXTRF', unicode(linekey.EXTRF)) self._set_Dim(item, 'EXCNT', unicode(linekey.EXCNT)) self._set_Dim(item, 'EXTTA', unicode(linekey.EXTTA)) self._set_Dim(item, 'EXREG', unicode(linekey.EXREG)) self._set_Dim(item, 'EXTGO', unicode(linekey.EXGO)) if extendedmode: self._set_Dim(item, 'EXTPC', unicode(linekey.EXTPC)) self._set_Dim(item, 'EXDELTRM', unicode(linekey.EXDELTRM)) self._set_Dim(item, 'EXTXVAL', unicode(round(amounts[0], 0)).replace(".", ",")) self._set_Dim(item, 'EXWEIGHT', unicode(round(amounts[1], 0)).replace(".", ",")) self._set_Dim(item, 'EXUNITS', unicode(round(amounts[2], 0)).replace(".", ",")) if numlgn == 0: #no datas datas.set('action', 'nihil') return decl def _set_Dim(self, item, prop, value): dim = ET.SubElement(item, 'Dim') dim.set('prop', prop) dim.text = value
agpl-3.0
susuchina/ERPNEXT
erpnext/projects/doctype/time_log_batch/time_log_batch.py
16
2387
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc class TimeLogBatch(Document): def validate(self): self.set_status() self.total_hours = 0.0 self.total_billing_amount = 0.0 for d in self.get("time_logs"): tl = frappe.get_doc("Time Log", d.time_log) self.update_time_log_values(d, tl) self.validate_time_log_is_submitted(tl) self.total_hours += flt(tl.hours) self.total_billing_amount += flt(tl.billing_amount) def update_time_log_values(self, d, tl): d.update({ "hours": tl.hours, "activity_type": tl.activity_type, "billing_amount": tl.billing_amount, "note": tl.note }) def validate_time_log_is_submitted(self, tl): if tl.status == "Batched for Billing": frappe.throw(_("Time Log {0} already billed").format(tl.name)) elif tl.docstatus != 1: frappe.throw(_("Time Log {0} must be 'Submitted'").format(tl.name)) def set_status(self): self.status = { "0": "Draft", "1": "Submitted", "2": "Cancelled" }[str(self.docstatus or 0)] if self.sales_invoice: self.status = "Billed" def on_submit(self): self.update_status(self.name) def before_cancel(self): self.update_status(None) def before_update_after_submit(self): self.update_status(self.name) def update_status(self, time_log_batch): self.set_status() for d in self.get("time_logs"): tl = frappe.get_doc("Time Log", d.time_log) tl.time_log_batch = time_log_batch tl.sales_invoice = self.sales_invoice tl.flags.ignore_validate_update_after_submit = True tl.save() @frappe.whitelist() def make_sales_invoice(source_name, target=None): def update_item(source_doc, target_doc, source_parent): target_doc.stock_uom = "Hour" target_doc.description = "via Time Logs" target_doc.qty = 1 target = frappe.new_doc("Sales Invoice") target.append("items", get_mapped_doc("Time Log Batch", source_name, { "Time Log Batch": { "doctype": "Sales Invoice Item", "field_map": { "total_billing_amount": "rate", "name": "time_log_batch" }, "postprocess": update_item } })) return target
agpl-3.0
acrispin/cython
Cython/Tests/TestCodeWriter.py
132
2316
from Cython.TestUtils import CythonTest class TestCodeWriter(CythonTest): # CythonTest uses the CodeWriter heavily, so do some checking by # roundtripping Cython code through the test framework. # Note that this test is dependant upon the normal Cython parser # to generate the input trees to the CodeWriter. This save *a lot* # of time; better to spend that time writing other tests than perfecting # this one... # Whitespace is very significant in this process: # - always newline on new block (!) # - indent 4 spaces # - 1 space around every operator def t(self, codestr): self.assertCode(codestr, self.fragment(codestr).root) def test_print(self): self.t(u""" print x, y print x + y ** 2 print x, y, z, """) def test_if(self): self.t(u"if x:\n pass") def test_ifelifelse(self): self.t(u""" if x: pass elif y: pass elif z + 34 ** 34 - 2: pass else: pass """) def test_def(self): self.t(u""" def f(x, y, z): pass def f(x = 34, y = 54, z): pass """) def test_longness_and_signedness(self): self.t(u"def f(unsigned long long long long long int y):\n pass") def test_signed_short(self): self.t(u"def f(signed short int y):\n pass") def test_typed_args(self): self.t(u"def f(int x, unsigned long int y):\n pass") def test_cdef_var(self): self.t(u""" cdef int hello cdef int hello = 4, x = 3, y, z """) def test_for_loop(self): self.t(u""" for x, y, z in f(g(h(34) * 2) + 23): print x, y, z else: print 43 """) def test_inplace_assignment(self): self.t(u"x += 43") def test_attribute(self): self.t(u"a.x") if __name__ == "__main__": import unittest unittest.main()
apache-2.0
denismakogon/pyvcloud
pyvcloud/vcloudair.py
1
77761
# VMware vCloud Python SDK # Copyright (c) 2014 VMware, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 #todo: upload/download ovf to/from catalog #todo: create vapp network name is not being used, clean it up #todo: pass parameters in the create vapp to optimize for speed, available from 6.3 #todo: refactor returns, raise exceptions, document with release notes import sys import os import time import requests from progressbar import AnimatedMarker, Bar, BouncingBar, Counter, ETA, \ FileTransferSpeed, FormatLabel, Percentage, \ ProgressBar, ReverseBar, RotatingMarker, \ SimpleProgress, Timer from StringIO import StringIO import json from xml.etree import ElementTree as ET from pyvcloud.schema.vcd.v1_5.schemas.admin import vCloudEntities from pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities import AdminCatalogType from pyvcloud.schema.vcd.v1_5.schemas.vcloud import sessionType, organizationType, \ vAppType, organizationListType, vdcType, catalogType, queryRecordViewType, \ networkType, vcloudType, taskType, diskType, vmsType, vdcTemplateListType, mediaType from schema.vcd.v1_5.schemas.vcloud.diskType import OwnerType, DiskType, VdcStorageProfileType, DiskCreateParamsType from pyvcloud.schema.vcd.schemas.versioning import versionsType from pyvcloud.vcloudsession import VCS from pyvcloud.vapp import VAPP from pyvcloud.gateway import Gateway from pyvcloud.schema.vcim import serviceType, vchsType from pyvcloud.helper import CommonUtils from pyvcloud.schema.vcd.v1_5.schemas.vcloud.networkType import OrgVdcNetworkType,\ ReferenceType, NetworkConfigurationType, IpScopesType, IpScopeType,\ IpRangesType, IpRangeType, DhcpPoolServiceType from pyvcloud.score import Score from pyvcloud import _get_logger, Http, Log class VCA(object): VCA_SERVICE_TYPE_STANDALONE = 'standalone' VCA_SERVICE_TYPE_VCHS = 'vchs' VCA_SERVICE_TYPE_VCA = 'vca' VCA_SERVICE_TYPE_UNKNOWN = 'unknown' statuses = ['Could not be created', 'Unresolved', 'Resolved', 'Deployed', 'Suspended', 'Powered on', 'Waiting for user input', 'Unknown state', 'Unrecognized state', 'Powered off', 'Inconsistent state', 'Children do not all have the same status', 'Upload initiated, OVF descriptor pending', 'Upload initiated, copying contents', 'Upload initiated , disk contents pending', 'Upload has been quarantined', 'Upload quarantine period has expired' ] def __init__(self, host, username, service_type=VCA_SERVICE_TYPE_VCA, version='5.7', verify=True, log=False): """ Create a VCA connection :param host: (str): The vCloud Air Host. Varies by service type. Valid values are https://vchs.vmware.com and https://vca.vmware.com :param username: (str): The username for the vCloud Air Service. :param service_type: (str, optional): The type of vCloud Air Service. Valid values are ondemand, subscription, vcd. :param version: (str, optional): The API version. Note: may vary by service type. :verify: (bool, optional): Enforce strict ssl certificate checking. :log: (bool, optional): enable logging for the connection. :return: (bool): True if the user was successfully logged in, False otherwise. **service type:** subscription, ondemand, vcd """ if not (host.startswith('https://') or host.startswith('http://')): host = 'https://' + host self.host = host self.username = username self.token = None self.service_type = service_type self.version = version self.verify = verify self.vcloud_session = None self.instances = None self.org = None self.organization = None self.vdc = None self.services = None self.response = None self.log = log self.logger = _get_logger() if log else None def get_service_type(self): """ Returns the service type provided by the host (standalone, vchs or vca). This method only uses the host variable, it doesn't require the user to login. :return: (str): The type of service provided by the host. **service type:** standalone, vchs, vca """ url = self.host + '/api/iam/login' headers = {} headers["Accept"] = "application/json;version=" + '5.7' response = Http.post(url, headers=headers, auth=('_', '_'), verify=self.verify, logger=self.logger) if response.status_code == requests.codes.unauthorized: return VCA.VCA_SERVICE_TYPE_VCA url = self.host + '/api/vchs/sessions' headers = {} headers["Accept"] = "application/xml;version=" + '5.6' response = Http.post(url, headers=headers, auth=('_', '_'), verify=self.verify, logger=self.logger) if response.status_code == requests.codes.unauthorized: return VCA.VCA_SERVICE_TYPE_VCHS url = self.host + '/api/versions' response = Http.get(url, verify=self.verify, logger=self.logger) if response.status_code == requests.codes.ok: try: supported_versions = versionsType.parseString(response.content, True) return VCA.VCA_SERVICE_TYPE_STANDALONE except: pass return VCA.VCA_SERVICE_TYPE_UNKNOWN def _get_services(self): headers = {} headers["x-vchs-authorization"] = self.token headers["Accept"] = "application/xml;version=" + self.version response = Http.get(self.host + "/api/vchs/services", headers=headers, verify=self.verify, logger=self.logger) if response.status_code == requests.codes.ok: return serviceType.parseString(response.content, True) def login(self, password=None, token=None, org=None, org_url=None): """ Request to login to vCloud Air :param password: (str, optional): The password. :param token: (str, optional): The token from a previous successful login, None if this is a new login request. :param org: (str, optional): The organization identifier. :param org_url: (str, optional): The org_url. :return: (bool): True if the user was successfully logged in, False otherwise. **service type:** vca, vchs, standalone """ if self.service_type in [VCA.VCA_SERVICE_TYPE_VCHS, 'subscription']: if token: headers = {} headers["x-vchs-authorization"] = token headers["Accept"] = "application/xml;version=" + self.version self.response = Http.get(self.host + "/api/vchs/services", headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: self.services = serviceType.parseString(self.response.content, True) self.token = token return True else: return False else: url = self.host + "/api/vchs/sessions" headers = {} headers["Accept"] = "application/xml;version=" + self.version self.response = Http.post(url, headers=headers, auth=(self.username, password), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: self.token = self.response.headers["x-vchs-authorization"] self.services = self._get_services() return True else: return False elif self.service_type in [VCA.VCA_SERVICE_TYPE_VCA, 'ondemand']: if token: self.token = token self.instances = self.get_instances() return self.instances != None else: url = self.host + "/api/iam/login" headers = {} headers["Accept"] = "application/json;version=%s" % self.version self.response = Http.post(url, headers=headers, auth=(self.username, password), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: self.token = self.response.headers["vchs-authorization"] self.instances = self.get_instances() return True else: return False elif self.service_type in [VCA.VCA_SERVICE_TYPE_STANDALONE, 'vcd']: if token: url = self.host + '/api/sessions' vcloud_session = VCS(url, self.username, org, None, org_url, org_url, version=self.version, verify=self.verify, log=self.log) result = vcloud_session.login(token=token) if result: self.org = org self.vcloud_session = vcloud_session return result else: url = self.host + '/api/sessions' vcloud_session = VCS(url, self.username, org, None, org_url, org_url, version=self.version, verify=self.verify, log=self.log) result = vcloud_session.login(password=password) if result: self.token = vcloud_session.token self.org = org self.vcloud_session = vcloud_session return result else: return False return False def get_service_groups(self): """ Request available service groups for a given company. :return: (list of str): list of available service groups. **service type:** vca """ headers = self._get_vcloud_headers() headers['Accept'] = "application/json;version=%s;class=com.vmware.vchs.billing.serviceGroups" % self.version self.response = Http.get(self.host + "/api/billing/service-groups", headers=headers, verify=self.verify, logger=self.logger) if self.response.history and self.response.history[-1]: self.response = Http.get(self.response.history[-1].headers['location'], headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return json.loads(self.response.content)['serviceGroupList'] else: raise Exception(self.response.status_code) def get_plans(self): """ Request plans available for an ondemand account. :return: (list of str): list of available plans in json format. **service type:** vca """ headers = self._get_vcloud_headers() headers['Accept'] = "application/json;version=%s;class=com.vmware.vchs.sc.restapi.model.planlisttype" % self.version self.response = Http.get(self.host + "/api/sc/plans", headers=headers, verify=self.verify, logger=self.logger) if self.response.history and self.response.history[-1]: self.response = Http.get(self.response.history[-1].headers['location'], headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return json.loads(self.response.content)['plans'] else: raise Exception(self.response.status_code) def get_plan(self, plan_id): """ Request plan details. :return: (str): plan in json format **service type:** vca """ headers = self._get_vcloud_headers() headers['Accept'] = "application/json;version=%s;class=com.vmware.vchs.sc.restapi.model.planlisttype" % self.version self.response = Http.get(self.host + "/api/sc/plans/%s" % plan_id, headers=headers, verify=self.verify, logger=self.logger) if self.response.history and self.response.history[-1]: self.response = Http.get(self.response.history[-1].headers['location'], headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return json.loads(self.response.content) else: raise Exception(self.response.status_code) def get_users(self): """ Retrieves a collection of all users the authenticated API user has access to. :return: (list of str): list of users. **service type:** vca """ headers = self._get_vcloud_headers() headers['Accept'] = "application/json;version=%s;class=com.vmware.vchs.iam.api.schema.v2.classes.user.Users" % self.version self.response = Http.get(self.host + "/api/iam/Users", headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return json.loads(self.response.content)['users'] else: raise Exception(self.response.status_code) def add_user(self, email, given_name, family_name, roles): """ Add user. :return: . **service type:** vca """ data = """ { "schemas": [ "urn:scim:schemas:core:1.0" ], "state": "Active", "email": "%s", "familyName": "%s", "givenName": "%s", "roles": { "roles": [ """ % (email, family_name, given_name) first_role = True for role in roles: if first_role: first_role = False else: data += ',' data += """ { "name": "%s" } """ % role.strip() data += """ ] }, "userName": "%s" } """ % email headers = self._get_vcloud_headers() headers['Accept'] = "application/json;version=%s;class=com.vmware.vchs.iam.api.schema.v2.classes.user.Users" % self.version headers['Content-Type'] = "application/json;class=com.vmware.vchs.iam.api.schema.v2.classes.user.User;version=%s" % self.version self.response = Http.post(self.host + "/api/iam/Users", headers=headers, data=data, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: return json.loads(self.response.content) else: raise Exception(self.response.status_code) def del_user(self, user_id): """ Delete user. :return: . **service type:** vca """ headers = self._get_vcloud_headers() headers['Accept'] = "application/json" self.response = Http.delete(self.host + "/api/iam/Users/" + user_id, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.no_content: return True else: Log.error(self.logger, self.response.status_code) Log.error(self.logger, self.response.content) raise Exception(self.response.status_code) def change_password(self, current_password, new_password): """ Change current user password. :return: . **service type:** vca """ data = """ {"currentPassword":"%s","newPassword":"%s"} """ % (current_password, new_password) headers = self._get_vcloud_headers() headers['Accept'] = "application/json;version=%s;class=com.vmware.vchs.iam.api.schema.v2.classes.user.Password" % self.version headers['Content-Type'] = "application/json;class=com.vmware.vchs.iam.api.schema.v2.classes.user.Password;version=%s" % self.version self.response = Http.put(self.host + "/api/iam/Users/password", headers=headers, data=data, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.no_content: return True else: raise Exception(self.response.status_code) def validate_user(self, email, new_password, token): """ Validate user and set the initial password. :return: . **service type:** vca """ headers = {} headers['Accept'] = "application/json;version=%s" % self.version headers['Content-Type'] = "application/json" self.response = Http.post(self.host + "/api/iam/access/%s" % token, headers=headers, auth=(email, new_password), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return True else: raise Exception(self.response.status_code) def reset_password(self, user_id): """ Reset user password. :return: . **service type:** vca """ headers = self._get_vcloud_headers() headers['Content-Type'] = "application/json;version=%s" % self.version self.response = Http.put(self.host + "/api/iam/Users/%s/password/reset" % user_id, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.no_content: return True else: Log.error(self.logger, self.response.status_code) Log.error(self.logger, self.response.content) raise Exception(self.response.status_code) def get_roles(self): """ Get role. :return: . **service type:** vca """ headers = self._get_vcloud_headers() headers['Accept'] = "application/json;version=%s;class=com.vmware.vchs.iam.api.schema.v2.classes.user.Roles" % self.version self.response = Http.get(self.host + "/api/iam/Roles", headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return json.loads(self.response.content)['roles'] else: raise Exception(self.response.status_code) def get_instances(self): """ Request available instances :return: (list of str): list of available instances in json format. **service type:** vca """ self.response = Http.get(self.host + "/api/sc/instances", headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.history and self.response.history[-1]: self.response = Http.get(self.response.history[-1].headers['location'], headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return json.loads(self.response.content)['instances'] else: raise Exception(self.response.status_code) def get_instance(self, instance_id): """ Returns the details of a service instance :return: (str): instance information in json format. **service type:** vca """ self.response = Http.get(self.host + "/api/sc/instances/%s" % instance_id, headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.history and self.response.history[-1]: self.response = Http.get(self.response.history[-1].headers['location'], headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return json.loads(self.response.content) else: raise Exception(self.response.status_code) def delete_instance(self, instance): """ Request to delete an existing instance :param instance: (str): The instance identifer. :return: (): True if the user was successfully logged in, False otherwise. **service type:** vca """ self.response = Http.delete(self.host + "/api/sc/instances/" + instance, headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger) print self.response.status_code, self.response.content def login_to_instance(self, instance, password, token=None, org_url=None): """ Request to login into a specific instance :param instance: (str): The instance identifer. :param password: (str): The password. :param token: (str, optional): The token from a previous successful login, None if this is a new login request. :param org_url: (str, optional): :return: (bool): True if the login was successful, False otherwise. **service type:** vca """ instances = filter(lambda i: i['id']==instance, self.instances) if len(instances)>0: if 'No Attributes' == instances[0]['instanceAttributes']: return False attributes = json.loads(instances[0]['instanceAttributes']) session_uri = attributes['sessionUri'] org_name = attributes['orgName'] vcloud_session = VCS(session_uri, self.username, org_name, instance, instances[0]['apiUrl'], org_url, version=self.version, verify=self.verify, log=self.log) result = vcloud_session.login(password, token) if result: self.vcloud_session = vcloud_session return True return False def login_to_instance_sso(self, instance, token=None, org_url=None): """ Request to login into a specific instance :param instance: (str): The instance identifer. :param token: (str, optional): The token from a previous successful login, None if this is a new login request. :param org_url: (str, optional): :return: (bool): True if the login was successful, False otherwise. **service type:** vca """ Log.debug(self.logger, 'SSO to instance %s, org_url=%s' % (instance, org_url)) instances = filter(lambda i: i['id']==instance, self.instances) if len(instances)>0: if 'instanceAttributes' not in instances[0] or 'No Attributes' == instances[0]['instanceAttributes']: return False attributes = json.loads(instances[0]['instanceAttributes']) plans = self.get_plans() service_name = filter(lambda plan: plan['id'] == instances[0]['planId'], plans)[0]['serviceName'] if 'com.vmware.vchs.compute' != service_name: Log.debug(self.logger, 'cannot select instance of plan %s' % service_name) return False session_uri = attributes['sessionUri'] org_name = attributes['orgName'] from urlparse import urlparse parsed_uri = urlparse(session_uri) region_fqdn = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) headers = self._get_vcloud_headers() headers['Accept'] = 'application/xml;version=5.7' Log.debug(self.logger, 'SSO with region_fqdn=%s, session_uri=%s, org_name=%s, apiUrl=%s' % (region_fqdn, session_uri, org_name, instances[0]['apiUrl'])) if org_url is None: org_url = instances[0]['apiUrl'] Log.debug(self.logger, headers) self.response = Http.post(region_fqdn + 'api/sessions/vcloud/' + org_name, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: Log.debug(self.logger, 'ok: ' + self.response.content) Log.debug(self.logger, 'ok: ' + str(self.response.headers)) vcloud_session = VCS(session_uri, self.username, org_name, instance, instances[0]['apiUrl'], org_url, version=self.version, verify=self.verify, log=self.log) token = self.response.headers['x-vcloud-authorization'] result = vcloud_session.login(token=token) if result: self.vcloud_session = vcloud_session return True else: return False else: Log.debug(self.logger, 'ko: ' + self.response.content) return False return False #subscription def get_vdc_references(self, serviceId): """ Request a list of references to existing virtual data centers. :param serviceId: (str): The service instance identifier. :return: (list of ReferenceType): a list of :class:`<pyvcloud.schema.vcim.vchsType.VdcReferenceType` objects for the vdcs hosting the service. **service type:** vchs """ serviceReferences = filter(lambda serviceReference: serviceReference.get_serviceId() == serviceId, self.services.get_Service()) if len(serviceReferences) == 0: return [] self.response = Http.get(serviceReferences[0].get_href(), headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger) vdcs = vchsType.parseString(self.response.content, True) return vdcs.get_VdcRef() def get_vdc_reference(self, serviceId, vdcId): """ Request a reference to a specific vdc context hosting a service. :param serviceId: (str): The service identifier for the service. :param vdcId: (str): The identifier for the virtual data center. :return: (ReferenceType) a :class:`pyvcloud.schema.vcim.vchsType.VdcReferenceType` object representing the vdc. **service type:** vchs """ vdcReferences = filter(lambda vdcRef: vdcRef.get_name() == vdcId, self.get_vdc_references(serviceId)) if len(vdcReferences) == 0: return None return vdcReferences[0] #in subscription 1 org <-> 1 vdc def login_to_org(self, service, org_name): """ Request to login into a specific organization. An organization is a unit of administration for a collection of users, groups, and computing resources. :param service: (str): The service identifer. :param org_name: (str): :return: (bool): True if the login was successful, False otherwise. **service type:** ondemand, subscription, vcd .. note:: for a subscription service, 1 org <-> 1 vdc """ vdcReference = self.get_vdc_reference(service, org_name) if vdcReference: link = filter(lambda link: link.get_type() == "application/xml;class=vnd.vmware.vchs.vcloudsession", vdcReference.get_Link())[0] self.response = Http.post(link.get_href(), headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: vchs = vchsType.parseString(self.response.content, True) vdcLink = vchs.get_VdcLink() headers = {} headers[vdcLink.authorizationHeader] = vdcLink.authorizationToken headers["Accept"] = "application/*+xml;version=" + self.version self.response = Http.get(vdcLink.href, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: self.vdc = vdcType.parseString(self.response.content, True) self.org = self.vdc.name org_url = filter(lambda link: link.get_type() == "application/vnd.vmware.vcloud.org+xml", self.vdc.get_Link())[0].href vcloud_session = VCS(org_url, self.username, self.org, None, org_url, org_url, version=self.version, verify=self.verify, log=self.log) if vcloud_session.login(password=None, token=vdcLink.authorizationToken): self.vcloud_session = vcloud_session return True return False #common def _get_vcloud_headers(self): headers = {} if self.service_type == VCA.VCA_SERVICE_TYPE_VCHS or self.service_type == 'subscription': headers["Accept"] = "application/xml;version=" + self.version headers["x-vchs-authorization"] = self.token elif self.service_type == VCA.VCA_SERVICE_TYPE_VCA or self.service_type == 'ondemand': headers["Authorization"] = "Bearer %s" % self.token headers["Accept"] = "application/json;version=%s" % self.version elif self.service_type == VCA.VCA_SERVICE_TYPE_STANDALONE or self.service_type == 'vcd': # headers["x-vcloud-authorization"] = self.token pass return headers def get_vdc_templates(self): pass def get_vdc(self, vdc_name): """ Request a reference to a specific Virtual Data Center. A vdc is a logical construct that provides compute, network, and storage resources to an organization. Virtual machines can be created, stored, and operated within a vdc. A vdc Data centers also provides storage for virtual media. :param vdc_name: (str): The virtual data center name. :return: (VdcType) a :class:`.vcloud.vdcType.VdcType` object describing the vdc. (For example: subscription, ondemand) **service type:** ondemand, subscription, vcd """ if self.vcloud_session and self.vcloud_session.organization: refs = filter(lambda ref: ref.name == vdc_name and ref.type_ == 'application/vnd.vmware.vcloud.vdc+xml', self.vcloud_session.organization.Link) if len(refs) == 1: self.response = Http.get(refs[0].href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return vdcType.parseString(self.response.content, True) def get_vdc_names(self): """ Returns a list of Virtual Data Centers in the Organization. :param vdc_name: (str): The virtual data center name. :return: (list of str) list of vdc names **service type:** vca, vchs, standalone """ vdcs = [] if self.vcloud_session and self.vcloud_session.organization: refs = filter(lambda ref: ref.type_ == 'application/vnd.vmware.vcloud.vdc+xml', self.vcloud_session.organization.Link) for ref in refs: vdcs.append(ref.name) return vdcs def get_vapp(self, vdc, vapp_name): """ Request a reference to a specific vapp. A vApp is an application package containing 1 or more virtual machines and their required operating system. :param vdc: (VdcType): The virtual data center name. :param vapp_name: (str): The name of the requested vapp. :return: (VAPP): a :class:`pyvcloud.vapp.VAPP` object describing the vApp. **service type:** ondemand, subscription, vcd """ refs = filter(lambda ref: ref.name == vapp_name and ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml', vdc.ResourceEntities.ResourceEntity) if len(refs) == 1: self.response = Http.get(refs[0].href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: vapp = VAPP(vAppType.parseString(self.response.content, True), self.vcloud_session.get_vcloud_headers(), self.verify, self.log) return vapp def _create_instantiateVAppTemplateParams(self, name, template_href, vm_name, vm_href, deploy, power, vm_cpus=None, vm_memory=None): templateParams = vcloudType.InstantiateVAppTemplateParamsType() templateParams.set_name(name) templateParams.set_deploy(deploy) templateParams.set_powerOn(power) source = vcloudType.ReferenceType(href=template_href) templateParams.set_Source(source) templateParams.set_AllEULAsAccepted("true") if vm_name or vm_cpus or vm_memory: params = vcloudType.SourcedCompositionItemParamType() if ((self.version == "1.0") or (self.version == "1.5") or (self.version == "5.1") or (self.version == "5.5")): message = 'Customization during instantiation is not ' +\ 'supported in this version, use vapp methods ' +\ 'to change vm name, cpu or memory' Log.error(self.logger, message) raise Exception(message) else: params.set_Source(vcloudType.ReferenceType(href=vm_href)) templateParams.add_SourcedItem(params) if vm_name: gen_params = vcloudType.VmGeneralParamsType() gen_params.set_Name(vm_name) params.set_VmGeneralParams(gen_params) if vm_cpus or vm_memory: inst_param = vcloudType.InstantiationParamsType() hardware = vcloudType.VirtualHardwareSection_Type(id=None) hardware.original_tagname_ = "VirtualHardwareSection" hardware.set_Info(vAppType.cimString(valueOf_="Virtual hardware requirements")) inst_param.add_Section(hardware) params.set_InstantiationParams(inst_param) if vm_cpus: cpudata = vAppType.RASD_Type() cpudata.original_tagname_ = "ovf:Item" cpudata.set_required(None) cpudata.set_AllocationUnits(vAppType.cimString(valueOf_="hertz * 10^6")) cpudata.set_Description(vAppType.cimString(valueOf_="Number of Virtual CPUs")) cpudata.set_ElementName(vAppType.cimString(valueOf_="{0} virtual CPU(s)".format(vm_cpus))) cpudata.set_InstanceID(vAppType.cimInt(valueOf_=1)) cpudata.set_ResourceType(3) cpudata.set_VirtualQuantity(vAppType.cimInt(valueOf_=vm_cpus)) hardware.add_Item(cpudata) if vm_memory: memorydata = vAppType.RASD_Type() memorydata.original_tagname_ = "ovf:Item" memorydata.set_required(None) memorydata.set_AllocationUnits(vAppType.cimString(valueOf_="byte * 2^20")) memorydata.set_Description(vAppType.cimString(valueOf_="Memory Size")) memorydata.set_ElementName(vAppType.cimString(valueOf_="{0} MB of memory".format(vm_memory))) memorydata.set_InstanceID(vAppType.cimInt(valueOf_=2)) memorydata.set_ResourceType(4) memorydata.set_VirtualQuantity(vAppType.cimInt(valueOf_=vm_memory)) hardware.add_Item(memorydata) return templateParams def _get_vdc_templates(self): content_type = "application/vnd.vmware.admin.vdcTemplates+xml" link = filter(lambda link: link.get_type() == content_type, self.vcloud_session.get_Link()) if len(link) == 0: return [] self.response = Http.get(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return vdcTemplateListType.parseString(self.response.content, True) def create_vdc(self, vdc_name, vdc_template_name=None): vdcTemplateList = self._get_vdc_templates() content_type = "application/vnd.vmware.admin.vdcTemplate+xml" vdcTemplate = None if vdc_template_name is None: vdcTemplate = filter(lambda link: link.get_type() == content_type, vdcTemplateList.get_VdcTemplate())[0] else: vdcTemplate = filter(lambda link: (link.get_type() == content_type) and (link.get_name() == vdc_template_name), vdcTemplateList.get_VdcTemplate())[0] source = vcloudType.ReferenceType(href=vdcTemplate.get_href()) templateParams = vcloudType.InstantiateVAppTemplateParamsType() # Too simple to add InstantiateVdcTemplateParamsType class templateParams.set_name(vdc_name) templateParams.set_Source(source) body = CommonUtils.convertPythonObjToStr(templateParams, name="InstantiateVdcTemplateParams", namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5"') content_type = "application/vnd.vmware.vcloud.instantiateVdcTemplateParams+xml" link = filter(lambda link: link.get_type() == content_type, self.vcloud_session.get_Link()) self.response = Http.post(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, data=body, logger=self.logger) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return task def delete_vdc(self, vdc_name): """ Request the deletion of an existing vdc. :param vdc_name: (str): The name of the virtual data center. :return: (tuple of (bool, task or str)) Two values are returned, a bool success indicator and a \ :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object if the bool value was True or a \ str message indicating the reason for failure if the bool value was False. **service type:** standalone, vchs, vca """ vdc = self.get_vdc(vdc_name) if vdc is None: return (False, 'VDC not found') vdc.get_href() self.response = Http.delete(vdc.get_href() + '?recursive=true&force=true', headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return (True, task) else: return (False, self.response.content) def create_vapp(self, vdc_name, vapp_name, template_name, catalog_name, network_name=None, network_mode='bridged', vm_name=None, vm_cpus=None, vm_memory=None, deploy='false', poweron='false'): """ Create a new vApp in a virtual data center. A vApp is an application package containing 1 or more virtual machines and their required operating system. :param vdc_name: (str): The virtual data center name. :param vapp_name: (str): The name of the new vapp. :param template_name: (str): The name of a template from a catalog that will be used to create the vApp. :param catalog_name: (str): The name of the catalog that contains the named template. :param network_name: (str): The name of the network contained within the vApp. :param network_mode: (str): The mode for the network contained within the vApp. :param vm_name: (str, optional): The name of the Virtual Machine contained in the vApp. :param vm_cpus: (str, optional): The number of virtual CPUs assigned to the VM. :param vm_memory: (str, optional): The amount of memory assigned to the VM, specified in MB. :param deploy: (bool): True to deploy the vApp immediately after creation, False otherwise. :param poweron: (bool): True to poweron the vApp immediately after deployment, False otherwise. :return: (task): a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType`, a handle to the asynchronous process executing the request. **service type:**. ondemand, subscription, vcd .. note:: In this version of pyvcloud a maximum of 1 vm can be added to a vapp. """ self.vdc = self.get_vdc(vdc_name) if not self.vcloud_session or not self.vcloud_session.organization or not self.vdc: #"Select an organization and datacenter first" return False if '' == vm_name: vm_name = None catalogs = filter(lambda link: catalog_name == link.get_name() and link.get_type() == "application/vnd.vmware.vcloud.catalog+xml", self.vcloud_session.organization.get_Link()) if len(catalogs) == 1: self.response = Http.get(catalogs[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: catalog = catalogType.parseString(self.response.content, True) catalog_items = filter(lambda catalogItemRef: catalogItemRef.get_name() == template_name, catalog.get_CatalogItems().get_CatalogItem()) if len(catalog_items) == 1: self.response = Http.get(catalog_items[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) # use ElementTree instead because none of the types inside resources (not even catalogItemType) is able to parse the response correctly catalogItem = ET.fromstring(self.response.content) entity = [child for child in catalogItem if child.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0] vm_href = None if vm_name: self.response = Http.get(entity.get('href'), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: vAppTemplate = ET.fromstring(self.response.content) for vm in vAppTemplate.iter('{http://www.vmware.com/vcloud/v1.5}Vm'): vm_href = vm.get('href') template_params = self._create_instantiateVAppTemplateParams( vapp_name, entity.get("href"), vm_name=vm_name, vm_href=vm_href, vm_cpus=vm_cpus, vm_memory=vm_memory, deploy=deploy, power=poweron) if network_name: pass output = StringIO() template_params.export(output, 0, name_ = 'InstantiateVAppTemplateParams', namespacedef_ = '''xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"''', pretty_print = False) body = '<?xml version="1.0" encoding="UTF-8"?>' + \ output.getvalue().replace('class:', 'rasd:')\ .replace(' xmlns:vmw="http://www.vmware.com/vcloud/v1.5"', '')\ .replace('vmw:', 'rasd:')\ .replace('Info>', "ovf:Info>") content_type = "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml" link = filter(lambda link: link.get_type() == content_type, self.vdc.get_Link()) self.response = Http.post(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, data=body, logger=self.logger) if self.response.status_code == requests.codes.created: vApp = vAppType.parseString(self.response.content, True) task = vApp.get_Tasks().get_Task()[0] return task return False def block_until_completed(self, task): """ Wait on a task until it has completed. A task is an asynchronous process executing a request. The status of the task is checked at one second intervals until the task is completed. No timeout. :param task: (task): A :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that represents a running task. :return: (bool) True if the task completed successfully, False if an error completed with an error. **service type:** ondemand, subscription, vcd """ progress = task.get_Progress() status = task.get_status() rnd = 0 while status != "success": if status == "error": error = task.get_Error() Log.error(self.logger, "task error, major=%s, minor=%s, message=%s" % (error.get_majorErrorCode(), error.get_minorErrorCode(), error.get_message())) return False else: # some task doesn't not report progress if progress: pass else: rnd += 1 time.sleep(1) self.response = Http.get(task.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: task = taskType.parseString(self.response.content, True) progress = task.get_Progress() status = task.get_status() else: Log.error(self.logger, "can't get task") return False return True def delete_vapp(self, vdc_name, vapp_name): """ Delete a specific vApp. A vApp is an application package containing 1 or more virtual machines and their required operating system. The vApp is undeployed and removed. :param vdc_name: (str): The virtual data center name. :param vapp_name: (str): The name of the vapp to be deleted. :return: (bool) True if the vapp was successfully deleted, false if the vapp was not found. **service type:** ondemand, subscription, vcd """ self.vdc = self.get_vdc(vdc_name) if not self.vcloud_session or not self.vcloud_session.organization or not self.vdc: return False vapp = self.get_vapp(self.vdc, vapp_name) if not vapp: return False #undeploy and remove if vapp.me.deployed: task = vapp.undeploy() if task: self.block_until_completed(task) else: Log.debug(self.logger, "vapp.undeploy() didn't return a task") return False vapp = self.get_vapp(self.vdc, vapp_name) if vapp: return vapp.delete() Log.debug(self.logger, "no vApp") def get_catalogs(self): """ Request a list of the available Public and Organization catalogs in the vdc. A catalog contains one or more vApp templates and media images. :return: (list of CatalogType) a list of :class:`pyvcloud.schema.vcd.v1_5.schemas.vcloud.catalogType.CatalogType` objects that describe the available catalogs. Each CatalogType contains a single :class:`.catalogType.CatalogItemsType` \n which contains a list of :class:`.vcloud.catalogType.ReferenceType` objects. use get_name() on a CatalogType to retrieve the catalog name. use get_name() on ReferenceType to retrieve the catalog item name. **service type:** ondemand, subscription, vcd """ self.vcloud_session.login(token=self.vcloud_session.token) links = filter(lambda link: link.get_type() == "application/vnd.vmware.vcloud.catalog+xml", self.vcloud_session.organization.Link) catalogs = [] for link in links: self.response = Http.get(link.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: catalogs.append(catalogType.parseString(self.response.content, True)) return catalogs def create_catalog(self, catalog_name, description): """ Create a new catalog. A catalog is a container for one or more vApp templates and media images. :param catalog_name: (str): The name of the new catalog. :param description: (str): A description for the new catalog. :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the creation of the catalog. **service type:** ondemand, subscription, vcd """ refs = filter(lambda ref: ref.rel == 'add' and ref.type_ == 'application/vnd.vmware.admin.catalog+xml', self.vcloud_session.organization.Link) if len(refs) == 1: data = """<?xml version="1.0" encoding="UTF-8"?> <AdminCatalog xmlns="http://www.vmware.com/vcloud/v1.5" name="%s"> <Description>%s</Description> </AdminCatalog> """ % (catalog_name, description) self.response = Http.post(refs[0].href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, data=data, logger=self.logger) if self.response.status_code == requests.codes.created: task = vCloudEntities.parseString(self.response.content, True) return task.get_Tasks().get_Task()[0] def delete_catalog(self, catalog_name): """ Delete a specific catalog. A catalog is a container for one or more vApp templates and media images. :param catalog_name: (str): The name of the catalog to delete. :return: (bool) True if the catalog was successfully deleted, false if the vapp was not deleted (or found). **service type:**. ondemand, subscription, vcd """ admin_url = None if not self.vcloud_session or not self.vcloud_session.organization: return False if 'ondemand' == self.service_type: refs = filter(lambda ref: ref.type_ == 'application/vnd.vmware.admin.organization+xml', self.vcloud_session.organization.Link) if len(refs) == 1: admin_url = refs[0].href else: refs = filter(lambda ref: ref.type_ == 'application/vnd.vmware.admin.catalog+xml', self.vcloud_session.organization.Link) if len(refs) == 1: admin_url = refs[0].href[:refs[0].href.rindex('/')] if admin_url: self.response = Http.get(admin_url, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: adminOrg = vCloudEntities.parseString(self.response.content, True) if adminOrg and adminOrg.Catalogs and adminOrg.Catalogs.CatalogReference: catRefs = filter(lambda ref: ref.name == catalog_name and ref.type_ == 'application/vnd.vmware.admin.catalog+xml', adminOrg.Catalogs.CatalogReference) if len(catRefs) == 1: self.response = Http.delete(catRefs[0].href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.no_content: return True return False def upload_media(self, catalog_name, item_name, media_file_name, description='', display_progress=False, chunk_bytes=128*1024): """ Uploads a media file (ISO) to a vCloud catalog :param catalog_name: (str): The name of the catalog to upload the media. :param item_name: (str): The name of the media file in the catalog. :param media_file_name: (str): The name of the local media file to upload. :return: (bool) True if the media file was successfully uploaded, false otherwise. **service type:** ondemand, subscription, vcd """ assert os.path.isfile(media_file_name) statinfo = os.stat(media_file_name) assert statinfo.st_size for catalog in self.get_catalogs(): if catalog_name != catalog.name: continue link = filter(lambda link: link.get_type() == "application/vnd.vmware.vcloud.media+xml" and link.get_rel() == 'add', catalog.get_Link()) assert len(link) == 1 Log.debug(self.logger, link[0].get_href()) data = """ <Media xmlns="http://www.vmware.com/vcloud/v1.5" name="%s" size="%s" imageType="iso"> <Description>%s</Description> </Media> """ % (item_name, statinfo.st_size, description) self.response = Http.post(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), data=data, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: catalogItem = ET.fromstring(self.response.content) entity = [child for child in catalogItem if child.get("type") == "application/vnd.vmware.vcloud.media+xml"][0] href = entity.get('href') self.response = Http.get(href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: media = mediaType.parseString(self.response.content, True) link = filter(lambda link: link.get_rel() == 'upload:default', media.get_Files().get_File()[0].get_Link())[0] progress_bar = None if display_progress: widgets = ['Uploading file: ', Percentage(), ' ', Bar(), ' ', ETA(), ' ', FileTransferSpeed()] progress_bar = ProgressBar(widgets=widgets, maxval=statinfo.st_size).start() f = open(media_file_name, 'rb') bytes_transferred = 0 while bytes_transferred < statinfo.st_size: my_bytes = f.read(chunk_bytes) if len(my_bytes) <= chunk_bytes: headers = self.vcloud_session.get_vcloud_headers() headers['Content-Range'] = 'bytes %s-%s/%s' % (bytes_transferred, len(my_bytes)-1, statinfo.st_size) headers['Content-Length'] = str(len(my_bytes)) self.response = Http.put(link.get_href(), headers=headers, data=my_bytes, verify=self.verify, logger=None) if self.response.status_code == requests.codes.ok: bytes_transferred += len(my_bytes) if display_progress: progress_bar.update(bytes_transferred) Log.debug(self.logger, 'transferred %s of %s bytes' % (str(bytes_transferred), str(statinfo.st_size))) else: Log.debug(self.logger, 'file upload failed with error: [%s] %s' % (self.response.status_code, self.response.content)) return False f.close() if display_progress: progress_bar.finish() return True return False def delete_catalog_item(self, catalog_name, item_name): """ Request the deletion of an item from a catalog. An item is a vApp template and media image stored in a catalog. :param catalog_name: (str): The name of the catalog to delete. :param item_name: (str): The name of the catalog item to delete. :return: (bool) True if the catalog item was successfully deleted, false if the vapp was not deleted (or found). **service type:** ondemand, subscription, vcd """ for catalog in self.get_catalogs(): if catalog_name != catalog.name: continue if catalog.CatalogItems and catalog.CatalogItems.CatalogItem: for item in catalog.CatalogItems.CatalogItem: if item_name == item.name: self.response = Http.delete(item.href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.no_content: return True return False def get_gateways(self, vdc_name): """ Request a list of the Gateways within a Virtual Data Center. :param vdc_name: (str): The virtual data center name. :return: (list of Gateway) A list of :class:`.pyvcloud.gateway.Gateway` objects describing the available gateways. **service type:** ondemand, subscription, vcd """ gateways = [] vdc = self.get_vdc(vdc_name) if not vdc: return gateways link = filter(lambda link: link.get_rel() == "edgeGateways", vdc.get_Link()) self.response = Http.get(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: queryResultRecords = queryRecordViewType.parseString(self.response.content, True) if queryResultRecords.get_Record(): for edgeGatewayRecord in queryResultRecords.get_Record(): self.response = Http.get(edgeGatewayRecord.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: gateway = Gateway(networkType.parseString(self.response.content, True), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, busy=edgeGatewayRecord.isBusy, log=self.log) gateways.append(gateway) return gateways def get_gateway(self, vdc_name, gateway_name): """ Request the details of a specific Gateway Appliance within a Virtual Data Center. :param vdc_name: (str): The virtual data center name. :param gateway_name: (str): The requested gateway name. :return: (Gateway) A :class:`.pyvcloud.gateway.Gateway` object describing the requested gateway. **service type:** ondemand, subscription, vcd """ gateway = None vdc = self.get_vdc(vdc_name) if not vdc: return gateway link = filter(lambda link: link.get_rel() == "edgeGateways", vdc.get_Link()) self.response = Http.get(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: queryResultRecords = queryRecordViewType.parseString(self.response.content, True) if queryResultRecords.get_Record(): for edgeGatewayRecord in queryResultRecords.get_Record(): if edgeGatewayRecord.get_name() == gateway_name: self.response = Http.get(edgeGatewayRecord.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: gateway = Gateway(networkType.parseString(self.response.content, True), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, busy=edgeGatewayRecord.isBusy, log=self.log) break return gateway def get_networks(self, vdc_name): """ Request a list of the Networks within a Virtual Data Center. :param vdc_name: (str): The virtual data center name. :return: (list of OrgVdcNetworkType) A list of :class:`pyvcloud.schema.vcd.v1_5.schemas.vcloud.networkType.OrgVdcNetworkType` objects describing the available networks. **service type:** ondemand, subscription, vcd """ result = [] vdc = self.get_vdc(vdc_name) if not vdc: return result networks = vdc.get_AvailableNetworks().get_Network() for n in networks: self.response = Http.get(n.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: network = networkType.parseString(self.response.content, True) result.append(network) return result def get_network(self, vdc_name, network_name): """ Request the details of a specific Network within a Virtual Data Center. :param vdc_name: (str): The virtual data center name. :param network_name: (str): The name of the requested network. :return: (OrgVdcNetworkType) An :class:`pyvcloud.schema.vcd.v1_5.schemas.vcloud.networkType.OrgVdcNetworkType` object describing the requested network. **service type:** ondemand, subscription, vcd """ result = None networks = self.get_networks(vdc_name) for network in networks: if network.get_name() == network_name: result = network return result def parsexml_(self, string_to_parse): doc = ET.fromstring(string_to_parse) return doc def get_media(self, catalog_name, media_name): """ Request a media resource from a catalog. :param catalog_name: (str): The name of the catalog containing the media. :param media_name: (str): The name of the requested media. :return: (dict of str,str) An dictionary describing the requested media. Dictionary keys in include a 'name' key with a value containing the media name. A 'href' key with a value containing a https url to the media. And a 'type' key with a value indicating the type of media. **service type:** ondemand, subscription, vcd """ refs = filter(lambda ref: ref.name == catalog_name and ref.type_ == 'application/vnd.vmware.vcloud.catalog+xml', self.vcloud_session.organization.Link) if len(refs) == 1: self.response = Http.get(refs[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: catalog = catalogType.parseString(self.response.content, True) catalog_items = filter(lambda catalogItemRef: catalogItemRef.get_name() == media_name, catalog.get_CatalogItems().get_CatalogItem()) if len(catalog_items) == 1: self.response = Http.get(catalog_items[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) # print self.response.content if self.response.status_code == requests.codes.ok: doc = self.parsexml_(self.response.content) for element in doc._children: if element.tag == '{http://www.vmware.com/vcloud/v1.5}Entity': return element.attrib # TODO: DELETE https://vchs.vmware.com/api/vchs/session def logout(self): """ Request to logout from vCloud Air. :return: **service type:** ondemand, subscription, vcd """ if self.service_type in [VCA.VCA_SERVICE_TYPE_STANDALONE, 'vcd']: pass elif self.service_type in [VCA.VCA_SERVICE_TYPE_VCHS, 'subscription']: pass elif self.service_type in [VCA.VCA_SERVICE_TYPE_VCA, 'ondemand']: pass self.token = None self.vcloud_session = None def create_vdc_network(self, vdc_name, network_name, gateway_name, start_address, end_address, gateway_ip, netmask, dns1, dns2, dns_suffix): """ Request the creation of an new network within a vdc. :param vdc_name: (str): The name of the virtual data center. :param network_name: (str): The name of the new network to be deleted. :param gateway_name: (str): The name of an existing edge Gateway appliance that will manage the virtual network. :param start_address: (str): The first ip address in a range of addresses for the network. :param end_address: (str): The last ip address in a range of addresses for the network. :return: (tuple of (bool, task or str)) Two values are returned, a bool success indicator and a \ :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object if the bool value was True or a \ str message indicating the reason for failure if the bool value was False. **service type:** ondemand, subscription, vcd """ vdc = self.get_vdc(vdc_name) gateway = ReferenceType(href=self.get_gateway(vdc_name, gateway_name).me.href) gateway.original_tagname_ = "EdgeGateway" iprange = IpRangeType(StartAddress=start_address, EndAddress=end_address) ipranges = IpRangesType(IpRange=[iprange]) ipscope = IpScopeType(IsInherited=False, Gateway=gateway_ip, Netmask=netmask, Dns1=dns1, Dns2=dns2, DnsSuffix=dns_suffix, IpRanges=ipranges) ipscopes = IpScopesType(IpScope=[ipscope]) configuration = NetworkConfigurationType(IpScopes=ipscopes, FenceMode="natRouted") net = OrgVdcNetworkType(name=network_name, Description="Network created by pyvcloud", EdgeGateway=gateway, Configuration=configuration, IsShared=False) namespacedef = 'xmlns="http://www.vmware.com/vcloud/v1.5"' content_type = "application/vnd.vmware.vcloud.orgVdcNetwork+xml" body = '<?xml version="1.0" encoding="UTF-8"?>{0}'.format( CommonUtils.convertPythonObjToStr(net, name='OrgVdcNetwork', namespacedef=namespacedef)) postlink = filter(lambda link: link.get_type() == content_type, vdc.get_Link())[0].href headers = self.vcloud_session.get_vcloud_headers() headers["Content-Type"] = content_type self.response = Http.post(postlink, data=body, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: network = networkType.parseString(self.response.content, True) task = network.get_Tasks().get_Task()[0] return (True, task) else: return (False, self.response.content) def delete_vdc_network(self, vdc_name, network_name): """ Request the deletion of an existing network within a vdc. :param vdc_name: (str): The name of the virtual data center. :param network_name: (str): The name of the new network to be deleted. :return: (tuple of (bool, task or str)) Two values are returned, a bool success indicator and a \ :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object if the bool value was True or a \ str message indicating the reason for failure if the bool value was False. **service type:** ondemand, subscription, vcd """ netref = self.get_admin_network_href(vdc_name, network_name) if netref is None: return (False, 'network not found') self.response = Http.delete(netref, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return (True, task) else: return (False, self.response.content) def get_admin_network_href(self, vdc_name, network_name): vdc = self.get_vdc(vdc_name) link = filter(lambda link: link.get_rel() == "orgVdcNetworks", vdc.get_Link()) self.response = Http.get(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) queryResultRecords = queryRecordViewType.parseString(self.response.content, True) if self.response.status_code == requests.codes.ok: for record in queryResultRecords.get_Record(): if record.name == network_name: return record.href def get_score_service(self, score_service_url): if self.vcloud_session is None or self.vcloud_session.token is None: Log.error(self.logger, "self.vcloud_session is None") return None return Score(score_service_url, self.vcloud_session.org_url, self.vcloud_session.token, self.version, self.verify, self.log) def get_diskRefs(self, vdc): """ Request a list of references to disk volumes in a vdc. :param vdc: (str): The name of the virtual data center. :return: (list of ResourceReferenceType) A list of :class:`pyvcloud.schema.vcd.v1_5.schemas.vcloud.vdcType.ResourceReferenceType` objects. Use get_name(), get_type() and get_href() methods on each list entry to return disk details. **service type:** ondemand, subscription, vcd """ resourceEntities = vdc.get_ResourceEntities().get_ResourceEntity() return [resourceEntity for resourceEntity in resourceEntities if resourceEntity.get_type() == "application/vnd.vmware.vcloud.disk+xml"] def _parse_disk(self, content): diskDesc = diskType.parseString(content, True) disk = DiskType() ids = diskDesc.anyAttributes_.get('id').split(':') disk.set_id(ids[3]) disk.set_name(diskDesc.anyAttributes_.get('name')) disk.set_size(diskDesc.anyAttributes_.get('size')) disk.set_busType(diskDesc.anyAttributes_.get('busType')) disk.set_busSubType(diskDesc.anyAttributes_.get('busSubType')) disk.set_status(diskDesc.anyAttributes_.get('status')) xml = ET.fromstring(content) for child in xml: if '{http://www.vmware.com/vcloud/v1.5}Owner' == child.tag: for grandchild in child: owner = OwnerType() owner.set_User(grandchild.attrib['name']) disk.set_Owner(owner) if '{http://www.vmware.com/vcloud/v1.5}StorageProfile' == child.tag: storageProfile = VdcStorageProfileType() storageProfile.set_name(child.attrib['name']) disk.set_StorageProfile(storageProfile) if '{http://www.vmware.com/vcloud/v1.5}Tasks' == child.tag: task = taskType.parseString(ET.tostring(child.getchildren()[0]), True) disk.set_Tasks([task]) return disk def get_disks(self, vdc_name): """ Request a list of disks attached to a vdc. :param vdc_name: (str): The name of a virtual data center. :return: (list of tuples of (DiskType, list of str)): An list of tuples. \ Each tuple contains a :class:`pyvcloud.schema.vcd.v1_5.schemas.vcloud.diskType.DiskType` object and a list of vms utilizing the disk. **service type:** ondemand, subscription, vcd """ vdc = self.get_vdc(vdc_name) links = self.get_diskRefs(vdc) disks = [] for link in links: response = Http.get(link.get_href(), headers = self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) disk = self._parse_disk(response.content) vms = [] content_type = "application/vnd.vmware.vcloud.vms+xml" response = Http.get(link.get_href()+'/attachedVms', headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) # print response.content listofvms = vmsType.parseString(response.content, True) for vmReference in listofvms.get_VmReference(): vms.append(vmReference) disks.append([disk, vms]) return disks def add_disk(self, vdc_name, name, size): """ Request the creation of an indepdent disk (not attached to a vApp). :param vdc_name: (str): The name of the virtual data center. :param name: (str): The name of the new disk. :param size: (str): The size of the new disk in MB. :return: (tuple(bool, DiskType)) Two values are returned, a bool success indicator and a :class:`pyvcloud.schema.vcd.v1_5.schemas.vcloud.diskType.DiskType` object describing the disk resource. **service type:** ondemand, subscription, vcd """ data = """ <vcloud:DiskCreateParams xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"> <vcloud:Disk name="%s" size="%s"/> </vcloud:DiskCreateParams> """ % (name, size) vdc = self.get_vdc(vdc_name) content_type = "application/vnd.vmware.vcloud.diskCreateParams+xml" link = filter(lambda link: link.get_type() == content_type, vdc.get_Link()) self.response = Http.post(link[0].get_href(), data=data, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: disk = self._parse_disk(self.response.content) return(True, disk) else: return(False, self.response.content) def delete_disk(self, vdc_name, name, id=None): """ Request the deletion of an existing disk within a vdc. :param vdc_name: (str): The name of the virtual data center. :param name: (str): The name of the new disk. :param id: (str, optional): The id of the disk resource. :return: (tuple(bool, TaskType)) Two values are returned, a bool success indicator and a \ :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object if the bool value was True or a \ str message indicating the reason for failure if the bool value was False. **service type:** ondemand, subscription, vcd """ vdc = self.get_vdc(vdc_name) refs = self.get_diskRefs(vdc) link = [] if id is not None: link = filter(lambda link: link.get_href().endswith('/'+id), refs) elif name is not None: link = filter(lambda link: link.get_name() == name, refs) if len(link) == 1: self.response = Http.delete(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return (True, task) else: return(False, self.response.content) elif len(link) == 0: return(False, 'disk not found') elif len(link) > 1: return(False, 'more than one disks found with that name, use the disk id') def cancel_task(self, task_url): self.response = Http.post(task_url + '/action/cancel', headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.no_content: return True else: Log.error(self.logger, "can't cancel task") return False def get_status(self, code): return self.statuses[code+1] def get_vdc_templates(self): if self.vcloud_session.organization is None: self.vcloud_session.login(token=self.vcloud_session.token) vdcTemplateList = self._get_vdc_templates() return vdcTemplateList
apache-2.0
chenc10/Spark-PAF
dist/ec2/lib/boto-2.34.0/boto/ec2/instanceinfo.py
152
1893
# Copyright (c) 2006-2008 Mitch Garnaat http://garnaat.org/ # # 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, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing 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 MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR 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. class InstanceInfo(object): """ Represents an EC2 Instance status response from CloudWatch """ def __init__(self, connection=None, id=None, state=None): """ :ivar str id: The instance's EC2 ID. :ivar str state: Specifies the current status of the instance. """ self.connection = connection self.id = id self.state = state def __repr__(self): return 'InstanceInfo:%s' % self.id def startElement(self, name, attrs, connection): return None def endElement(self, name, value, connection): if name == 'instanceId' or name == 'InstanceId': self.id = value elif name == 'state': self.state = value else: setattr(self, name, value)
apache-2.0
arohacs/fabfile
fabfile.py
1
4753
# Copyright 2011-2012 Adam Rohacs # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from fabric.api import local from fabric.contrib.project import rsync_project from fabric.api import * from fabric.api import env, run import re import subprocess from subprocess import PIPE, Popen, STDOUT, call import ssh env.forward_agent = True env.user = 'user' env.key_filename = ('/home/user/.ssh/filename') envdir = ['/home/user/dir/'] env.roledefs = { 'test': ['user@host'], 'test2': ['user@host'], 'vm': ['host_IP'], 'prod': ['user@host'] } def vmheadless(vm='host', cmd='start'): '''usage: vmheadless:vm="vm name",cmd="start/stop"''' full_cmd = '' if cmd == 'start': full_cmd = 'VBoxHeadless -s ' + vm + ' --vrde=off' ' &' #don't need vrde if I'm only ssh'ing to the box elif cmd == 'stop': full_cmd += 'VBoxManage controlvm ' + vm + ' savestate' print "press enter to do the following:", full_cmd raw_input() local(full_cmd) def rundev(name="host",proj='myproj'): #can change name of env as needed for command '''usage: rundev:name="host",proj="myproj"''' print "starting dev server..." local("cd /home/user/directory ; python manage.py runserver --insecure" % (name, proj)) def deploy(pushorpull='push',remoteenv='env',project='myproj',svName='',sshPort=): '''usage: fab deploy:pushorpull="push/pull",remotenv="myenv",project="myproj",svName="",sshPort="''' #svName='django' normally, but changed for first deploy to prevent failure print env.host_string wordlist=[] #parse data from 'pwd' command output = subprocess.Popen(['pwd'],\ stdout=subprocess.PIPE).communicate()[0] #get location of virtualenv words = output.split('/') #use regex to split directories counter = 0 #keep track of which part is which myDirShard = '' #will contain part of dir that I want for index in words: if counter > 0: #once we have passed the .virtualenv directory myDirShard += '/' + str(index).rstrip() if 'virtualenv' in index: #let us know when to start counting counter +=1 myDirShard += '/' #add slashes so directory can be used as-is devdir = '/home/user/dir/'+ myDirShard #make dev dir for use with pull/push remotedir = str(env.host_string) + ":~/.virtualenvs" + '/' + remoteenv + '/' + project print "Dev directory = {0} and remote directory = {1} - correct?".format(devdir,remotedir) print "Press enter if this is ok, or control-c to exit: " raw_input() if svName: #for first deploy, svName should not yet exist as there is no project to use runit against print"Stopping Django on {0} - press enter to continue or control-c to exit: ".format(env.host_string) raw_input() args = ('stop',svName,sshPort) _django(*args) #stop django so I can pull the database or push it back with other changes if pushorpull == 'push': print "I will push {0} to {1}, ok?".format(devdir, remotedir) raw_input("press 'enter' to continue ...") local('rsync -avz -e "ssh -p %s" --progress %s %s' % (sshPort, devdir, remotedir)) elif pushorpull == 'pull': print "I will pull {0} to {1}, ok?".format(remotedir, devdir) raw_input("press 'enter' to continue ...") local('rsync -avz -e "ssh -p %s" --progress %s %s' % (sshPort, remotedir, devdir)) if svName: print"Starting Django on {0} ...".format(env.host_string) args = ('start',svName,sshPort) _django(*args) getmem() def _django(DjangoCmd='restart',svName='myServiceName',sshPort=): #print "I will perform this option: {0}".format('sudo sv '+ DjangoCmd + " " + svName) #raw_input("press enter") env.host_string += ':' + sshPort sudo('sv %s %s' % (DjangoCmd, svName)) def getmem(): ''' runs free -m command ''' run(' free -m') def _agent_run(cmd): #for h in env.hosts: for h in env.roledefs: try: host, port = h.split(':') local('ssh -p %s -A %s %s' % (port, host, cmd)) except ValueError: local('ssh -A %s %s' % (h, cmd))
gpl-3.0
Zephor5/scrapy
scrapy/utils/defer.py
62
3554
""" Helper functions for dealing with Twisted deferreds """ from twisted.internet import defer, reactor, task from twisted.python import failure from scrapy.exceptions import IgnoreRequest def defer_fail(_failure): """Same as twisted.internet.defer.fail but delay calling errback until next reactor loop It delays by 100ms so reactor has a chance to go trough readers and writers before attending pending delayed calls, so do not set delay to zero. """ d = defer.Deferred() reactor.callLater(0.1, d.errback, _failure) return d def defer_succeed(result): """Same as twisted.internet.defer.succeed but delay calling callback until next reactor loop It delays by 100ms so reactor has a chance to go trough readers and writers before attending pending delayed calls, so do not set delay to zero. """ d = defer.Deferred() reactor.callLater(0.1, d.callback, result) return d def defer_result(result): if isinstance(result, defer.Deferred): return result elif isinstance(result, failure.Failure): return defer_fail(result) else: return defer_succeed(result) def mustbe_deferred(f, *args, **kw): """Same as twisted.internet.defer.maybeDeferred, but delay calling callback/errback to next reactor loop """ try: result = f(*args, **kw) # FIXME: Hack to avoid introspecting tracebacks. This to speed up # processing of IgnoreRequest errors which are, by far, the most common # exception in Scrapy - see #125 except IgnoreRequest as e: return defer_fail(failure.Failure(e)) except: return defer_fail(failure.Failure()) else: return defer_result(result) def parallel(iterable, count, callable, *args, **named): """Execute a callable over the objects in the given iterable, in parallel, using no more than ``count`` concurrent calls. Taken from: http://jcalderone.livejournal.com/24285.html """ coop = task.Cooperator() work = (callable(elem, *args, **named) for elem in iterable) return defer.DeferredList([coop.coiterate(work) for _ in range(count)]) def process_chain(callbacks, input, *a, **kw): """Return a Deferred built by chaining the given callbacks""" d = defer.Deferred() for x in callbacks: d.addCallback(x, *a, **kw) d.callback(input) return d def process_chain_both(callbacks, errbacks, input, *a, **kw): """Return a Deferred built by chaining the given callbacks and errbacks""" d = defer.Deferred() for cb, eb in zip(callbacks, errbacks): d.addCallbacks(cb, eb, callbackArgs=a, callbackKeywords=kw, errbackArgs=a, errbackKeywords=kw) if isinstance(input, failure.Failure): d.errback(input) else: d.callback(input) return d def process_parallel(callbacks, input, *a, **kw): """Return a Deferred with the output of all successful calls to the given callbacks """ dfds = [defer.succeed(input).addCallback(x, *a, **kw) for x in callbacks] d = defer.DeferredList(dfds, fireOnOneErrback=1, consumeErrors=1) d.addCallbacks(lambda r: [x[1] for x in r], lambda f: f.value.subFailure) return d def iter_errback(iterable, errback, *a, **kw): """Wraps an iterable calling an errback if an error is caught while iterating it. """ it = iter(iterable) while True: try: yield next(it) except StopIteration: break except: errback(failure.Failure(), *a, **kw)
bsd-3-clause
ahamilton55/ansible
lib/ansible/modules/cloud/univention/udm_user.py
69
21748
#!/usr/bin/python # -*- coding: UTF-8 -*- # Copyright (c) 2016, Adfinis SyGroup AG # Tobias Rueetschi <tobias.ruetschi@adfinis-sygroup.ch> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: udm_user version_added: "2.2" author: "Tobias Rueetschi (@2-B)" short_description: Manage posix users on a univention corporate server description: - "This module allows to manage posix users on a univention corporate server (UCS). It uses the python API of the UCS to create a new object or edit it." requirements: - Python >= 2.6 options: state: required: false default: "present" choices: [ present, absent ] description: - Whether the user is present or not. username: required: true description: - User name aliases: ['name'] firstname: required: false description: - First name. Required if C(state=present). lastname: required: false description: - Last name. Required if C(state=present). password: required: false default: None description: - Password. Required if C(state=present). birthday: required: false default: None description: - Birthday city: required: false default: None description: - City of users business address. country: required: false default: None description: - Country of users business address. department_number: required: false default: None description: - Department number of users business address. aliases: [ departmentNumber ] description: required: false default: None description: - Description (not gecos) display_name: required: false default: None description: - Display name (not gecos) aliases: [ displayName ] email: required: false default: [''] description: - A list of e-mail addresses. employee_number: required: false default: None description: - Employee number aliases: [ employeeNumber ] employee_type: required: false default: None description: - Employee type aliases: [ employeeType ] gecos: required: false default: None description: - GECOS groups: required: false default: [] description: - "POSIX groups, the LDAP DNs of the groups will be found with the LDAP filter for each group as $GROUP: C((&(objectClass=posixGroup)(cn=$GROUP)))." home_share: required: false default: None description: - "Home NFS share. Must be a LDAP DN, e.g. C(cn=home,cn=shares,ou=school,dc=example,dc=com)." aliases: [ homeShare ] home_share_path: required: false default: None description: - Path to home NFS share, inside the homeShare. aliases: [ homeSharePath ] home_telephone_number: required: false default: [] description: - List of private telephone numbers. aliases: [ homeTelephoneNumber ] homedrive: required: false default: None description: - Windows home drive, e.g. C("H:"). mail_alternative_address: required: false default: [] description: - List of alternative e-mail addresses. aliases: [ mailAlternativeAddress ] mail_home_server: required: false default: None description: - FQDN of mail server aliases: [ mailHomeServer ] mail_primary_address: required: false default: None description: - Primary e-mail address aliases: [ mailPrimaryAddress ] mobile_telephone_number: required: false default: [] description: - Mobile phone number aliases: [ mobileTelephoneNumber ] organisation: required: false default: None description: - Organisation override_pw_history: required: false default: False description: - Override password history aliases: [ overridePWHistory ] override_pw_length: required: false default: False description: - Override password check aliases: [ overridePWLength ] pager_telephonenumber: required: false default: [] description: - List of pager telephone numbers. aliases: [ pagerTelephonenumber ] phone: required: false default: [] description: - List of telephone numbers. postcode: required: false default: None description: - Postal code of users business address. primary_group: required: false default: cn=Domain Users,cn=groups,$LDAP_BASE_DN description: - Primary group. This must be the group LDAP DN. aliases: [ primaryGroup ] profilepath: required: false default: None description: - Windows profile directory pwd_change_next_login: required: false default: None choices: [ '0', '1' ] description: - Change password on next login. aliases: [ pwdChangeNextLogin ] room_number: required: false default: None description: - Room number of users business address. aliases: [ roomNumber ] samba_privileges: required: false default: [] description: - "Samba privilege, like allow printer administration, do domain join." aliases: [ sambaPrivileges ] samba_user_workstations: required: false default: [] description: - Allow the authentication only on this Microsoft Windows host. aliases: [ sambaUserWorkstations ] sambahome: required: false default: None description: - Windows home path, e.g. C('\\\\$FQDN\\$USERNAME'). scriptpath: required: false default: None description: - Windows logon script. secretary: required: false default: [] description: - A list of superiors as LDAP DNs. serviceprovider: required: false default: [''] description: - Enable user for the following service providers. shell: required: false default: '/bin/bash' description: - Login shell street: required: false default: None description: - Street of users business address. title: required: false default: None description: - Title, e.g. C(Prof.). unixhome: required: false default: '/home/$USERNAME' description: - Unix home directory userexpiry: required: false default: Today + 1 year description: - Account expiry date, e.g. C(1999-12-31). position: required: false default: '' description: - "Define the whole position of users object inside the LDAP tree, e.g. C(cn=employee,cn=users,ou=school,dc=example,dc=com)." update_password: required: false default: always description: - "C(always) will update passwords if they differ. C(on_create) will only set the password for newly created users." version_added: "2.3" ou: required: false default: '' description: - "Organizational Unit inside the LDAP Base DN, e.g. C(school) for LDAP OU C(ou=school,dc=example,dc=com)." subpath: required: false default: 'cn=users' description: - "LDAP subpath inside the organizational unit, e.g. C(cn=teachers,cn=users) for LDAP container C(cn=teachers,cn=users,dc=example,dc=com)." ''' EXAMPLES = ''' # Create a user on a UCS - udm_user: name: FooBar password: secure_password firstname: Foo lastname: Bar # Create a user with the DN # C(uid=foo,cn=teachers,cn=users,ou=school,dc=school,dc=example,dc=com) - udm_user: name: foo password: secure_password firstname: Foo lastname: Bar ou: school subpath: 'cn=teachers,cn=users' # or define the position - udm_user: name: foo password: secure_password firstname: Foo lastname: Bar position: 'cn=teachers,cn=users,ou=school,dc=school,dc=example,dc=com' ''' RETURN = '''# ''' from datetime import date import crypt from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.univention_umc import ( umc_module_for_add, umc_module_for_edit, ldap_search, base_dn, ) from dateutil.relativedelta import relativedelta def main(): expiry = date.strftime(date.today() + relativedelta(years=1), "%Y-%m-%d") module = AnsibleModule( argument_spec = dict( birthday = dict(default=None, type='str'), city = dict(default=None, type='str'), country = dict(default=None, type='str'), department_number = dict(default=None, type='str', aliases=['departmentNumber']), description = dict(default=None, type='str'), display_name = dict(default=None, type='str', aliases=['displayName']), email = dict(default=[''], type='list'), employee_number = dict(default=None, type='str', aliases=['employeeNumber']), employee_type = dict(default=None, type='str', aliases=['employeeType']), firstname = dict(default=None, type='str'), gecos = dict(default=None, type='str'), groups = dict(default=[], type='list'), home_share = dict(default=None, type='str', aliases=['homeShare']), home_share_path = dict(default=None, type='str', aliases=['homeSharePath']), home_telephone_number = dict(default=[], type='list', aliases=['homeTelephoneNumber']), homedrive = dict(default=None, type='str'), lastname = dict(default=None, type='str'), mail_alternative_address= dict(default=[], type='list', aliases=['mailAlternativeAddress']), mail_home_server = dict(default=None, type='str', aliases=['mailHomeServer']), mail_primary_address = dict(default=None, type='str', aliases=['mailPrimaryAddress']), mobile_telephone_number = dict(default=[], type='list', aliases=['mobileTelephoneNumber']), organisation = dict(default=None, type='str'), overridePWHistory = dict(default=False, type='bool', aliases=['override_pw_history']), overridePWLength = dict(default=False, type='bool', aliases=['override_pw_length']), pager_telephonenumber = dict(default=[], type='list', aliases=['pagerTelephonenumber']), password = dict(default=None, type='str', no_log=True), phone = dict(default=[], type='list'), postcode = dict(default=None, type='str'), primary_group = dict(default=None, type='str', aliases=['primaryGroup']), profilepath = dict(default=None, type='str'), pwd_change_next_login = dict(default=None, type='str', choices=['0', '1'], aliases=['pwdChangeNextLogin']), room_number = dict(default=None, type='str', aliases=['roomNumber']), samba_privileges = dict(default=[], type='list', aliases=['sambaPrivileges']), samba_user_workstations = dict(default=[], type='list', aliases=['sambaUserWorkstations']), sambahome = dict(default=None, type='str'), scriptpath = dict(default=None, type='str'), secretary = dict(default=[], type='list'), serviceprovider = dict(default=[''], type='list'), shell = dict(default='/bin/bash', type='str'), street = dict(default=None, type='str'), title = dict(default=None, type='str'), unixhome = dict(default=None, type='str'), userexpiry = dict(default=expiry, type='str'), username = dict(required=True, aliases=['name'], type='str'), position = dict(default='', type='str'), update_password = dict(default='always', choices=['always', 'on_create'], type='str'), ou = dict(default='', type='str'), subpath = dict(default='cn=users', type='str'), state = dict(default='present', choices=['present', 'absent'], type='str') ), supports_check_mode=True, required_if = ([ ('state', 'present', ['firstname', 'lastname', 'password']) ]) ) username = module.params['username'] position = module.params['position'] ou = module.params['ou'] subpath = module.params['subpath'] state = module.params['state'] changed = False users = list(ldap_search( '(&(objectClass=posixAccount)(uid={}))'.format(username), attr=['uid'] )) if position != '': container = position else: if ou != '': ou = 'ou={},'.format(ou) if subpath != '': subpath = '{},'.format(subpath) container = '{}{}{}'.format(subpath, ou, base_dn()) user_dn = 'uid={},{}'.format(username, container) exists = bool(len(users)) if state == 'present': try: if not exists: obj = umc_module_for_add('users/user', container) else: obj = umc_module_for_edit('users/user', user_dn) if module.params['displayName'] is None: module.params['displayName'] = '{} {}'.format( module.params['firstname'], module.params['lastname'] ) if module.params['unixhome'] is None: module.params['unixhome'] = '/home/{}'.format( module.params['username'] ) for k in obj.keys(): if (k != 'password' and k != 'groups' and k != 'overridePWHistory' and k in module.params and module.params[k] is not None): obj[k] = module.params[k] # handle some special values obj['e-mail'] = module.params['email'] password = module.params['password'] if obj['password'] is None: obj['password'] = password if module.params['update_password'] == 'always': old_password = obj['password'].split('}', 2)[1] if crypt.crypt(password, old_password) != old_password: obj['overridePWHistory'] = module.params['overridePWHistory'] obj['overridePWLength'] = module.params['overridePWLength'] obj['password'] = password diff = obj.diff() if exists: for k in obj.keys(): if obj.hasChanged(k): changed = True else: changed = True if not module.check_mode: if not exists: obj.create() elif changed: obj.modify() except: module.fail_json( msg="Creating/editing user {} in {} failed".format( username, container ) ) try: groups = module.params['groups'] if groups: filter = '(&(objectClass=posixGroup)(|(cn={})))'.format( ')(cn='.join(groups) ) group_dns = list(ldap_search(filter, attr=['dn'])) for dn in group_dns: grp = umc_module_for_edit('groups/group', dn[0]) if user_dn not in grp['users']: grp['users'].append(user_dn) if not module.check_mode: grp.modify() changed = True except: module.fail_json( msg="Adding groups to user {} failed".format(username) ) if state == 'absent' and exists: try: obj = umc_module_for_edit('users/user', user_dn) if not module.check_mode: obj.remove() changed = True except: module.fail_json( msg="Removing user {} failed".format(username) ) module.exit_json( changed=changed, username=username, diff=diff, container=container ) if __name__ == '__main__': main()
gpl-3.0
mindriot101/bokeh
sphinx/source/docs/user_guide/examples/extensions_putting_together_ts.py
9
2258
from bokeh.core.properties import String, Instance from bokeh.models import LayoutDOM, Slider CODE =""" import {div, empty} from "core/dom" import * as p from "core/properties" import {LayoutDOM, LayoutDOMView} from "models/layouts/layout_dom" export class CustomView extends LayoutDOMView { initialize(options) { super.initialize(options) this.render() // Set BokehJS listener so that when the Bokeh slider has a change // event, we can process the new data this.connect(this.model.slider.change, () => this.render()) } render() { // BokehjS Views create <div> elements by default, accessible as // ``this.el``. Many Bokeh views ignore this default <div>, and instead // do things like draw to the HTML canvas. In this case though, we change // the contents of the <div>, based on the current slider value. empty(this.el) this.el.appendChild(div({ style: { 'padding': '2px', 'color': '#b88d8e', 'background-color': '#2a3153', }, }, `${this.model.text}: ${this.model.slider.value}`)) } } export class Custom extends LayoutDOM { // If there is an associated view, this is typically boilerplate. default_view = CustomView // The ``type`` class attribute should generally match exactly the name // of the corresponding Python class. type = "Custom" } // The @define block adds corresponding "properties" to the JS model. These // should normally line up 1-1 with the Python model class. Most property // types have counterparts, e.g. bokeh.core.properties.String will be // ``p.String`` in the JS implementation. Any time the JS type system is not // yet as complete, you can use ``p.Any`` as a "wildcard" property type. Custom.define({ text: [ p.String ], slider: [ p.Any ], }) """ from bokeh.util.compiler import TypeScript class Custom(LayoutDOM): __implementation__ = TypeScript(CODE) text = String(default="Custom text") slider = Instance(Slider) from bokeh.io import show from bokeh.layouts import column from bokeh.models import Slider slider = Slider(start=0, end=10, step=0.1, value=0, title="value") custom = Custom(text="Special Slider Display", slider=slider) layout = column(slider, custom) show(layout)
bsd-3-clause
henrytao-me/openerp.positionq
openerp/modules/__init__.py
66
1595
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.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/>. # ############################################################################## """ Modules (also called addons) management. """ from . import db, graph, loading, migration, module, registry # TODO temporarily expose those things from openerp.modules.module import \ get_modules, get_modules_with_version, \ load_information_from_description_file, \ get_module_resource, zip_directory, \ get_module_path, initialize_sys_path, \ load_openerp_module, init_module_models, \ adapt_version from openerp.modules.loading import load_modules # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
googlearchive/appengine-try-python-flask
lib/flask/signals.py
783
2140
# -*- coding: utf-8 -*- """ flask.signals ~~~~~~~~~~~~~ Implements signals based on blinker if available, otherwise falls silently back to a noop :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ signals_available = False try: from blinker import Namespace signals_available = True except ImportError: class Namespace(object): def signal(self, name, doc=None): return _FakeSignal(name, doc) class _FakeSignal(object): """If blinker is unavailable, create a fake class with the same interface that allows sending of signals but will fail with an error on anything else. Instead of doing anything on send, it will just ignore the arguments and do nothing instead. """ def __init__(self, name, doc=None): self.name = name self.__doc__ = doc def _fail(self, *args, **kwargs): raise RuntimeError('signalling support is unavailable ' 'because the blinker library is ' 'not installed.') send = lambda *a, **kw: None connect = disconnect = has_receivers_for = receivers_for = \ temporarily_connected_to = connected_to = _fail del _fail # the namespace for code signals. If you are not flask code, do # not put signals in here. Create your own namespace instead. _signals = Namespace() # core signals. For usage examples grep the sourcecode or consult # the API documentation in docs/api.rst as well as docs/signals.rst template_rendered = _signals.signal('template-rendered') request_started = _signals.signal('request-started') request_finished = _signals.signal('request-finished') request_tearing_down = _signals.signal('request-tearing-down') got_request_exception = _signals.signal('got-request-exception') appcontext_tearing_down = _signals.signal('appcontext-tearing-down') appcontext_pushed = _signals.signal('appcontext-pushed') appcontext_popped = _signals.signal('appcontext-popped') message_flashed = _signals.signal('message-flashed')
apache-2.0
zahodi/ansible
lib/ansible/playbook/role_include.py
66
5020
# # 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 from os.path import basename from ansible.errors import AnsibleParserError from ansible.playbook.attribute import FieldAttribute from ansible.playbook.task import Task from ansible.playbook.role import Role from ansible.playbook.role.include import RoleInclude try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() __all__ = ['IncludeRole'] class IncludeRole(Task): """ A Role include is derived from a regular role to handle the special circumstances related to the `- include_role: ...` """ # ================================================================================= # ATTRIBUTES # private as this is a 'module options' vs a task property _allow_duplicates = FieldAttribute(isa='bool', default=True, private=True) _private = FieldAttribute(isa='bool', default=None, private=True) _static = FieldAttribute(isa='bool', default=None) def __init__(self, block=None, role=None, task_include=None): super(IncludeRole, self).__init__(block=block, role=role, task_include=task_include) self.statically_loaded = False self._from_files = {} self._parent_role = role self._role_name = None def get_block_list(self, play=None, variable_manager=None, loader=None): # only need play passed in when dynamic if play is None: myplay = self._parent._play else: myplay = play ri = RoleInclude.load(self._role_name, play=myplay, variable_manager=variable_manager, loader=loader) ri.vars.update(self.vars) # build role actual_role = Role.load(ri, myplay, parent_role=self._parent_role, from_files=self._from_files) actual_role._metadata.allow_duplicates = self.allow_duplicates # compile role with parent roles as dependencies to ensure they inherit # variables if not self._parent_role: dep_chain = [] else: dep_chain = list(self._parent_role._parents) dep_chain.extend(self._parent_role.get_all_dependencies()) dep_chain.append(self._parent_role) blocks = actual_role.compile(play=myplay, dep_chain=dep_chain) for b in blocks: b._parent = self # updated available handlers in play myplay.handlers = myplay.handlers + actual_role.get_handler_blocks(play=myplay) return blocks @staticmethod def load(data, block=None, role=None, task_include=None, variable_manager=None, loader=None): ir = IncludeRole(block, role, task_include=task_include).load_data(data, variable_manager=variable_manager, loader=loader) ### Process options # name is needed, or use role as alias ir._role_name = ir.args.get('name', ir.args.get('role')) if ir._role_name is None: raise AnsibleParserError("'name' is a required field for include_role.") # build options for role includes for key in ['tasks', 'vars', 'defaults']: from_key ='%s_from' % key if ir.args.get(from_key): ir._from_files[key] = basename(ir.args.get(from_key)) #FIXME: find a way to make this list come from object ( attributes does not work as per below) # manual list as otherwise the options would set other task parameters we don't want. for option in ['private', 'allow_duplicates']: if option in ir.args: setattr(ir, option, ir.args.get(option)) return ir.load_data(data, variable_manager=variable_manager, loader=loader) def copy(self, exclude_parent=False, exclude_tasks=False): new_me = super(IncludeRole, self).copy(exclude_parent=exclude_parent, exclude_tasks=exclude_tasks) new_me.statically_loaded = self.statically_loaded new_me._from_files = self._from_files.copy() new_me._parent_role = self._parent_role new_me._role_name = self._role_name return new_me def get_include_params(self): v = super(IncludeRole, self).get_include_params() if self._parent_role: v.update(self._parent_role.get_role_params()) return v
gpl-3.0
stvstnfrd/edx-platform
common/lib/xmodule/xmodule/modulestore/tests/test_split_modulestore_bulk_operations.py
1
36024
""" Tests for bulk operations in Split Modulestore. """ # pylint: disable=protected-access import copy import unittest import six import ddt from bson.objectid import ObjectId from mock import MagicMock, Mock, call from opaque_keys.edx.locator import CourseLocator from six.moves import range from xmodule.modulestore.split_mongo.mongo_connection import MongoConnection from xmodule.modulestore.split_mongo.split import SplitBulkWriteMixin VERSION_GUID_DICT = { 'SAMPLE_VERSION_GUID': 'deadbeef1234' * 2, 'SAMPLE_UNICODE_VERSION_GUID': u'deadbeef1234' * 2, 'BSON_OBJECTID': ObjectId() } SAMPLE_GUIDS_LIST = ['SAMPLE_VERSION_GUID', 'SAMPLE_UNICODE_VERSION_GUID', 'BSON_OBJECTID'] class TestBulkWriteMixin(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring def setUp(self): super(TestBulkWriteMixin, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.bulk = SplitBulkWriteMixin() self.bulk.SCHEMA_VERSION = 1 self.clear_cache = self.bulk._clear_cache = Mock(name='_clear_cache') self.conn = self.bulk.db_connection = MagicMock(name='db_connection', spec=MongoConnection) self.conn.get_course_index.return_value = {'initial': 'index'} self.course_key = CourseLocator('org', 'course', 'run-a', branch='test') self.course_key_b = CourseLocator('org', 'course', 'run-b', branch='test') self.structure = {'this': 'is', 'a': 'structure', '_id': ObjectId()} self.definition = {'this': 'is', 'a': 'definition', '_id': ObjectId()} self.index_entry = {'this': 'is', 'an': 'index'} def assertConnCalls(self, *calls): assert list(calls) == self.conn.mock_calls def assertCacheNotCleared(self): assert not self.clear_cache.called class TestBulkWriteMixinPreviousTransaction(TestBulkWriteMixin): """ Verify that opening and closing a transaction doesn't affect later behaviour. """ def setUp(self): super(TestBulkWriteMixinPreviousTransaction, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.bulk._begin_bulk_operation(self.course_key) self.bulk.insert_course_index(self.course_key, MagicMock('prev-index-entry')) self.bulk.update_structure(self.course_key, {'this': 'is', 'the': 'previous structure', '_id': ObjectId()}) self.bulk._end_bulk_operation(self.course_key) self.conn.reset_mock() self.clear_cache.reset_mock() @ddt.ddt class TestBulkWriteMixinClosed(TestBulkWriteMixin): """ Tests of the bulk write mixin when bulk operations aren't active. """ @ddt.data(*SAMPLE_GUIDS_LIST) def test_no_bulk_read_structure(self, version_guid_name): # Reading a structure when no bulk operation is active should just call # through to the db_connection version_guid = VERSION_GUID_DICT[version_guid_name] result = self.bulk.get_structure(self.course_key, version_guid) self.assertConnCalls( call.get_structure(self.course_key.as_object_id(version_guid), self.course_key) ) assert result == self.conn.get_structure.return_value self.assertCacheNotCleared() def test_no_bulk_write_structure(self): # Writing a structure when no bulk operation is active should just # call through to the db_connection. It should also clear the # system cache self.bulk.update_structure(self.course_key, self.structure) self.assertConnCalls(call.insert_structure(self.structure, self.course_key)) self.clear_cache.assert_called_once_with(self.structure['_id']) @ddt.data(*SAMPLE_GUIDS_LIST) def test_no_bulk_read_definition(self, version_guid_name): # Reading a definition when no bulk operation is active should just call # through to the db_connection version_guid = VERSION_GUID_DICT[version_guid_name] result = self.bulk.get_definition(self.course_key, version_guid) self.assertConnCalls( call.get_definition( self.course_key.as_object_id(version_guid), self.course_key ) ) assert result == self.conn.get_definition.return_value def test_no_bulk_write_definition(self): # Writing a definition when no bulk operation is active should just # call through to the db_connection. self.bulk.update_definition(self.course_key, self.definition) self.assertConnCalls(call.insert_definition(self.definition, self.course_key)) @ddt.data(True, False) def test_no_bulk_read_index(self, ignore_case): # Reading a course index when no bulk operation is active should just call # through to the db_connection result = self.bulk.get_course_index(self.course_key, ignore_case=ignore_case) self.assertConnCalls(call.get_course_index(self.course_key, ignore_case)) assert result == self.conn.get_course_index.return_value self.assertCacheNotCleared() def test_no_bulk_write_index(self): # Writing a course index when no bulk operation is active should just call # through to the db_connection self.bulk.insert_course_index(self.course_key, self.index_entry) self.assertConnCalls(call.insert_course_index(self.index_entry, self.course_key)) self.assertCacheNotCleared() def test_out_of_order_end(self): # Calling _end_bulk_operation without a corresponding _begin... # is a noop self.bulk._end_bulk_operation(self.course_key) def test_write_new_index_on_close(self): self.conn.get_course_index.return_value = None self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.insert_course_index(self.course_key, self.index_entry) self.assertConnCalls() self.bulk._end_bulk_operation(self.course_key) self.conn.insert_course_index.assert_called_once_with(self.index_entry, self.course_key) def test_write_updated_index_on_close(self): old_index = {'this': 'is', 'an': 'old index'} self.conn.get_course_index.return_value = old_index self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.insert_course_index(self.course_key, self.index_entry) self.assertConnCalls() self.bulk._end_bulk_operation(self.course_key) self.conn.update_course_index.assert_called_once_with( self.index_entry, from_index=old_index, course_context=self.course_key, ) def test_write_structure_on_close(self): self.conn.get_course_index.return_value = None self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.update_structure(self.course_key, self.structure) self.assertConnCalls() self.bulk._end_bulk_operation(self.course_key) self.assertConnCalls(call.insert_structure(self.structure, self.course_key)) def test_write_multiple_structures_on_close(self): self.conn.get_course_index.return_value = None self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.update_structure(self.course_key.replace(branch='a'), self.structure) other_structure = {'another': 'structure', '_id': ObjectId()} self.bulk.update_structure(self.course_key.replace(branch='b'), other_structure) self.assertConnCalls() self.bulk._end_bulk_operation(self.course_key) six.assertCountEqual( self, [ call.insert_structure(self.structure, self.course_key), call.insert_structure(other_structure, self.course_key) ], self.conn.mock_calls ) def test_write_index_and_definition_on_close(self): original_index = {'versions': {}} self.conn.get_course_index.return_value = copy.deepcopy(original_index) self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.update_definition(self.course_key, self.definition) self.bulk.insert_course_index(self.course_key, {'versions': {self.course_key.branch: self.definition['_id']}}) # lint-amnesty, pylint: disable=no-member self.assertConnCalls() self.bulk._end_bulk_operation(self.course_key) self.assertConnCalls( call.insert_definition(self.definition, self.course_key), call.update_course_index( {'versions': {self.course_key.branch: self.definition['_id']}}, # lint-amnesty, pylint: disable=no-member from_index=original_index, course_context=self.course_key ) ) def test_write_index_and_multiple_definitions_on_close(self): original_index = {'versions': {'a': ObjectId(), 'b': ObjectId()}} self.conn.get_course_index.return_value = copy.deepcopy(original_index) self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.update_definition(self.course_key.replace(branch='a'), self.definition) other_definition = {'another': 'definition', '_id': ObjectId()} self.bulk.update_definition(self.course_key.replace(branch='b'), other_definition) self.bulk.insert_course_index(self.course_key, {'versions': {'a': self.definition['_id'], 'b': other_definition['_id']}}) # lint-amnesty, pylint: disable=line-too-long self.bulk._end_bulk_operation(self.course_key) six.assertCountEqual( self, [ call.insert_definition(self.definition, self.course_key), call.insert_definition(other_definition, self.course_key), call.update_course_index( {'versions': {'a': self.definition['_id'], 'b': other_definition['_id']}}, from_index=original_index, course_context=self.course_key, ) ], self.conn.mock_calls ) def test_write_definition_on_close(self): self.conn.get_course_index.return_value = None self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.update_definition(self.course_key, self.definition) self.assertConnCalls() self.bulk._end_bulk_operation(self.course_key) self.assertConnCalls(call.insert_definition(self.definition, self.course_key)) def test_write_multiple_definitions_on_close(self): self.conn.get_course_index.return_value = None self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.update_definition(self.course_key.replace(branch='a'), self.definition) other_definition = {'another': 'definition', '_id': ObjectId()} self.bulk.update_definition(self.course_key.replace(branch='b'), other_definition) self.assertConnCalls() self.bulk._end_bulk_operation(self.course_key) six.assertCountEqual( self, [ call.insert_definition(self.definition, self.course_key), call.insert_definition(other_definition, self.course_key) ], self.conn.mock_calls ) def test_write_index_and_structure_on_close(self): original_index = {'versions': {}} self.conn.get_course_index.return_value = copy.deepcopy(original_index) self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.update_structure(self.course_key, self.structure) self.bulk.insert_course_index(self.course_key, {'versions': {self.course_key.branch: self.structure['_id']}}) # lint-amnesty, pylint: disable=no-member self.assertConnCalls() self.bulk._end_bulk_operation(self.course_key) self.assertConnCalls( call.insert_structure(self.structure, self.course_key), call.update_course_index( {'versions': {self.course_key.branch: self.structure['_id']}}, # lint-amnesty, pylint: disable=no-member from_index=original_index, course_context=self.course_key, ) ) def test_write_index_and_multiple_structures_on_close(self): original_index = {'versions': {'a': ObjectId(), 'b': ObjectId()}} self.conn.get_course_index.return_value = copy.deepcopy(original_index) self.bulk._begin_bulk_operation(self.course_key) self.conn.reset_mock() self.bulk.update_structure(self.course_key.replace(branch='a'), self.structure) other_structure = {'another': 'structure', '_id': ObjectId()} self.bulk.update_structure(self.course_key.replace(branch='b'), other_structure) self.bulk.insert_course_index(self.course_key, {'versions': {'a': self.structure['_id'], 'b': other_structure['_id']}}) # lint-amnesty, pylint: disable=line-too-long self.bulk._end_bulk_operation(self.course_key) six.assertCountEqual( self, [ call.insert_structure(self.structure, self.course_key), call.insert_structure(other_structure, self.course_key), call.update_course_index( {'versions': {'a': self.structure['_id'], 'b': other_structure['_id']}}, from_index=original_index, course_context=self.course_key, ) ], self.conn.mock_calls ) def test_version_structure_creates_new_version(self): assert self.bulk.version_structure(self.course_key, self.structure, 'user_id')['_id'] != self.structure['_id'] def test_version_structure_new_course(self): self.conn.get_course_index.return_value = None self.bulk._begin_bulk_operation(self.course_key) version_result = self.bulk.version_structure(self.course_key, self.structure, 'user_id') get_result = self.bulk.get_structure(self.course_key, version_result['_id']) assert version_result == get_result class TestBulkWriteMixinClosedAfterPrevTransaction(TestBulkWriteMixinClosed, TestBulkWriteMixinPreviousTransaction): # lint-amnesty, pylint: disable=test-inherits-tests """ Test that operations on with a closed transaction aren't affected by a previously executed transaction """ pass # lint-amnesty, pylint: disable=unnecessary-pass @ddt.ddt class TestBulkWriteMixinFindMethods(TestBulkWriteMixin): """ Tests of BulkWriteMixin methods for finding many structures or indexes """ def test_no_bulk_find_matching_course_indexes(self): branch = Mock(name='branch') search_targets = MagicMock(name='search_targets') org_targets = None self.conn.find_matching_course_indexes.return_value = [Mock(name='result')] result = self.bulk.find_matching_course_indexes(branch, search_targets) self.assertConnCalls(call.find_matching_course_indexes( branch, search_targets, org_targets, course_keys=None ) ) assert result == self.conn.find_matching_course_indexes.return_value self.assertCacheNotCleared() @ddt.data( (None, None, [], []), ( 'draft', None, [{'versions': {'draft': '123'}}], [ {'versions': {'published': '123'}}, {} ], ), ( 'draft', {'f1': 'v1'}, [{'versions': {'draft': '123'}, 'search_targets': {'f1': 'v1'}}], [ {'versions': {'draft': '123'}, 'search_targets': {'f1': 'value2'}}, {'versions': {'published': '123'}, 'search_targets': {'f1': 'v1'}}, {'search_targets': {'f1': 'v1'}}, {'versions': {'draft': '123'}}, ], ), ( None, {'f1': 'v1'}, [ {'versions': {'draft': '123'}, 'search_targets': {'f1': 'v1'}}, {'versions': {'published': '123'}, 'search_targets': {'f1': 'v1'}}, {'search_targets': {'f1': 'v1'}}, ], [ {'versions': {'draft': '123'}, 'search_targets': {'f1': 'v2'}}, {'versions': {'draft': '123'}, 'search_targets': {'f2': 'v1'}}, {'versions': {'draft': '123'}}, ], ), ( None, {'f1': 'v1', 'f2': 2}, [ {'search_targets': {'f1': 'v1', 'f2': 2}}, {'search_targets': {'f1': 'v1', 'f2': 2}}, ], [ {'versions': {'draft': '123'}, 'search_targets': {'f1': 'v1'}}, {'search_targets': {'f1': 'v1'}}, {'versions': {'draft': '123'}, 'search_targets': {'f1': 'v2'}}, {'versions': {'draft': '123'}}, ], ), ) @ddt.unpack def test_find_matching_course_indexes(self, branch, search_targets, matching, unmatching): db_indexes = [{'org': 'what', 'course': 'this', 'run': 'needs'}] for n, index in enumerate(matching + unmatching): course_key = CourseLocator('org', 'course', 'run{}'.format(n)) self.bulk._begin_bulk_operation(course_key) for attr in ['org', 'course', 'run']: index[attr] = getattr(course_key, attr) self.bulk.insert_course_index(course_key, index) expected = matching + db_indexes self.conn.find_matching_course_indexes.return_value = db_indexes result = self.bulk.find_matching_course_indexes(branch, search_targets) six.assertCountEqual(self, result, expected) for item in unmatching: assert item not in result def test_no_bulk_find_structures_by_id(self): ids = [Mock(name='id')] self.conn.find_structures_by_id.return_value = [MagicMock(name='result')] result = self.bulk.find_structures_by_id(ids) self.assertConnCalls(call.find_structures_by_id(ids)) assert result == self.conn.find_structures_by_id.return_value self.assertCacheNotCleared() @ddt.data( ([], [], []), ([1, 2, 3], [1, 2], [1, 2]), ([1, 2, 3], [1], [1, 2]), ([1, 2, 3], [], [1, 2]), ) @ddt.unpack def test_find_structures_by_id(self, search_ids, active_ids, db_ids): db_structure = lambda _id: {'db': 'structure', '_id': _id} active_structure = lambda _id: {'active': 'structure', '_id': _id} db_structures = [db_structure(_id) for _id in db_ids if _id not in active_ids] for n, _id in enumerate(active_ids): course_key = CourseLocator('org', 'course', 'run{}'.format(n)) self.bulk._begin_bulk_operation(course_key) self.bulk.update_structure(course_key, active_structure(_id)) self.conn.find_structures_by_id.return_value = db_structures results = self.bulk.find_structures_by_id(search_ids) self.conn.find_structures_by_id.assert_called_once_with(list(set(search_ids) - set(active_ids))) for _id in active_ids: if _id in search_ids: assert active_structure(_id) in results else: assert active_structure(_id) not in results for _id in db_ids: if _id in search_ids and _id not in active_ids: assert db_structure(_id) in results else: assert db_structure(_id) not in results @ddt.data( ([], [], []), ([1, 2, 3], [1, 2], [1, 2]), ([1, 2, 3], [1], [1, 2]), ([1, 2, 3], [], [1, 2]), ) @ddt.unpack def test_get_definitions(self, search_ids, active_ids, db_ids): db_definition = lambda _id: {'db': 'definition', '_id': _id} active_definition = lambda _id: {'active': 'definition', '_id': _id} db_definitions = [db_definition(_id) for _id in db_ids if _id not in active_ids] self.bulk._begin_bulk_operation(self.course_key) for _id in active_ids: self.bulk.update_definition(self.course_key, active_definition(_id)) self.conn.get_definitions.return_value = db_definitions results = self.bulk.get_definitions(self.course_key, search_ids) definitions_gotten = list(set(search_ids) - set(active_ids)) if len(definitions_gotten) > 0: self.conn.get_definitions.assert_called_once_with(definitions_gotten, self.course_key) else: # If no definitions to get, then get_definitions() should *not* have been called. assert self.conn.get_definitions.call_count == 0 for _id in active_ids: if _id in search_ids: assert active_definition(_id) in results else: assert active_definition(_id) not in results for _id in db_ids: if _id in search_ids and _id not in active_ids: assert db_definition(_id) in results else: assert db_definition(_id) not in results def test_get_definitions_doesnt_update_db(self): test_ids = [1, 2] db_definition = lambda _id: {'db': 'definition', '_id': _id} db_definitions = [db_definition(_id) for _id in test_ids] self.conn.get_definitions.return_value = db_definitions self.bulk._begin_bulk_operation(self.course_key) self.bulk.get_definitions(self.course_key, test_ids) self.bulk._end_bulk_operation(self.course_key) assert not self.conn.insert_definition.called def test_no_bulk_find_structures_derived_from(self): ids = [Mock(name='id')] self.conn.find_structures_derived_from.return_value = [MagicMock(name='result')] result = self.bulk.find_structures_derived_from(ids) self.assertConnCalls(call.find_structures_derived_from(ids)) assert result == self.conn.find_structures_derived_from.return_value self.assertCacheNotCleared() @ddt.data( # Test values are: # - previous_versions to search for # - documents in the cache with $previous_version.$_id # - documents in the db with $previous_version.$_id ([], [], []), (['1', '2', '3'], ['1.a', '1.b', '2.c'], ['1.a', '2.c']), (['1', '2', '3'], ['1.a'], ['1.a', '2.c']), (['1', '2', '3'], [], ['1.a', '2.c']), (['1', '2', '3'], ['4.d'], ['1.a', '2.c']), ) @ddt.unpack def test_find_structures_derived_from(self, search_ids, active_ids, db_ids): def db_structure(_id): previous, _, current = _id.partition('.') return {'db': 'structure', 'previous_version': previous, '_id': current} def active_structure(_id): previous, _, current = _id.partition('.') return {'active': 'structure', 'previous_version': previous, '_id': current} db_structures = [db_structure(_id) for _id in db_ids] active_structures = [] for n, _id in enumerate(active_ids): course_key = CourseLocator('org', 'course', 'run{}'.format(n)) self.bulk._begin_bulk_operation(course_key) structure = active_structure(_id) self.bulk.update_structure(course_key, structure) active_structures.append(structure) self.conn.find_structures_derived_from.return_value = db_structures results = self.bulk.find_structures_derived_from(search_ids) self.conn.find_structures_derived_from.assert_called_once_with(search_ids) for structure in active_structures: if structure['previous_version'] in search_ids: assert structure in results else: assert structure not in results for structure in db_structures: if ( structure['previous_version'] in search_ids and # We're searching for this document not any(active.endswith(structure['_id']) for active in active_ids) # This document doesn't match any active _ids # lint-amnesty, pylint: disable=line-too-long ): assert structure in results else: assert structure not in results def test_no_bulk_find_ancestor_structures(self): original_version = Mock(name='original_version') block_id = Mock(name='block_id') self.conn.find_ancestor_structures.return_value = [MagicMock(name='result')] result = self.bulk.find_ancestor_structures(original_version, block_id) self.assertConnCalls(call.find_ancestor_structures(original_version, block_id)) assert result == self.conn.find_ancestor_structures.return_value self.assertCacheNotCleared() @ddt.data( # Test values are: # - original_version # - block_id # - matching documents in the cache # - non-matching documents in the cache # - expected documents returned from the db # - unexpected documents returned from the db ('ov', 'bi', [{'original_version': 'ov', 'blocks': {'bi': {'edit_info': {'update_version': 'foo'}}}}], [], [], []), # lint-amnesty, pylint: disable=line-too-long ('ov', 'bi', [{'original_version': 'ov', 'blocks': {'bi': {'edit_info': {'update_version': 'foo'}}}, '_id': 'foo'}], [], [], [{'_id': 'foo'}]), # lint-amnesty, pylint: disable=line-too-long ('ov', 'bi', [], [{'blocks': {'bi': {'edit_info': {'update_version': 'foo'}}}}], [], []), ('ov', 'bi', [], [{'original_version': 'ov'}], [], []), ('ov', 'bi', [], [], [{'original_version': 'ov', 'blocks': {'bi': {'edit_info': {'update_version': 'foo'}}}}], []), # lint-amnesty, pylint: disable=line-too-long ( 'ov', 'bi', [{'original_version': 'ov', 'blocks': {'bi': {'edit_info': {'update_version': 'foo'}}}}], [], [{'original_version': 'ov', 'blocks': {'bi': {'edit_info': {'update_version': 'bar'}}}}], [] ), ) @ddt.unpack def test_find_ancestor_structures(self, original_version, block_id, active_match, active_unmatch, db_match, db_unmatch): # lint-amnesty, pylint: disable=line-too-long for structure in active_match + active_unmatch + db_match + db_unmatch: structure.setdefault('_id', ObjectId()) for n, structure in enumerate(active_match + active_unmatch): course_key = CourseLocator('org', 'course', 'run{}'.format(n)) self.bulk._begin_bulk_operation(course_key) self.bulk.update_structure(course_key, structure) self.conn.find_ancestor_structures.return_value = db_match + db_unmatch results = self.bulk.find_ancestor_structures(original_version, block_id) self.conn.find_ancestor_structures.assert_called_once_with(original_version, block_id) six.assertCountEqual(self, active_match + db_match, results) @ddt.ddt class TestBulkWriteMixinOpen(TestBulkWriteMixin): """ Tests of the bulk write mixin when bulk write operations are open """ def setUp(self): super(TestBulkWriteMixinOpen, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.bulk._begin_bulk_operation(self.course_key) @ddt.data(*SAMPLE_GUIDS_LIST) def test_read_structure_without_write_from_db(self, version_guid_name): # Reading a structure before it's been written (while in bulk operation mode) # returns the structure from the database version_guid = VERSION_GUID_DICT[version_guid_name] result = self.bulk.get_structure(self.course_key, version_guid) assert self.conn.get_structure.call_count == 1 assert result == self.conn.get_structure.return_value self.assertCacheNotCleared() @ddt.data(*SAMPLE_GUIDS_LIST) def test_read_structure_without_write_only_reads_once(self, version_guid_name): # Reading the same structure multiple times shouldn't hit the database # more than once version_guid = VERSION_GUID_DICT[version_guid_name] for _ in range(2): result = self.bulk.get_structure(self.course_key, version_guid) assert self.conn.get_structure.call_count == 1 assert result == self.conn.get_structure.return_value self.assertCacheNotCleared() @ddt.data(*SAMPLE_GUIDS_LIST) def test_read_structure_after_write_no_db(self, version_guid_name): # Reading a structure that's already been written shouldn't hit the db at all version_guid = VERSION_GUID_DICT[version_guid_name] self.structure['_id'] = version_guid self.bulk.update_structure(self.course_key, self.structure) result = self.bulk.get_structure(self.course_key, version_guid) assert self.conn.get_structure.call_count == 0 assert result == self.structure @ddt.data(*SAMPLE_GUIDS_LIST) def test_read_structure_after_write_after_read(self, version_guid_name): # Reading a structure that's been updated after being pulled from the db should # still get the updated value version_guid = VERSION_GUID_DICT[version_guid_name] self.structure['_id'] = version_guid self.bulk.get_structure(self.course_key, version_guid) self.bulk.update_structure(self.course_key, self.structure) result = self.bulk.get_structure(self.course_key, version_guid) assert self.conn.get_structure.call_count == 1 assert result == self.structure @ddt.data(*SAMPLE_GUIDS_LIST) def test_read_definition_without_write_from_db(self, version_guid_name): # Reading a definition before it's been written (while in bulk operation mode) # returns the definition from the database version_guid = VERSION_GUID_DICT[version_guid_name] result = self.bulk.get_definition(self.course_key, version_guid) assert self.conn.get_definition.call_count == 1 assert result == self.conn.get_definition.return_value self.assertCacheNotCleared() @ddt.data(*SAMPLE_GUIDS_LIST) def test_read_definition_without_write_only_reads_once(self, version_guid_name): # Reading the same definition multiple times shouldn't hit the database # more than once version_guid = VERSION_GUID_DICT[version_guid_name] for _ in range(2): result = self.bulk.get_definition(self.course_key, version_guid) assert self.conn.get_definition.call_count == 1 assert result == self.conn.get_definition.return_value self.assertCacheNotCleared() @ddt.data(*SAMPLE_GUIDS_LIST) def test_read_definition_after_write_no_db(self, version_guid_name): # Reading a definition that's already been written shouldn't hit the db at all version_guid = VERSION_GUID_DICT[version_guid_name] self.definition['_id'] = version_guid self.bulk.update_definition(self.course_key, self.definition) result = self.bulk.get_definition(self.course_key, version_guid) assert self.conn.get_definition.call_count == 0 assert result == self.definition @ddt.data(*SAMPLE_GUIDS_LIST) def test_read_definition_after_write_after_read(self, version_guid_name): # Reading a definition that's been updated after being pulled from the db should # still get the updated value version_guid = VERSION_GUID_DICT[version_guid_name] self.definition['_id'] = version_guid self.bulk.get_definition(self.course_key, version_guid) self.bulk.update_definition(self.course_key, self.definition) result = self.bulk.get_definition(self.course_key, version_guid) assert self.conn.get_definition.call_count == 1 assert result == self.definition @ddt.data(True, False) def test_read_index_without_write_from_db(self, ignore_case): # Reading the index without writing to it should pull from the database result = self.bulk.get_course_index(self.course_key, ignore_case=ignore_case) assert self.conn.get_course_index.call_count == 1 assert self.conn.get_course_index.return_value == result @ddt.data(True, False) def test_read_index_without_write_only_reads_once(self, ignore_case): # Reading the index multiple times should only result in one read from # the database for _ in range(2): result = self.bulk.get_course_index(self.course_key, ignore_case=ignore_case) assert self.conn.get_course_index.call_count == 1 assert self.conn.get_course_index.return_value == result @ddt.data(True, False) def test_read_index_after_write(self, ignore_case): # Reading the index after a write still should hit the database once to fetch the # initial index, and should return the written index_entry self.bulk.insert_course_index(self.course_key, self.index_entry) result = self.bulk.get_course_index(self.course_key, ignore_case=ignore_case) assert self.conn.get_course_index.call_count == 1 assert self.index_entry == result def test_read_index_ignore_case(self): # Reading using ignore case should find an already written entry with a different case self.bulk.insert_course_index(self.course_key, self.index_entry) result = self.bulk.get_course_index( self.course_key.replace( org=self.course_key.org.upper(), course=self.course_key.course.title(), run=self.course_key.run.upper() ), ignore_case=True ) assert self.conn.get_course_index.call_count == 1 assert self.index_entry == result def test_version_structure_creates_new_version_before_read(self): assert self.bulk.version_structure(self.course_key, self.structure, 'user_id')['_id'] != self.structure['_id'] def test_version_structure_creates_new_version_after_read(self): self.conn.get_structure.return_value = copy.deepcopy(self.structure) self.bulk.get_structure(self.course_key, self.structure['_id']) assert self.bulk.version_structure(self.course_key, self.structure, 'user_id')['_id'] != self.structure['_id'] def test_copy_branch_versions(self): # Directly updating an index so that the draft branch points to the published index # version should work, and should only persist a single structure self.maxDiff = None published_structure = {'published': 'structure', '_id': ObjectId()} self.bulk.update_structure(self.course_key, published_structure) index = {'versions': {'published': published_structure['_id']}} self.bulk.insert_course_index(self.course_key, index) index_copy = copy.deepcopy(index) index_copy['versions']['draft'] = index['versions']['published'] self.bulk.update_course_index(self.course_key, index_copy) self.bulk._end_bulk_operation(self.course_key) self.conn.insert_structure.assert_called_once_with(published_structure, self.course_key) self.conn.update_course_index.assert_called_once_with( index_copy, from_index=self.conn.get_course_index.return_value, course_context=self.course_key, ) self.conn.get_course_index.assert_called_once_with(self.course_key, ignore_case=False) class TestBulkWriteMixinOpenAfterPrevTransaction(TestBulkWriteMixinOpen, TestBulkWriteMixinPreviousTransaction): # lint-amnesty, pylint: disable=test-inherits-tests """ Test that operations on with an open transaction aren't affected by a previously executed transaction """ pass # lint-amnesty, pylint: disable=unnecessary-pass
agpl-3.0
maurofaccenda/ansible
lib/ansible/modules/cloud/google/gc_storage.py
64
16793
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gc_storage version_added: "1.4" short_description: This module manages objects/buckets in Google Cloud Storage. description: - This module allows users to manage their objects/buckets in Google Cloud Storage. It allows upload and download operations and can set some canned permissions. It also allows retrieval of URLs for objects for use in playbooks, and retrieval of string contents of objects. This module requires setting the default project in GCS prior to playbook usage. See U(https://developers.google.com/storage/docs/reference/v1/apiversion1) for information about setting the default project. options: bucket: description: - Bucket name. required: true object: description: - Keyname of the object inside the bucket. Can be also be used to create "virtual directories" (see examples). required: false default: null src: description: - The source file path when performing a PUT operation. required: false default: null dest: description: - The destination file path when downloading an object/key with a GET operation. required: false force: description: - Forces an overwrite either locally on the filesystem or remotely with the object/key. Used with PUT and GET operations. required: false default: true aliases: [ 'overwrite' ] permission: description: - This option let's the user set the canned permissions on the object/bucket that are created. The permissions that can be set are 'private', 'public-read', 'authenticated-read'. required: false default: private headers: version_added: "2.0" description: - Headers to attach to object. required: false default: '{}' expiration: description: - Time limit (in seconds) for the URL generated and returned by GCA when performing a mode=put or mode=get_url operation. This url is only available when public-read is the acl for the object. required: false default: null mode: description: - Switches the module behaviour between upload, download, get_url (return download url) , get_str (download object as string), create (bucket) and delete (bucket). required: true default: null choices: [ 'get', 'put', 'get_url', 'get_str', 'delete', 'create' ] gs_secret_key: description: - GS secret key. If not set then the value of the GS_SECRET_ACCESS_KEY environment variable is used. required: true default: null gs_access_key: description: - GS access key. If not set then the value of the GS_ACCESS_KEY_ID environment variable is used. required: true default: null requirements: - "python >= 2.6" - "boto >= 2.9" author: "Benno Joy (@bennojoy)" ''' EXAMPLES = ''' - name: Upload some content gc_storage: bucket: mybucket object: key.txt src: /usr/local/myfile.txt mode: put permission: public-read - name: Upload some headers gc_storage: bucket: mybucket object: key.txt src: /usr/local/myfile.txt headers: '{"Content-Encoding": "gzip"}' - name: Download some content gc_storage: bucket: mybucket object: key.txt dest: /usr/local/myfile.txt mode: get - name: Download an object as a string to use else where in your playbook gc_storage: bucket: mybucket object: key.txt mode: get_str - name: Create an empty bucket gc_storage: bucket: mybucket mode: create - name: Create a bucket with key as directory gc_storage: bucket: mybucket object: /my/directory/path mode: create - name: Delete a bucket and all contents gc_storage: bucket: mybucket mode: delete ''' import os import urlparse import hashlib try: import boto HAS_BOTO = True except ImportError: HAS_BOTO = False def grant_check(module, gs, obj): try: acp = obj.get_acl() if module.params.get('permission') == 'public-read': grant = [ x for x in acp.entries.entry_list if x.scope.type == 'AllUsers'] if not grant: obj.set_acl('public-read') module.exit_json(changed=True, result="The objects permission as been set to public-read") if module.params.get('permission') == 'authenticated-read': grant = [ x for x in acp.entries.entry_list if x.scope.type == 'AllAuthenticatedUsers'] if not grant: obj.set_acl('authenticated-read') module.exit_json(changed=True, result="The objects permission as been set to authenticated-read") except gs.provider.storage_response_error as e: module.fail_json(msg= str(e)) return True def key_check(module, gs, bucket, obj): try: bucket = gs.lookup(bucket) key_check = bucket.get_key(obj) except gs.provider.storage_response_error as e: module.fail_json(msg= str(e)) if key_check: grant_check(module, gs, key_check) return True else: return False def keysum(module, gs, bucket, obj): bucket = gs.lookup(bucket) key_check = bucket.get_key(obj) if not key_check: return None md5_remote = key_check.etag[1:-1] etag_multipart = '-' in md5_remote # Check for multipart, etag is not md5 if etag_multipart is True: module.fail_json(msg="Files uploaded with multipart of gs are not supported with checksum, unable to compute checksum.") return md5_remote def bucket_check(module, gs, bucket): try: result = gs.lookup(bucket) except gs.provider.storage_response_error as e: module.fail_json(msg= str(e)) if result: grant_check(module, gs, result) return True else: return False def create_bucket(module, gs, bucket): try: bucket = gs.create_bucket(bucket) bucket.set_acl(module.params.get('permission')) except gs.provider.storage_response_error as e: module.fail_json(msg= str(e)) if bucket: return True def delete_bucket(module, gs, bucket): try: bucket = gs.lookup(bucket) bucket_contents = bucket.list() for key in bucket_contents: bucket.delete_key(key.name) bucket.delete() return True except gs.provider.storage_response_error as e: module.fail_json(msg= str(e)) def delete_key(module, gs, bucket, obj): try: bucket = gs.lookup(bucket) bucket.delete_key(obj) module.exit_json(msg="Object deleted from bucket ", changed=True) except gs.provider.storage_response_error as e: module.fail_json(msg= str(e)) def create_dirkey(module, gs, bucket, obj): try: bucket = gs.lookup(bucket) key = bucket.new_key(obj) key.set_contents_from_string('') module.exit_json(msg="Virtual directory %s created in bucket %s" % (obj, bucket.name), changed=True) except gs.provider.storage_response_error as e: module.fail_json(msg= str(e)) def path_check(path): if os.path.exists(path): return True else: return False def transform_headers(headers): """ Boto url-encodes values unless we convert the value to `str`, so doing this prevents 'max-age=100000' from being converted to "max-age%3D100000". :param headers: Headers to convert :type headers: dict :rtype: dict """ for key, value in headers.items(): headers[key] = str(value) return headers def upload_gsfile(module, gs, bucket, obj, src, expiry): try: bucket = gs.lookup(bucket) key = bucket.new_key(obj) key.set_contents_from_filename( filename=src, headers=transform_headers(module.params.get('headers')) ) key.set_acl(module.params.get('permission')) url = key.generate_url(expiry) module.exit_json(msg="PUT operation complete", url=url, changed=True) except gs.provider.storage_copy_error as e: module.fail_json(msg= str(e)) def download_gsfile(module, gs, bucket, obj, dest): try: bucket = gs.lookup(bucket) key = bucket.lookup(obj) key.get_contents_to_filename(dest) module.exit_json(msg="GET operation complete", changed=True) except gs.provider.storage_copy_error as e: module.fail_json(msg= str(e)) def download_gsstr(module, gs, bucket, obj): try: bucket = gs.lookup(bucket) key = bucket.lookup(obj) contents = key.get_contents_as_string() module.exit_json(msg="GET operation complete", contents=contents, changed=True) except gs.provider.storage_copy_error as e: module.fail_json(msg= str(e)) def get_download_url(module, gs, bucket, obj, expiry): try: bucket = gs.lookup(bucket) key = bucket.lookup(obj) url = key.generate_url(expiry) module.exit_json(msg="Download url:", url=url, expiration=expiry, changed=True) except gs.provider.storage_response_error as e: module.fail_json(msg= str(e)) def handle_get(module, gs, bucket, obj, overwrite, dest): md5_remote = keysum(module, gs, bucket, obj) md5_local = module.md5(dest) if md5_local == md5_remote: module.exit_json(changed=False) if md5_local != md5_remote and not overwrite: module.exit_json(msg="WARNING: Checksums do not match. Use overwrite parameter to force download.", failed=True) else: download_gsfile(module, gs, bucket, obj, dest) def handle_put(module, gs, bucket, obj, overwrite, src, expiration): # Lets check to see if bucket exists to get ground truth. bucket_rc = bucket_check(module, gs, bucket) key_rc = key_check(module, gs, bucket, obj) # Lets check key state. Does it exist and if it does, compute the etag md5sum. if bucket_rc and key_rc: md5_remote = keysum(module, gs, bucket, obj) md5_local = module.md5(src) if md5_local == md5_remote: module.exit_json(msg="Local and remote object are identical", changed=False) if md5_local != md5_remote and not overwrite: module.exit_json(msg="WARNING: Checksums do not match. Use overwrite parameter to force upload.", failed=True) else: upload_gsfile(module, gs, bucket, obj, src, expiration) if not bucket_rc: create_bucket(module, gs, bucket) upload_gsfile(module, gs, bucket, obj, src, expiration) # If bucket exists but key doesn't, just upload. if bucket_rc and not key_rc: upload_gsfile(module, gs, bucket, obj, src, expiration) def handle_delete(module, gs, bucket, obj): if bucket and not obj: if bucket_check(module, gs, bucket): module.exit_json(msg="Bucket %s and all keys have been deleted."%bucket, changed=delete_bucket(module, gs, bucket)) else: module.exit_json(msg="Bucket does not exist.", changed=False) if bucket and obj: if bucket_check(module, gs, bucket): if key_check(module, gs, bucket, obj): module.exit_json(msg="Object has been deleted.", changed=delete_key(module, gs, bucket, obj)) else: module.exit_json(msg="Object does not exists.", changed=False) else: module.exit_json(msg="Bucket does not exist.", changed=False) else: module.fail_json(msg="Bucket or Bucket & object parameter is required.", failed=True) def handle_create(module, gs, bucket, obj): if bucket and not obj: if bucket_check(module, gs, bucket): module.exit_json(msg="Bucket already exists.", changed=False) else: module.exit_json(msg="Bucket created successfully", changed=create_bucket(module, gs, bucket)) if bucket and obj: if obj.endswith('/'): dirobj = obj else: dirobj = obj + "/" if bucket_check(module, gs, bucket): if key_check(module, gs, bucket, dirobj): module.exit_json(msg="Bucket %s and key %s already exists."% (bucket, obj), changed=False) else: create_dirkey(module, gs, bucket, dirobj) else: create_bucket(module, gs, bucket) create_dirkey(module, gs, bucket, dirobj) def main(): module = AnsibleModule( argument_spec = dict( bucket = dict(required=True), object = dict(default=None, type='path'), src = dict(default=None), dest = dict(default=None, type='path'), expiration = dict(type='int', default=600, aliases=['expiry']), mode = dict(choices=['get', 'put', 'delete', 'create', 'get_url', 'get_str'], required=True), permission = dict(choices=['private', 'public-read', 'authenticated-read'], default='private'), headers = dict(type='dict', default={}), gs_secret_key = dict(no_log=True, required=True), gs_access_key = dict(required=True), overwrite = dict(default=True, type='bool', aliases=['force']), ), ) if not HAS_BOTO: module.fail_json(msg='boto 2.9+ required for this module') bucket = module.params.get('bucket') obj = module.params.get('object') src = module.params.get('src') dest = module.params.get('dest') mode = module.params.get('mode') expiry = module.params.get('expiration') gs_secret_key = module.params.get('gs_secret_key') gs_access_key = module.params.get('gs_access_key') overwrite = module.params.get('overwrite') if mode == 'put': if not src or not object: module.fail_json(msg="When using PUT, src, bucket, object are mandatory parameters") if mode == 'get': if not dest or not object: module.fail_json(msg="When using GET, dest, bucket, object are mandatory parameters") try: gs = boto.connect_gs(gs_access_key, gs_secret_key) except boto.exception.NoAuthHandlerFound as e: module.fail_json(msg = str(e)) if mode == 'get': if not bucket_check(module, gs, bucket) or not key_check(module, gs, bucket, obj): module.fail_json(msg="Target bucket/key cannot be found", failed=True) if not path_check(dest): download_gsfile(module, gs, bucket, obj, dest) else: handle_get(module, gs, bucket, obj, overwrite, dest) if mode == 'put': if not path_check(src): module.fail_json(msg="Local object for PUT does not exist", failed=True) handle_put(module, gs, bucket, obj, overwrite, src, expiry) # Support for deleting an object if we have both params. if mode == 'delete': handle_delete(module, gs, bucket, obj) if mode == 'create': handle_create(module, gs, bucket, obj) if mode == 'get_url': if bucket and obj: if bucket_check(module, gs, bucket) and key_check(module, gs, bucket, obj): get_download_url(module, gs, bucket, obj, expiry) else: module.fail_json(msg="Key/Bucket does not exist", failed=True) else: module.fail_json(msg="Bucket and Object parameters must be set", failed=True) # --------------------------- Get the String contents of an Object ------------------------- if mode == 'get_str': if bucket and obj: if bucket_check(module, gs, bucket) and key_check(module, gs, bucket, obj): download_gsstr(module, gs, bucket, obj) else: module.fail_json(msg="Key/Bucket does not exist", failed=True) else: module.fail_json(msg="Bucket and Object parameters must be set", failed=True) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
codeaudit/fuel
fuel/datasets/text.py
21
4353
from picklable_itertools import iter_, chain from fuel.datasets import Dataset class TextFile(Dataset): r"""Reads text files and numberizes them given a dictionary. Parameters ---------- files : list of str The names of the files in order which they should be read. Each file is expected to have a sentence per line. dictionary : str or dict Either the path to a Pickled dictionary mapping tokens to integers, or the dictionary itself. At the very least this dictionary must map the unknown word-token to an integer. bos_token : str or None, optional The beginning-of-sentence (BOS) token in the dictionary that denotes the beginning of a sentence. Is ``<S>`` by default. If passed ``None`` no beginning of sentence markers will be added. eos_token : str or None, optional The end-of-sentence (EOS) token is ``</S>`` by default, see ``bos_taken``. unk_token : str, optional The token in the dictionary to fall back on when a token could not be found in the dictionary. level : 'word' or 'character', optional If 'word' the dictionary is expected to contain full words. The sentences in the text file will be split at the spaces, and each word replaced with its number as given by the dictionary, resulting in each example being a single list of numbers. If 'character' the dictionary is expected to contain single letters as keys. A single example will be a list of character numbers, starting with the first non-whitespace character and finishing with the last one. preprocess : function, optional A function which takes a sentence (string) as an input and returns a modified string. For example ``str.lower`` in order to lowercase the sentence before numberizing. Examples -------- >>> with open('sentences.txt', 'w') as f: ... _ = f.write("This is a sentence\n") ... _ = f.write("This another one") >>> dictionary = {'<UNK>': 0, '</S>': 1, 'this': 2, 'a': 3, 'one': 4} >>> def lower(s): ... return s.lower() >>> text_data = TextFile(files=['sentences.txt'], ... dictionary=dictionary, bos_token=None, ... preprocess=lower) >>> from fuel.streams import DataStream >>> for data in DataStream(text_data).get_epoch_iterator(): ... print(data) ([2, 0, 3, 0, 1],) ([2, 0, 4, 1],) .. doctest:: :hide: >>> import os >>> os.remove('sentences.txt') """ provides_sources = ('features',) example_iteration_scheme = None def __init__(self, files, dictionary, bos_token='<S>', eos_token='</S>', unk_token='<UNK>', level='word', preprocess=None): self.files = files self.dictionary = dictionary if bos_token is not None and bos_token not in dictionary: raise ValueError self.bos_token = bos_token if eos_token is not None and eos_token not in dictionary: raise ValueError self.eos_token = eos_token if unk_token not in dictionary: raise ValueError self.unk_token = unk_token if level not in ('word', 'character'): raise ValueError self.level = level self.preprocess = preprocess super(TextFile, self).__init__() def open(self): return chain(*[iter_(open(f)) for f in self.files]) def get_data(self, state=None, request=None): if request is not None: raise ValueError sentence = next(state) if self.preprocess is not None: sentence = self.preprocess(sentence) data = [self.dictionary[self.bos_token]] if self.bos_token else [] if self.level == 'word': data.extend(self.dictionary.get(word, self.dictionary[self.unk_token]) for word in sentence.split()) else: data.extend(self.dictionary.get(char, self.dictionary[self.unk_token]) for char in sentence.strip()) if self.eos_token: data.append(self.dictionary[self.eos_token]) return (data,)
mit
ProjectSWGCore/NGECore2
scripts/mobiles/naboo/fambaa.py
2
1669
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobileTemplate.setCreatureName('fambaa') mobileTemplate.setLevel(22) mobileTemplate.setDifficulty(Difficulty.NORMAL) mobileTemplate.setMinSpawnDistance(4) mobileTemplate.setMaxSpawnDistance(8) mobileTemplate.setDeathblow(False) mobileTemplate.setScale(1) mobileTemplate.setMeatType("Reptile Meat") mobileTemplate.setMeatAmount(1250) mobileTemplate.setHideType("Leathery Hide") mobileTemplate.setHideAmount(325) mobileTemplate.setBoneType("Animal Bones") mobileTemplate.setBoneAmount(675) mobileTemplate.setSocialGroup("self") mobileTemplate.setAssistRange(20) mobileTemplate.setStalker(False) mobileTemplate.setOptionsBitmask(Options.ATTACKABLE) templates = Vector() templates.add('object/mobile/shared_fambaa.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() attacks.add('bm_dampen_pain_2') attacks.add('bm_shaken_2') attacks.add('bm_stomp_2') mobileTemplate.setDefaultAttack('creatureMeleeAttack') mobileTemplate.setAttacks(attacks) core.spawnService.addMobileTemplate('fambaa', mobileTemplate) return
lgpl-3.0
mstriemer/olympia
src/olympia/bandwagon/views.py
3
22490
import functools import hashlib import os from django import http from django.core.cache import cache from django.core.exceptions import PermissionDenied from django.db.models import Q from django.db.transaction import non_atomic_requests from django.shortcuts import get_object_or_404, redirect from django.views.decorators.http import require_POST from django.views.decorators.csrf import csrf_protect from django.utils.translation import ugettext_lazy as _lazy, ugettext as _ import caching.base as caching import commonware.log from django_statsd.clients import statsd from olympia import amo from olympia.amo import messages from olympia.amo.decorators import ( allow_mine, json_view, login_required, post_required, restricted_content, write) from olympia.amo.urlresolvers import reverse from olympia.amo.utils import paginate, urlparams, render from olympia.access import acl from olympia.accounts.utils import redirect_for_login from olympia.addons.models import Addon from olympia.addons.views import BaseFilter from olympia.legacy_api.utils import addon_to_dict from olympia.tags.models import Tag from olympia.translations.query import order_by_translation from olympia.users.models import UserProfile from .models import ( Collection, CollectionAddon, CollectionWatcher, CollectionVote, SPECIAL_SLUGS) from . import forms, tasks log = commonware.log.getLogger('z.collections') @non_atomic_requests def get_collection(request, username, slug): if (slug in SPECIAL_SLUGS.values() and request.user.is_authenticated() and request.user.username == username): return getattr(request.user, slug + '_collection')() else: return get_object_or_404(Collection.objects, author__username=username, slug=slug) def owner_required(f=None, require_owner=True): """Requires collection to be owned, by someone.""" def decorator(func): @functools.wraps(func) def wrapper(request, username, slug, *args, **kw): collection = get_collection(request, username, slug) if acl.check_collection_ownership(request, collection, require_owner=require_owner): return func(request, collection, username, slug, *args, **kw) else: raise PermissionDenied return wrapper return decorator(f) if f else decorator @non_atomic_requests def legacy_redirect(request, uuid, edit=False): # Nicknames have a limit of 30, so len == 36 implies a uuid. key = 'uuid' if len(uuid) == 36 else 'nickname' collection = get_object_or_404(Collection.objects, **{key: uuid}) if edit: return http.HttpResponseRedirect(collection.edit_url()) to = collection.get_url_path() + '?' + request.GET.urlencode() return http.HttpResponseRedirect(to) @non_atomic_requests def legacy_directory_redirects(request, page): sorts = {'editors_picks': 'featured', 'popular': 'popular', 'users': 'followers'} loc = base = reverse('collections.list') if page in sorts: loc = urlparams(base, sort=sorts[page]) elif request.user.is_authenticated(): if page == 'mine': loc = reverse('collections.user', args=[request.user.username]) elif page == 'favorites': loc = reverse('collections.following') return http.HttpResponseRedirect(loc) class CollectionFilter(BaseFilter): opts = (('featured', _lazy(u'Featured')), ('followers', _lazy(u'Most Followers')), ('created', _lazy(u'Newest'))) extras = (('name', _lazy(u'Name')), ('updated', _lazy(u'Recently Updated')), ('popular', _lazy(u'Recently Popular'))) def filter_featured(self): return self.base_queryset.filter(type=amo.COLLECTION_FEATURED) def filter_followers(self): return self.base_queryset.order_by('-subscribers') def filter_popular(self): return self.base_queryset.order_by('-weekly_subscribers') def filter_updated(self): return self.base_queryset.order_by('-modified') def filter_created(self): return self.base_queryset.order_by('-created') def filter_name(self): return order_by_translation(self.base_queryset, 'name') def get_filter(request, base=None): if base is None: base = Collection.objects.listed() base = (base.filter(Q(application=request.APP.id) | Q(application=None)) .exclude(addon_count=0)) return CollectionFilter(request, base, key='sort', default='featured') @non_atomic_requests def render_cat(request, template, data=None, extra=None): if extra is None: extra = {} if data is None: data = {} data.update(dict(search_cat='collections')) return render(request, template, data, **extra) # TODO (potch): restore this when we do mobile bandwagon # @mobile_template('bandwagon/{mobile/}collection_listing.html') @non_atomic_requests def collection_listing(request, base=None): sort = request.GET.get('sort') # We turn users into followers. if sort == 'users': return redirect(urlparams(reverse('collections.list'), sort='followers'), permanent=True) filter = get_filter(request, base) # Counts are hard to cache automatically, and accuracy for this # one is less important. Remember it for 5 minutes. countkey = hashlib.md5(str(filter.qs.query) + '_count').hexdigest() count = cache.get(countkey) if count is None: count = filter.qs.count() cache.set(countkey, count, 300) collections = paginate(request, filter.qs, count=count) return render_cat(request, 'bandwagon/impala/collection_listing.html', dict(collections=collections, src='co-hc-sidebar', dl_src='co-dp-sidebar', filter=filter, sort=sort, sorting=filter.field)) def get_votes(request, collections): if not request.user.is_authenticated(): return {} q = CollectionVote.objects.filter( user=request.user, collection__in=[c.id for c in collections]) return dict((v.collection_id, v) for v in q) @allow_mine @non_atomic_requests def user_listing(request, username): author = get_object_or_404(UserProfile, username=username) qs = (Collection.objects.filter(author__username=username) .order_by('-created')) mine = (request.user.is_authenticated() and request.user.username == username) if mine: page = 'mine' else: page = 'user' qs = qs.filter(listed=True) collections = paginate(request, qs) votes = get_votes(request, collections.object_list) return render_cat(request, 'bandwagon/user_listing.html', dict(collections=collections, collection_votes=votes, page=page, author=author, filter=get_filter(request))) class CollectionAddonFilter(BaseFilter): opts = (('added', _lazy(u'Added')), ('popular', _lazy(u'Popularity')), ('name', _lazy(u'Name'))) def filter_added(self): return self.base_queryset.order_by('collectionaddon__created') def filter_name(self): return order_by_translation(self.base_queryset, 'name') def filter_popular(self): return self.base_queryset.order_by('-weekly_downloads') @allow_mine @non_atomic_requests def collection_detail(request, username, slug): collection = get_collection(request, username, slug) if not collection.listed: if not request.user.is_authenticated(): return redirect_for_login(request) if not acl.check_collection_ownership(request, collection): raise PermissionDenied if request.GET.get('format') == 'rss': return http.HttpResponsePermanentRedirect(collection.feed_url()) base = Addon.objects.valid() & collection.addons.all() filter = CollectionAddonFilter(request, base, key='sort', default='popular') notes = get_notes(collection) # Go directly to CollectionAddon for the count to avoid joins. count = CollectionAddon.objects.filter( Addon.objects.all().valid_q( amo.VALID_ADDON_STATUSES, prefix='addon__'), collection=collection.id) addons = paginate(request, filter.qs, per_page=15, count=count.count()) # The add-on query is not related to the collection, so we need to manually # hook them up for invalidation. Bonus: count invalidation. keys = [addons.object_list.flush_key(), count.flush_key()] caching.invalidator.add_to_flush_list({collection.flush_key(): keys}) if collection.author_id: qs = Collection.objects.listed().filter(author=collection.author) others = amo.utils.randslice(qs, limit=4, exclude=collection.id) else: others = [] # `perms` is defined in django.contrib.auth.context_processors. Gotcha! user_perms = { 'view_stats': acl.check_ownership( request, collection, require_owner=False), } tags = Tag.objects.filter( id__in=collection.top_tags) if collection.top_tags else [] return render_cat(request, 'bandwagon/collection_detail.html', {'collection': collection, 'filter': filter, 'addons': addons, 'notes': notes, 'author_collections': others, 'tags': tags, 'user_perms': user_perms}) @json_view(has_trans=True) @allow_mine @non_atomic_requests def collection_detail_json(request, username, slug): collection = get_collection(request, username, slug) if not (collection.listed or acl.check_collection_ownership( request, collection)): raise PermissionDenied # We evaluate the QuerySet with `list` to work around bug 866454. addons_dict = [addon_to_dict(a) for a in list(collection.addons.valid())] return { 'name': collection.name, 'url': collection.get_abs_url(), 'iconUrl': collection.icon_url, 'addons': addons_dict } def get_notes(collection, raw=False): # This might hurt in a big collection with lots of notes. # It's a generator so we don't evaluate anything by default. notes = CollectionAddon.objects.filter(collection=collection, comments__isnull=False) rv = {} for note in notes: # Watch out for comments in a language we didn't pick up. if note.comments: rv[note.addon_id] = (note.comments.localized_string if raw else note.comments) yield rv @write @login_required def collection_vote(request, username, slug, direction): collection = get_collection(request, username, slug) if request.method != 'POST': return http.HttpResponseRedirect(collection.get_url_path()) vote = {'up': 1, 'down': -1}[direction] qs = (CollectionVote.objects.using('default') .filter(collection=collection, user=request.user)) if qs: cv = qs[0] if vote == cv.vote: # Double vote => cancel. cv.delete() else: cv.vote = vote cv.save(force_update=True) else: CollectionVote.objects.create(collection=collection, user=request.user, vote=vote) if request.is_ajax(): return http.HttpResponse() else: return http.HttpResponseRedirect(collection.get_url_path()) def initial_data_from_request(request): return dict(author=request.user, application=request.APP.id) def collection_message(request, collection, option): if option == 'add': title = _('Collection created!') msg = _( 'Your new collection is shown below. You can ' '<a href="%(url)s">edit additional settings</a> if you\'d ' 'like.' ) % {'url': collection.edit_url()} elif option == 'update': title = _('Collection updated!') msg = _( '<a href="%(url)s">View your collection</a> to see the changes.' ) % {'url': collection.get_url_path()} else: raise ValueError('Incorrect option "%s", ' 'takes only "add" or "update".' % option) messages.success(request, title, msg, message_safe=True) @write @login_required @restricted_content def add(request): """Displays/processes a form to create a collection.""" data = {} if request.method == 'POST': form = forms.CollectionForm( request.POST, request.FILES, initial=initial_data_from_request(request)) aform = forms.AddonsForm(request.POST) if form.is_valid(): collection = form.save(default_locale=request.LANG) collection.save() if aform.is_valid(): aform.save(collection) collection_message(request, collection, 'add') statsd.incr('collections.created') log.info('Created collection %s' % collection.id) return http.HttpResponseRedirect(collection.get_url_path()) else: data['addons'] = Addon.objects.filter(pk__in=aform.clean_addon()) data['comments'] = aform.clean_addon_comment() else: form = forms.CollectionForm() data.update(form=form, filter=get_filter(request)) return render_cat(request, 'bandwagon/add.html', data) @write @login_required(redirect=False) def ajax_new(request): form = forms.CollectionForm( request.POST or None, initial={'author': request.user, 'application': request.APP.id}, ) if request.method == 'POST' and form.is_valid(): collection = form.save() addon_id = request.REQUEST['addon_id'] collection.add_addon(Addon.objects.get(pk=addon_id)) log.info('Created collection %s' % collection.id) return http.HttpResponseRedirect(reverse('collections.ajax_list') + '?addon_id=%s' % addon_id) return render(request, 'bandwagon/ajax_new.html', {'form': form}) @login_required(redirect=False) @non_atomic_requests def ajax_list(request): try: addon_id = int(request.GET['addon_id']) except (KeyError, ValueError): return http.HttpResponseBadRequest() collections = ( Collection.objects .publishable_by(request.user) .with_has_addon(addon_id)) return render(request, 'bandwagon/ajax_list.html', {'collections': collections}) @write @login_required @post_required def collection_alter(request, username, slug, action): collection = get_collection(request, username, slug) return change_addon(request, collection, action) def change_addon(request, collection, action): if not acl.check_collection_ownership(request, collection): raise PermissionDenied try: addon = get_object_or_404(Addon.objects, pk=request.POST['addon_id']) except (ValueError, KeyError): return http.HttpResponseBadRequest() getattr(collection, action + '_addon')(addon) log.info(u'%s: %s %s to collection %s' % (request.user, action, addon.id, collection.id)) if request.is_ajax(): url = '%s?addon_id=%s' % (reverse('collections.ajax_list'), addon.id) else: url = collection.get_url_path() return http.HttpResponseRedirect(url) @write @login_required @post_required def ajax_collection_alter(request, action): try: collection = get_object_or_404( Collection.objects, pk=request.POST['id']) except (ValueError, KeyError): return http.HttpResponseBadRequest() return change_addon(request, collection, action) @write @login_required # Contributors are allowed to *see* the page, but there is another # permission check below to prevent them from doing any modifications. @owner_required(require_owner=False) def edit(request, collection, username, slug): is_admin = acl.action_allowed(request, 'Collections', 'Edit') if not acl.check_collection_ownership( request, collection, require_owner=True): if request.method == 'POST': raise PermissionDenied form = None elif request.method == 'POST': initial = initial_data_from_request(request) if collection.author_id: # Don't try to change the author. initial['author'] = collection.author form = forms.CollectionForm(request.POST, request.FILES, initial=initial, instance=collection) if form.is_valid(): collection = form.save() collection_message(request, collection, 'update') log.info(u'%s edited collection %s' % (request.user, collection.id)) return http.HttpResponseRedirect(collection.edit_url()) else: form = forms.CollectionForm(instance=collection) qs = (CollectionAddon.objects.no_cache().using('default') .filter(collection=collection)) meta = dict((c.addon_id, c) for c in qs) addons = collection.addons.no_cache().all() comments = get_notes(collection, raw=True).next() if is_admin: initial = dict(type=collection.type, application=collection.application) admin_form = forms.AdminForm(initial=initial) else: admin_form = None data = dict(collection=collection, form=form, username=username, slug=slug, meta=meta, filter=get_filter(request), is_admin=is_admin, admin_form=admin_form, addons=addons, comments=comments) return render_cat(request, 'bandwagon/edit.html', data) @write @login_required @owner_required(require_owner=False) @post_required def edit_addons(request, collection, username, slug): if request.method == 'POST': form = forms.AddonsForm(request.POST) if form.is_valid(): form.save(collection) collection_message(request, collection, 'update') log.info(u'%s added add-ons to %s' % (request.user, collection.id)) return http.HttpResponseRedirect(collection.edit_url() + '#addons-edit') @write @login_required @owner_required @post_required def edit_contributors(request, collection, username, slug): is_admin = acl.action_allowed(request, 'Collections', 'Edit') if is_admin: admin_form = forms.AdminForm(request.POST) if admin_form.is_valid(): admin_form.save(collection) form = forms.ContributorsForm(request.POST) if form.is_valid(): form.save(collection) collection_message(request, collection, 'update') if form.cleaned_data['new_owner']: return http.HttpResponseRedirect(collection.get_url_path()) return http.HttpResponseRedirect(collection.edit_url() + '#users-edit') @write @login_required @owner_required @post_required def edit_privacy(request, collection, username, slug): collection.listed = not collection.listed collection.save() log.info(u'%s changed privacy on collection %s' % (request.user, collection.id)) return http.HttpResponseRedirect(collection.get_url_path()) @write @login_required def delete(request, username, slug): collection = get_object_or_404(Collection, author__username=username, slug=slug) if not acl.check_collection_ownership(request, collection, True): log.info(u'%s is trying to delete collection %s' % (request.user, collection.id)) raise PermissionDenied data = dict(collection=collection, username=username, slug=slug) if request.method == 'POST': if request.POST['sure'] == '1': collection.delete() log.info(u'%s deleted collection %s' % (request.user, collection.id)) url = reverse('collections.user', args=[username]) return http.HttpResponseRedirect(url) else: return http.HttpResponseRedirect(collection.get_url_path()) return render_cat(request, 'bandwagon/delete.html', data) @require_POST @write @login_required @owner_required @json_view @csrf_protect def delete_icon(request, collection, username, slug): log.debug(u"User deleted collection (%s) icon " % slug) tasks.delete_icon(os.path.join(collection.get_img_dir(), '%d.png' % collection.id)) collection.icontype = '' collection.save() if request.is_ajax(): return {'icon': collection.icon_url} else: messages.success(request, _('Icon Deleted')) return http.HttpResponseRedirect(collection.edit_url()) @login_required @post_required @json_view def watch(request, username, slug): """ POST /collections/:user/:slug/watch to toggle the user's watching status. For ajax, return {watching: true|false}. (reflects the new value) Otherwise, redirect to the collection page. """ collection = get_collection(request, username, slug) d = dict(user=request.user, collection=collection) qs = CollectionWatcher.objects.no_cache().using('default').filter(**d) watching = not qs # Flip the bool since we're about to change it. if qs: qs.delete() else: CollectionWatcher.objects.create(**d) if request.is_ajax(): return {'watching': watching} else: return http.HttpResponseRedirect(collection.get_url_path()) @login_required @non_atomic_requests def following(request): qs = (Collection.objects.filter(following__user=request.user) .order_by('-following__created')) collections = paginate(request, qs) votes = get_votes(request, collections.object_list) return render_cat(request, 'bandwagon/user_listing.html', dict(collections=collections, votes=votes, page='following', filter=get_filter(request))) @login_required @allow_mine @non_atomic_requests def mine(request, username=None, slug=None): if slug is None: return user_listing(request, username) else: return collection_detail(request, username, slug)
bsd-3-clause
biocore/qiime
qiime/simsam.py
15
11761
#!/usr/bin/env python # File created on 19 Mar 2011 from __future__ import division __author__ = "Justin Kuczynski" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["Justin Kuczynski", "Rob Knight", "Jai Ram Rideout", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Justin Kuczynski" __email__ = "justinak@gmail.com" from os.path import join from operator import add from datetime import datetime from random import choice from numpy import zeros from biom.table import Table from qiime.format import format_mapping_file from qiime.parse import parse_mapping_file from qiime.util import (make_option, create_dir, parse_command_line_parameters, write_biom_table, get_generated_by_for_biom_tables) from qiime.sort import natsort def sim_otu_table(sample_ids, otu_ids, samples, otu_metadata, tree, num_replicates, dissimilarity): """ make n samples related to each sample in an input otu table input: the constituents of an otu table * sample_ids: list * otu_ids: list * samples: iterable, each element must have sample_vector = elem[0] where sample_vector looks like [1,0,7,9...] * otu_metadata: list, either empty or of length len(otu_ids) tree: a PhyloNode tree or compatible, num_replicates: how many replicates for each input sample dissimilarity: how phylogenetically dissimilar each replicate should be relative to the original output is a tuple with the constituents of an otu table, possibly missing some otu metadata: (res_sam_names, res_otus, res_otu_mtx, res_otu_metadata) """ # hold sample abundance vector in a dict (sample_dict) temporarily # format of sample_dict: otu_id: num_seqs sample_dicts = [] res_sam_names = [] for i, sample_info in enumerate(samples): sample_vector = sample_info[0] # sample_vector = otu_observations.next() for j in range(num_replicates): sample_dict = {} for k in range(len(otu_ids)): otu_abundance = sample_vector[k] if otu_abundance == 0: continue new_otu_id = get_new_otu_id(otu_ids[k], tree, dissimilarity) # beware, get_new_otu_id may return something we already # have in the table if new_otu_id in sample_dict: sample_dict[new_otu_id] += otu_abundance else: sample_dict[new_otu_id] = otu_abundance sample_dicts.append(sample_dict) res_sam_names.append(sample_ids[i] + '.' + str(j)) res_otu_mtx, res_otus = combine_sample_dicts(sample_dicts) res_otu_metadata = [] if otu_metadata is None or otu_metadata == []: res_otu_metadata = None else: for otu_id in res_otus: # if otu was in original table, just copy its metadata try: res_otu_metadata.append(otu_metadata[otu_ids.index(otu_id)]) except ValueError: # else just append None since we don't have its metadata res_otu_metadata.append(None) return res_sam_names, res_otus, res_otu_mtx, res_otu_metadata def create_tip_index(tree): """Create a tip lookup index on the tree""" if hasattr(tree, '_tip_index'): return else: tree._tip_index = {n.Name: n for n in tree.tips()} def cache_tip_names(tree): """Cache tip names""" if hasattr(tree, '_tip_names'): return else: for n in tree.postorder(): if n.isTip(): n._tip_names = [n.Name] else: n._tip_names = reduce(add, [c._tip_names for c in n.Children]) def get_new_otu_id(old_otu_id, tree, dissim): """ simulates an otu switching to related one input a tipname, a tree, and a distance to walk up the tree ouputs the name of the new, randomly chosen, tree tip output tip name may be the same as """ create_tip_index(tree) cache_tip_names(tree) node = tree._tip_index[old_otu_id] distance_up_tree = 0 while (not node.isRoot()) and (distance_up_tree + node.Length < dissim): distance_up_tree += node.Length node = node.Parent # another option is to do 50-50 descending each node, # so we don't bias for overrepresented clades if node.isTip(): return node.Name else: return choice(node._tip_names) def combine_sample_dicts(sample_dicts): """ combines a list of sample_dicts into one otu table sample dicts is a list of dicts, each one {otu_id:num_seqs} output is a tuple: (otu_mtx (rows are otus), otu_ids (list)) * otu_mtx has samples in order of dicts, otus sorted with natsort / human sort * otu_mtx will have all otus mentioned as keys in sample_dicts, even if they are abundance 0 ({otu_id:0,...}) such otus will simply be rows of zeros """ all_otu_ids = [] for s in sample_dicts: all_otu_ids.extend(s.keys()) all_otu_ids = list(set(all_otu_ids)) all_otu_ids = natsort(all_otu_ids) # get index once now, for all samples, instead of all_otu_ids.index() indices = {} for i in range(len(all_otu_ids)): indices[all_otu_ids[i]] = i otu_mtx = zeros((len(all_otu_ids), len(sample_dicts)), int) # otus (rows) by samples (cols) for i, sample_dict in enumerate(sample_dicts): for otu, abund in sample_dict.items(): otu_mtx[indices[otu], i] = abund return otu_mtx, all_otu_ids def create_replicated_mapping_file(map_f, num_replicates, sample_ids): """Returns a formatted mapping file with replicated sample IDs. Each sample ID will have an ascending integer appended to it from the range [0, num_replicates - 1]. For example, if there are two input sample IDs, S1 and S2, with 3 replicates each, the output will be: S1.0 S1.1 S1.2 S2.0 S2.1 S2.2 All other metadata columns will simply be copied to the output mapping file. The order of input sample IDs is preserved. Arguments: map_f - input mapping file to replicate (file-like object) num_replicates - number of replicates at each sample sample_ids - only sample IDs in the mapping file that are in this list will be replicated. Sample IDs in the mapping file that are not found in this list will not be added to the resulting mapping file """ if num_replicates < 1: raise ValueError("Must specify at least one sample replicate (was " "provided %d)." % num_replicates) map_data, header, comments = parse_mapping_file(map_f) rep_map_data = [] for row in map_data: if row[0] in sample_ids: for rep_num in range(num_replicates): rep_map_data.append(['%s.%i' % (row[0], rep_num)] + row[1:]) return format_mapping_file(header, rep_map_data, comments) def simsam_range(table, tree, simulated_sample_sizes, dissimilarities, mapping_f=None): """Applies sim_otu_table over a range of parameters table: the input table to simulate samples from tree: tree related OTUs in input table simulated_sample_sizes: a list of ints defining how many output samples should be create per input sample dissimilarities: a list of floats containing the dissimilarities to use in simulating tables mapping_f: file handle for metadata mapping file, if a mapping file should be created with the samples from each simulated table This function will yield tuples with the following form: (output table, output mapping lines, simulated_sample_size, dissimilarity) If the user does not provide mapping_f, the tuples will look like: (output table, None, simulated_sample_size, dissimilarity) """ if mapping_f is not None: # if the user provided a mapping file, load it into # a list for repeated use, and define the function for # processing the mapping file mapping_lines = list(mapping_f) process_map = create_replicated_mapping_file else: # otherwise create a dummy function for processing the # mapping file so we don't have to check whether it # exists on every iteration mapping_lines = None def process_map(mapping_lines, simulated_sample_size, sample_ids): return None for simulated_sample_size in simulated_sample_sizes: # create the output mapping file data output_mapping_lines = \ process_map(mapping_lines, simulated_sample_size, table.ids()) for dissimilarity in dissimilarities: # create the simulated otu table output_sample_ids, output_otu_ids, output_data, output_metadata = \ sim_otu_table(table.ids(), table.ids(axis='observation').tolist(), table.iter(), table.metadata(axis='observation'), tree, simulated_sample_size, dissimilarity) output_table = Table( output_data, output_otu_ids, output_sample_ids, observation_metadata=output_metadata, generated_by=get_generated_by_for_biom_tables(), create_date=datetime.now().isoformat()) yield (output_table, output_mapping_lines, simulated_sample_size, dissimilarity) def simsam_range_to_files(table, tree, simulated_sample_sizes, dissimilarities, output_dir, mapping_f=None, output_table_basename="table", output_map_basename="map"): """Applies sim_otu_table over a range of parameters, writing output to file table: the input table to simulate samples from tree: tree related OTUs in input table simulated_sample_sizes: a list of ints defining how many output samples should be create per input sample dissimilarities: a list of floats containing the dissimilarities to use in simulating tables output_dir: the directory where all output tables and mapping files should be written mapping_f: file handle for metadata mapping file, if a mapping file should be created with the samples from each simulated table output_table_basename: basename for output table files (default: table) output_map_basename: basename for output mapping files (default: map) """ create_dir(output_dir) for e in simsam_range(table, tree, simulated_sample_sizes, dissimilarities, mapping_f): output_table = e[0] output_mapping_lines = e[1] simulated_sample_size = e[2] dissimilarity = e[3] output_table_fp = join(output_dir, '%s_n%d_d%r.biom' % (output_table_basename, simulated_sample_size, dissimilarity)) write_biom_table(output_table, output_table_fp) if output_mapping_lines is not None: output_map_fp = join(output_dir, '%s_n%d_d%r.txt' % (output_map_basename, simulated_sample_size, dissimilarity)) output_map_f = open(output_map_fp, 'w') output_map_f.write(''.join(output_mapping_lines)) output_map_f.close()
gpl-2.0
RainMark/SimpleMediaDownloader
src/core/Network.py
1
1071
#!/usr/bin/python3 import sys, os, logging from urllib import request, parse, error class Network(object): def __init__(self): # Dirty hack. major, minor, _, _, _ = sys.version_info if major == 3 and minor < 5: self.has_quote_plus = False else: self.has_quote_plus = True def network_check(func): def wrapper(*args, **kw): try: return func(*args, **kw) except error.HTTPError as e1: logging.warning(e1) except error.URLError as e2: logging.warning(e2) return wrapper @network_check def urlrequest(self, url): raw_data = request.urlopen(url).read() if not raw_data: return None return raw_data.decode('utf-8') def urlencode(self, param_dict): if self.has_quote_plus: encode_data = parse.urlencode(param_dict, quote_via = parse.quote_plus) else: encode_data = parse.urlencode(param_dict) return encode_data
mit
AyoubZahid/odoo
addons/google_calendar/res_config.py
42
1476
from openerp.osv import fields, osv class calendar_config_settings(osv.TransientModel): _inherit = 'base.config.settings' _columns = { 'google_cal_sync': fields.boolean("Show Tutorial"), 'cal_client_id': fields.char("Client_id"), 'cal_client_secret': fields.char("Client_key"), 'server_uri': fields.char('URI for tuto') } def set_calset(self,cr,uid,ids,context=None) : params = self.pool['ir.config_parameter'] myself = self.browse(cr,uid,ids[0],context=context) params.set_param(cr, uid, 'google_calendar_client_id', (myself.cal_client_id or '').strip(), groups=['base.group_system'], context=None) params.set_param(cr, uid, 'google_calendar_client_secret', (myself.cal_client_secret or '').strip(), groups=['base.group_system'], context=None) def get_default_all(self,cr,uid,ids,context=None): params = self.pool.get('ir.config_parameter') cal_client_id = params.get_param(cr, uid, 'google_calendar_client_id',default='',context=context) cal_client_secret = params.get_param(cr, uid, 'google_calendar_client_secret',default='',context=context) server_uri= "%s/google_account/authentication" % params.get_param(cr, uid, 'web.base.url',default="http://yourcompany.odoo.com",context=context) return dict(cal_client_id=cal_client_id,cal_client_secret=cal_client_secret,server_uri=server_uri)
gpl-3.0
paweljasinski/ironpython3
Tests/test_list.py
2
12648
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### from iptest.assert_util import * def test_extend_self(): l=['a','b','c'] l.extend(l) Assert(l==['a','b','c','a','b','c']) # verify repr and print have the same result for a recursive list @skip('silverlight') def test_append_self(): a = list('abc') a.append(a) AreEqual(str(a), "['a', 'b', 'c', [...]]") ## file from iptest.file_util import path_combine fn = path_combine(testpath.temporary_dir, "testfile.txt") fo = open(fn, "wb") a = list('abc') a.append(a) print >>fo, a, fo.close() fo = open(fn, "rb") Assert(fo.read() == repr(a)) fo.close() if is_cli or is_silverlight: import clr x = [1,2,3] y = [] xenum = iter(x) while xenum.MoveNext(): y.append(xenum.Current) AreEqual(x, y) def test_assign_to_empty(): # should all succeed y = [] [] = y [], t = y, 0 [[[]]] = [[y]] del y def test_unpack(): listOfSize2 = [1, 2] # Disallow unequal unpacking assignment def f1(): [a, b, c] = listOfSize2 def f2(): del a def f3(): [a] = listOfSize2 AssertError(ValueError, f1) AssertError(NameError, f2) AssertError(ValueError, f3) AssertError(NameError, f2) [a, [b, c]] = [listOfSize2, listOfSize2] AreEqual(a, listOfSize2) AreEqual(b, 1) AreEqual(c, 2) del a, b, c [[a, b], c] = (listOfSize2, listOfSize2) AreEqual(a, 1) AreEqual(b, 2) AreEqual(c, listOfSize2) del a, b, c def test_sort(): # named params passed to sort LExpected = ['A', 'b', 'c', 'D'] L = ['D', 'c', 'b', 'A'] L.sort(key=lambda x: x.lower()) Assert(L == LExpected) l = [1, 2, 3] l2 = l[:] l.sort(lambda x, y: x > y) AreEqual(l, l2) l.sort(lambda x, y: x > y) AreEqual(l, l2) def test_list_in_list(): aList = [['a']] anItem = ['a'] AreEqual( aList.index(anItem), 0 ) Assert(anItem in aList) def test_pop(): x = [1,2,3,4,5,6,7,8,9,0] Assert(x.pop() == 0) Assert(x.pop(3) == 4) Assert(x.pop(-5) == 5) Assert(x.pop(0) == 1) Assert(x.pop() == 9) Assert(x.pop(2) == 6) Assert(x.pop(3) == 8) Assert(x.pop(-1) == 7) Assert(x.pop(-2) == 2) Assert(x.pop() == 3) def test_add_mul(): x = [1,2,3] x += [4,5,6] Assert(x == [1,2,3,4,5,6]) x = [1,2,3] AreEqual(x * 2, [1,2,3,1,2,3]) AreEqual(2 * x, [1,2,3,1,2,3]) class mylong(long): pass AreEqual([1, 2] * mylong(2L), [1, 2, 1, 2]) AreEqual([3, 4].__mul__(mylong(2L)), [3, 4, 3, 4]) AreEqual([5, 6].__rmul__(mylong(2L)), [5, 6, 5, 6]) AreEqual(mylong(2L) * [7,8] , [7, 8, 7, 8]) AssertError(TypeError, lambda: [1,2] * [3,4]) AssertError(OverflowError, lambda: [1,2] * mylong(203958720984752098475023957209L)) def test_reverse(): x = ["begin",1,2,3,4,5,6,7,8,9,0,"end"] del x[6:] x.reverse() Assert(x == [5, 4, 3, 2, 1, "begin"]) x = list("iron python") x.reverse() Assert(x == ['n','o','h','t','y','p',' ','n','o','r','i']) # should return listreverseenumerator, not reversed Assert(type(reversed([2,3,4])) != reversed) def test_equal(): AreEqual([2,3] == '', False) AreEqual(list.__eq__([], None), NotImplemented) class MyEquality(object): def __eq__(self, other): return 'abc' class MyOldEquality(object): def __eq__(self, other): return 'def' AreEqual([] == MyEquality(), 'abc') AreEqual([] == MyOldEquality(), 'def') AreEqual([2,3] == (2,3), False) class MyIterable(object): def __iter__(self): return MyIterable() def next(self): yield 'a' yield 'b' AreEqual(['a', 'b'] == MyIterable(), False) def test_self_init(): a = [1, 2, 3] list.__init__(a, a) AreEqual(a, []) ###################################################################### # Verify behavior of index when the list changes... class clears(object): def __eq__(self, other): global hitCount hitCount = hitCount + 1 del a[:] return False class appends(object): def __eq__(self, other): global hitCount hitCount = hitCount + 1 a.append(self) return False a = [clears(), clears(),clears(),clears(),clears()] hitCount = 0 AssertError(ValueError, a.index, 23) AreEqual(hitCount, 1) # should stop after the first equality check a = [appends(), appends(), appends()] hitCount = 0 AssertError(ValueError, a.index, 2) AreEqual(hitCount, 3) # should have only checked existing items @runonly('cli') def test_pass_pythonlist_to_clr(): ## ## test passing pythonlist to clr where IList or ArrayList is requested ## also borrow this place to test passing python dict to clr where ## IDictionary or Hashtable is requested ## def contains_all_1s(x): '''check the return value are 11111 or similar''' if type(x) == tuple: x = x[0] s = str(x) AreEqual(s.count("1"), len(s)) def do_something(thetype, pl, cl, check_func): pt = thetype(pl) pt.AddRemove() ct = thetype(cl) ct.AddRemove() check_func() x = pt.Inspect() y = ct.Inspect() contains_all_1s(x) contains_all_1s(y) AreEqual(x, y) AreEqual(pt.Loop(), ct.Loop()) check_func() load_iron_python_test() import System import IronPythonTest # test ListWrapperForIList pl = range(40) cl = System.Collections.Generic.List[int]() for x in pl: cl.Add(x) def check_content(): for x, y in zip(cl, pl): AreEqual(x, y) do_something(IronPythonTest.UsePythonListAsList, pl, cl, check_content) # test DictWrapperForIDict pl = {"redmond" : 10, "seattle" : 20} cl = System.Collections.Generic.Dictionary[str, int]() for x, y in pl.iteritems(): cl.Add(x, y) pll = list(pl.iteritems()) cll = list(cl) pll.sort(lambda x, y: cmp(x[0], y[0])) cll.sort(lambda x, y: cmp(x.Key, y.Key)) def check_content(): for x, y in zip(cll, pll): AreEqual(x.Key, y[0]) AreEqual(x.Value, y[1]) do_something(IronPythonTest.UsePythonDictAsDictionary, pl, cl, check_content) def test_inplace_addition(): x = [2,3,4] x += x AreEqual(x, [2,3,4,2,3,4]) test_cases = [ ([], [], []), ([1], [], [1]), ([], [1], [1]), ([1], [1], [1, 1]), ([1], [2], [1, 2]), ([2], [1], [2, 1]), ([1, 2], [], [1, 2]), ([], [1, 2], [1, 2]), ([1, 2], [3], [1, 2, 3]), ([3], [1, 2], [3, 1, 2]), ([1, 2], [3, 4], [1, 2, 3, 4]), ([3, 4], [1, 2], [3, 4, 1, 2]), ([None], [], [None]), ([None], [2], [None, 2]), ([""], [], [""]), ] for left_operand, right_operand, result in test_cases: #(No access to copy.deepcopy in IP) # Create new list to verify no side effects to the RHS list orig_right = [x for x in right_operand] left_operand += right_operand AreEqual(left_operand, result) #Side effects... AreEqual(orig_right, right_operand) #interesting cases x = [None] x += xrange(3) AreEqual(x, [None, 0, 1, 2]) x = [None] x += (0, 1, 2) AreEqual(x, [None, 0, 1, 2]) x = [None] x += "012" AreEqual(x, [None, "0", "1", "2"]) x = [None] x += Exception() AreEqual(x, [None]) #negative cases neg_cases = [ ([], None), ([], 1), ([], 1L), ([], 3.14), ([], object), ([], object()), ] for left_operand, right_operand in neg_cases: try: left_operand += right_operand AssertUnreachable() except TypeError, e: pass def test_indexing(): l = [2,3,4] def set(x, i, v): x[i] = v AssertError(TypeError, lambda : l[2.0]) AssertError(TypeError, lambda : set(l, 2.0, 1)) class mylist(list): def __getitem__(self, index): return list.__getitem__(self, int(index)) def __setitem__(self, index, value): return list.__setitem__(self, int(index), value) l = mylist(l) AreEqual(l[2.0], 4) l[2.0] = 1 AreEqual(l[2], 1) def test_getslice(): """overriding __len__ doesn't get called when doing __getslice__""" class l(list): def __len__(self): raise Exception() x = l() AreEqual(x.__getslice__(-1, -200), []) class mylist(list): def __getslice__(self, i, j): return i, j class mylong(long): pass class myint(int): pass # all indexes to __getslice__ should be ints for listType in list, mylist: for input in [0, 1, False, True, myint(0), myint(1), mylong(0), mylong(1), -1, myint(-1), mylong(-1)]: for x in listType(range(5))[input:input]: AreEqual(type(x), int) def test_repr(): class mylist(list): def __repr__(self): return 'abc' AreEqual(repr(mylist()), 'abc') def test_index_multiply(): for data in ([1,2], (1,2), 'ab'): class M: def __rmul__(self, other): return 1 class Index(object): def __index__(self): return 2 class OldIndex: def __index__(self): return 2 AreEqual(data * M(), 1) AssertError(TypeError, lambda : data.__mul__(M())) AreEqual(data * Index(), data * 2) AreEqual(data * OldIndex(), data * 2) AreEqual(data.__mul__(Index()), data * 2) AreEqual(data.__mul__(OldIndex()), data * 2) AssertErrorWithMessage(TypeError, "'NoneType' object cannot be interpreted as an index", lambda : data.__mul__(None)) AssertError(TypeError, lambda : data * None) AssertError(TypeError, lambda : None * data) def test_sequence_assign(): tokens = [(chr(ord('a') + val), val) for val in range(0,10)] (first,pos),tokens = tokens[0], tokens[1:] AreEqual(first, 'a') AreEqual(pos, 0) AreEqual(tokens, [('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('h', 7), ('i', 8), ('j', 9)]) def test_inheritance(): listIter = type(iter([2,3,4])) reverseListIter = type(reversed([2,3,4])) for base in (listIter, reverseListIter): def subclass(): class x(base): pass AssertError(TypeError, subclass) def test_backwards_slicing_no_step(): class mylist(object): def __getitem__(self, index): return 'stuff'[index] a = list('stuff') for val in (a, 'stuff', tuple('stuff'), mylist()): a[1:0] = val AreEqual(a, list("stuff"[:1] + "stuff" + "stuff"[1:])) a = list('stuff') for val in (a, 'stuff', tuple('stuff'), mylist()): a[1:0:1] = a AreEqual(a, list("stuff"[:1] + "stuff" + "stuff"[1:])) a = list('stuff') def test_cp20125(): class Temp(list): def __init__(self, value): self.value = value def __mul__(self, other): return self.value * other t1 = Temp(3.0) AreEqual(t1 * 3.0, 9.0) #--MAIN------------------------------------------------------------------------ run_test(__name__)
apache-2.0
mmerce/python
bigml/tests/test_06_batch_predictions.py
1
15010
# -*- coding: utf-8 -*- # # Copyright 2015-2020 BigML # # 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. """ Creating batch predictions """ from .world import world, setup_module, teardown_module from . import create_source_steps as source_create from . import create_dataset_steps as dataset_create from . import create_model_steps as model_create from . import create_ensemble_steps as ensemble_create from . import create_cluster_steps as cluster_create from . import create_anomaly_steps as anomaly_create from . import create_batch_prediction_steps as batch_pred_create from . import create_prediction_steps as prediction_create class TestBatchPrediction(object): def setup(self): """ Debug information """ print("\n-------------------\nTests in: %s\n" % __name__) def teardown(self): """ Debug information """ print("\nEnd of tests in: %s\n-------------------\n" % __name__) def test_scenario1(self): """ Scenario: Successfully creating a batch prediction: Given I create a data source uploading a "<data>" file And I wait until the source is ready less than <time_1> secs And I create a dataset And I wait until the dataset is ready less than <time_2> secs And I create a model And I wait until the model is ready less than <time_3> secs When I create a batch prediction for the dataset with the model And I wait until the batch prediction is ready less than <time_4> secs And I download the created predictions file to "<local_file>" Then the batch prediction file is like "<predictions_file>" Examples: | data | time_1 | time_2 | time_3 | time_4 | local_file | predictions_file | | ../data/iris.csv | 30 | 30 | 50 | 50 | ./tmp/batch_predictions.csv |./data/batch_predictions.csv | """ print(self.test_scenario1.__doc__) examples = [ ['data/iris.csv', '30', '30', '50', '50', 'tmp/batch_predictions.csv', 'data/batch_predictions.csv']] for example in examples: print("\nTesting with:\n", example) source_create.i_upload_a_file(self, example[0]) source_create.the_source_is_finished(self, example[1]) dataset_create.i_create_a_dataset(self) dataset_create.the_dataset_is_finished_in_less_than(self, example[2]) model_create.i_create_a_model(self) model_create.the_model_is_finished_in_less_than(self, example[3]) batch_pred_create.i_create_a_batch_prediction(self) batch_pred_create.the_batch_prediction_is_finished_in_less_than(self, example[4]) batch_pred_create.i_download_predictions_file(self, example[5]) batch_pred_create.i_check_predictions(self, example[6]) def test_scenario2(self): """ Scenario: Successfully creating a batch prediction for an ensemble: Given I create a data source uploading a "<data>" file And I wait until the source is ready less than <time_1> secs And I create a dataset And I wait until the dataset is ready less than <time_2> secs And I create an ensemble of <number_of_models> models and <tlp> tlp And I wait until the ensemble is ready less than <time_3> secs When I create a batch prediction for the dataset with the ensemble and "<params>" And I wait until the batch prediction is ready less than <time_4> secs And I download the created predictions file to "<local_file>" Then the batch prediction file is like "<predictions_file>" Examples: | data | time_1 | time_2 | number_of_models | tlp | time_3 | time_4 | local_file | predictions_file | params | ../data/iris.csv | 30 | 30 | 5 | 1 | 80 | 50 | ./tmp/batch_predictions.csv | ./data/batch_predictions_e.csv | {"combiner": 0} """ print(self.test_scenario2.__doc__) examples = [ ['data/iris.csv', '30', '30', '5', '1', '180', '150', 'tmp/batch_predictions.csv', 'data/batch_predictions_e_c0.csv', {"combiner":0}], ['data/iris.csv', '30', '30', '5', '1', '180', '150', 'tmp/batch_predictions.csv', 'data/batch_predictions_e_c1.csv', {"combiner":1, "confidence": True}], ['data/iris.csv', '30', '30', '5', '1', '180', '150', 'tmp/batch_predictions.csv', 'data/batch_predictions_e_c2.csv', {"combiner":2, "confidence": True}], ['data/iris.csv', '30', '30', '5', '1', '180', '150', 'tmp/batch_predictions.csv', 'data/batch_predictions_e_o_k_v.csv', {"operating_kind": "votes", "confidence": True}], ['data/iris.csv', '30', '30', '5', '1', '180', '150', 'tmp/batch_predictions.csv', 'data/batch_predictions_e_o_k_p.csv', {"operating_kind": "probability", "probability": True}], ['data/iris.csv', '30', '30', '5', '1', '180', '150', 'tmp/batch_predictions.csv', 'data/batch_predictions_e_o_k_c.csv', {"operating_kind": "confidence", "confidence": True}]] for example in examples: print("\nTesting with:\n", example) source_create.i_upload_a_file(self, example[0]) source_create.the_source_is_finished(self, example[1]) dataset_create.i_create_a_dataset(self) dataset_create.the_dataset_is_finished_in_less_than(self, example[2]) ensemble_create.i_create_an_ensemble(self, example[3], example[4]) ensemble_create.the_ensemble_is_finished_in_less_than(self, example[5]) batch_pred_create.i_create_a_batch_prediction_ensemble(self, example[9]) batch_pred_create.the_batch_prediction_is_finished_in_less_than(self, example[6]) batch_pred_create.i_download_predictions_file(self, example[7]) batch_pred_create.i_check_predictions(self, example[8]) def test_scenario3(self): """ Scenario: Successfully creating a batch centroid from a cluster: Given I create a data source uploading a "<data>" file And I wait until the source is ready less than <time_1> secs And I create a dataset And I wait until the dataset is ready less than <time_2> secs And I create a cluster And I wait until the cluster is ready less than <time_3> secs When I create a batch centroid for the dataset And I check the batch centroid is ok And I wait until the batch centroid is ready less than <time_4> secs And I download the created centroid file to "<local_file>" Then the batch centroid file is like "<predictions_file>" Examples: | data | time_1 | time_2 | time_3 | time_4 | local_file | predictions_file | | ../data/diabetes.csv | 50 | 50 | 50 | 50 | ./tmp/batch_predictions.csv |./data/batch_predictions_c.csv | """ print(self.test_scenario3.__doc__) examples = [ ['data/diabetes.csv', '50', '50', '50', '50', 'tmp/batch_predictions.csv', 'data/batch_predictions_c.csv']] for example in examples: print("\nTesting with:\n", example) source_create.i_upload_a_file(self, example[0]) source_create.the_source_is_finished(self, example[1]) dataset_create.i_create_a_dataset(self) dataset_create.the_dataset_is_finished_in_less_than(self, example[2]) cluster_create.i_create_a_cluster(self) cluster_create.the_cluster_is_finished_in_less_than(self, example[3]) batch_pred_create.i_create_a_batch_prediction_with_cluster(self) batch_pred_create.the_batch_centroid_is_finished_in_less_than(self, example[4]) batch_pred_create.i_download_centroid_file(self, example[5]) batch_pred_create.i_check_predictions(self, example[6]) def test_scenario4(self): """ Scenario: Successfully creating a source from a batch prediction: Given I create a data source uploading a "<data>" file And I wait until the source is ready less than <time_1> secs And I create a dataset And I wait until the dataset is ready less than <time_2> secs And I create a model And I wait until the model is ready less than <time_3> secs When I create a batch prediction for the dataset with the model And I wait until the batch prediction is ready less than <time_4> secs Then I create a source from the batch prediction And I wait until the source is ready less than <time_1> secs Examples: | data | time_1 | time_2 | time_3 | time_4 | | ../data/iris.csv | 30 | 30 | 50 | 50 | """ print(self.test_scenario4.__doc__) examples = [ ['data/diabetes.csv', '30', '30', '50', '50']] for example in examples: print("\nTesting with:\n", example) source_create.i_upload_a_file(self, example[0]) source_create.the_source_is_finished(self, example[1]) dataset_create.i_create_a_dataset(self) dataset_create.the_dataset_is_finished_in_less_than(self, example[2]) model_create.i_create_a_model(self) model_create.the_model_is_finished_in_less_than(self, example[3]) batch_pred_create.i_create_a_batch_prediction(self) batch_pred_create.the_batch_prediction_is_finished_in_less_than(self, example[4]) batch_pred_create.i_create_a_source_from_batch_prediction(self) source_create.the_source_is_finished(self, example[1]) def test_scenario5(self): """ Scenario: Successfully creating a batch anomaly score from an anomaly detector: Given I create a data source uploading a "<data>" file And I wait until the source is ready less than <time_1> secs And I create a dataset And I wait until the dataset is ready less than <time_2> secs And I create an anomaly detector And I wait until the anomaly detector is ready less than <time_3> secs When I create a batch anomaly score And I check the batch anomaly score is ok And I wait until the batch anomaly score is ready less than <time_4> secs And I download the created anomaly score file to "<local_file>" Then the batch anomaly score file is like "<predictions_file>" Examples: | data | time_1 | time_2 | time_3 | time_4 | local_file | predictions_file | | ../data/tiny_kdd.csv | 30 | 30 | 50 | 50 | ./tmp/batch_predictions.csv |./data/batch_predictions_a.csv | """ print(self.test_scenario5.__doc__) examples = [ ['data/tiny_kdd.csv', '30', '30', '50', '50', 'tmp/batch_predictions.csv', 'data/batch_predictions_a.csv']] for example in examples: print("\nTesting with:\n", example) source_create.i_upload_a_file(self, example[0]) source_create.the_source_is_finished(self, example[1]) dataset_create.i_create_a_dataset(self) dataset_create.the_dataset_is_finished_in_less_than(self, example[2]) anomaly_create.i_create_an_anomaly(self) anomaly_create.the_anomaly_is_finished_in_less_than(self, example[3]) batch_pred_create.i_create_a_batch_prediction_with_anomaly(self) batch_pred_create.the_batch_anomaly_score_is_finished_in_less_than(self, example[4]) batch_pred_create.i_download_anomaly_score_file(self, example[5]) batch_pred_create.i_check_predictions(self, example[6]) def test_scenario6(self): """ Scenario: Successfully creating a batch prediction for a logistic regression: Given I create a data source uploading a "<data>" file And I wait until the source is ready less than <time_1> secs And I create a dataset And I wait until the dataset is ready less than <time_2> secs And I create a logistic regression And I wait until the logistic regression is ready less than <time_3> secs When I create a batch prediction for the dataset with the logistic regression And I wait until the batch prediction is ready less than <time_4> secs And I download the created predictions file to "<local_file>" Then the batch prediction file is like "<predictions_file>" Examples: | data | time_1 | time_2 | time_3 | time_4 | local_file | predictions_file | | ../data/iris.csv | 30 | 30 | 80 | 50 | ./tmp/batch_predictions.csv | ./data/batch_predictions_lr.csv | """ print(self.test_scenario6.__doc__) examples = [ ['data/iris.csv', '30', '30', '80', '50', 'tmp/batch_predictions.csv', 'data/batch_predictions_lr.csv']] for example in examples: print("\nTesting with:\n", example) source_create.i_upload_a_file(self, example[0]) source_create.the_source_is_finished(self, example[1]) dataset_create.i_create_a_dataset(self) dataset_create.the_dataset_is_finished_in_less_than(self, example[2]) model_create.i_create_a_logistic_model(self) model_create.the_logistic_model_is_finished_in_less_than(self, example[3]) batch_pred_create.i_create_a_batch_prediction_logistic_model(self) batch_pred_create.the_batch_prediction_is_finished_in_less_than(self, example[4]) batch_pred_create.i_download_predictions_file(self, example[5]) batch_pred_create.i_check_predictions(self, example[6])
apache-2.0
vikatory/kbengine
kbe/src/lib/python/Lib/test/test_sunau.py
92
4663
from test.support import TESTFN import unittest from test import audiotests from audioop import byteswap import sys import sunau class SunauTest(audiotests.AudioWriteTests, audiotests.AudioTestsWithSourceFile): module = sunau class SunauPCM8Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pcm8.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 1 framerate = 11025 nframes = 48 comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ 02FF 4B00 3104 8008 CB06 4803 BF01 03FE B8FA B4F3 29EB 1AE6 \ EDE4 C6E2 0EE0 EFE0 57E2 FBE8 13EF D8F7 97FB F5FC 08FB DFFB \ 11FA 3EFB BCFC 66FF CF04 4309 C10E 5112 EE17 8216 7F14 8012 \ 490E 520D EF0F CE0F E40C 630A 080A 2B0B 510E 8B11 B60E 440A \ """) class SunauPCM16Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pcm16.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 2 framerate = 11025 nframes = 48 comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ 022EFFEA 4B5C00F9 311404EF 80DB0844 CBE006B0 48AB03F3 BFE601B5 0367FE80 \ B853FA42 B4AFF351 2997EBCD 1A5AE6DC EDF9E492 C627E277 0E06E0B7 EF29E029 \ 5759E271 FB34E83F 1377EF85 D82CF727 978EFB79 F5F7FC12 0864FB9E DF30FB40 \ 1183FA30 3EEAFB59 BC78FCB4 66D5FF60 CF130415 431A097D C1BA0EC7 512312A0 \ EEE11754 82071666 7FFE1448 80001298 49990EB7 52B40DC1 EFAD0F65 CE3A0FBE \ E4B70CE6 63490A57 08CC0A1D 2BBC0B09 51480E46 8BCB113C B6F60EE9 44150A5A \ """) class SunauPCM24Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pcm24.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 3 framerate = 11025 nframes = 48 comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ 022D65FFEB9D 4B5A0F00FA54 3113C304EE2B 80DCD6084303 \ CBDEC006B261 48A99803F2F8 BFE82401B07D 036BFBFE7B5D \ B85756FA3EC9 B4B055F3502B 299830EBCB62 1A5CA7E6D99A \ EDFA3EE491BD C625EBE27884 0E05A9E0B6CF EF2929E02922 \ 5758D8E27067 FB3557E83E16 1377BFEF8402 D82C5BF7272A \ 978F16FB7745 F5F865FC1013 086635FB9C4E DF30FCFB40EE \ 117FE0FA3438 3EE6B8FB5AC3 BC77A3FCB2F4 66D6DAFF5F32 \ CF13B9041275 431D69097A8C C1BB600EC74E 5120B912A2BA \ EEDF641754C0 8207001664B7 7FFFFF14453F 8000001294E6 \ 499C1B0EB3B2 52B73E0DBCA0 EFB2B20F5FD8 CE3CDB0FBE12 \ E4B49C0CEA2D 6344A80A5A7C 08C8FE0A1FFE 2BB9860B0A0E \ 51486F0E44E1 8BCC64113B05 B6F4EC0EEB36 4413170A5B48 \ """) class SunauPCM32Test(SunauTest, unittest.TestCase): sndfilename = 'pluck-pcm32.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 4 framerate = 11025 nframes = 48 comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ 022D65BCFFEB9D92 4B5A0F8000FA549C 3113C34004EE2BC0 80DCD680084303E0 \ CBDEC0C006B26140 48A9980003F2F8FC BFE8248001B07D92 036BFB60FE7B5D34 \ B8575600FA3EC920 B4B05500F3502BC0 29983000EBCB6240 1A5CA7A0E6D99A60 \ EDFA3E80E491BD40 C625EB80E27884A0 0E05A9A0E0B6CFE0 EF292940E0292280 \ 5758D800E2706700 FB3557D8E83E1640 1377BF00EF840280 D82C5B80F7272A80 \ 978F1600FB774560 F5F86510FC101364 086635A0FB9C4E20 DF30FC40FB40EE28 \ 117FE0A0FA3438B0 3EE6B840FB5AC3F0 BC77A380FCB2F454 66D6DA80FF5F32B4 \ CF13B980041275B0 431D6980097A8C00 C1BB60000EC74E00 5120B98012A2BAA0 \ EEDF64C01754C060 820700001664B780 7FFFFFFF14453F40 800000001294E6E0 \ 499C1B000EB3B270 52B73E000DBCA020 EFB2B2E00F5FD880 CE3CDB400FBE1270 \ E4B49CC00CEA2D90 6344A8800A5A7CA0 08C8FE800A1FFEE0 2BB986C00B0A0E00 \ 51486F800E44E190 8BCC6480113B0580 B6F4EC000EEB3630 441317800A5B48A0 \ """) class SunauULAWTest(SunauTest, unittest.TestCase): sndfilename = 'pluck-ulaw.au' sndfilenframes = 3307 nchannels = 2 sampwidth = 2 framerate = 11025 nframes = 48 comptype = 'ULAW' compname = 'CCITT G.711 u-law' frames = bytes.fromhex("""\ 022CFFE8 497C00F4 307C04DC 8284083C CB84069C 497C03DC BE8401AC 036CFE74 \ B684FA24 B684F344 2A7CEC04 19FCE704 EE04E504 C584E204 0E3CE104 EF04DF84 \ 557CE204 FB24E804 12FCEF04 D784F744 9684FB64 F5C4FC24 083CFBA4 DF84FB24 \ 11FCFA24 3E7CFB64 BA84FCB4 657CFF5C CF84041C 417C09BC C1840EBC 517C12FC \ EF0416FC 828415FC 7D7C13FC 828412FC 497C0EBC 517C0DBC F0040F3C CD840FFC \ E5040CBC 617C0A3C 08BC0A3C 2C7C0B3C 517C0E3C 8A8410FC B6840EBC 457C0A3C \ """) if sys.byteorder != 'big': frames = byteswap(frames, 2) if __name__ == "__main__": unittest.main()
lgpl-3.0
aasiutin/electrum
lib/old_mnemonic.py
16
17742
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 thomasv@gitorious # # 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. # list of words from http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/Contemporary_poetry words = [ "like", "just", "love", "know", "never", "want", "time", "out", "there", "make", "look", "eye", "down", "only", "think", "heart", "back", "then", "into", "about", "more", "away", "still", "them", "take", "thing", "even", "through", "long", "always", "world", "too", "friend", "tell", "try", "hand", "thought", "over", "here", "other", "need", "smile", "again", "much", "cry", "been", "night", "ever", "little", "said", "end", "some", "those", "around", "mind", "people", "girl", "leave", "dream", "left", "turn", "myself", "give", "nothing", "really", "off", "before", "something", "find", "walk", "wish", "good", "once", "place", "ask", "stop", "keep", "watch", "seem", "everything", "wait", "got", "yet", "made", "remember", "start", "alone", "run", "hope", "maybe", "believe", "body", "hate", "after", "close", "talk", "stand", "own", "each", "hurt", "help", "home", "god", "soul", "new", "many", "two", "inside", "should", "true", "first", "fear", "mean", "better", "play", "another", "gone", "change", "use", "wonder", "someone", "hair", "cold", "open", "best", "any", "behind", "happen", "water", "dark", "laugh", "stay", "forever", "name", "work", "show", "sky", "break", "came", "deep", "door", "put", "black", "together", "upon", "happy", "such", "great", "white", "matter", "fill", "past", "please", "burn", "cause", "enough", "touch", "moment", "soon", "voice", "scream", "anything", "stare", "sound", "red", "everyone", "hide", "kiss", "truth", "death", "beautiful", "mine", "blood", "broken", "very", "pass", "next", "forget", "tree", "wrong", "air", "mother", "understand", "lip", "hit", "wall", "memory", "sleep", "free", "high", "realize", "school", "might", "skin", "sweet", "perfect", "blue", "kill", "breath", "dance", "against", "fly", "between", "grow", "strong", "under", "listen", "bring", "sometimes", "speak", "pull", "person", "become", "family", "begin", "ground", "real", "small", "father", "sure", "feet", "rest", "young", "finally", "land", "across", "today", "different", "guy", "line", "fire", "reason", "reach", "second", "slowly", "write", "eat", "smell", "mouth", "step", "learn", "three", "floor", "promise", "breathe", "darkness", "push", "earth", "guess", "save", "song", "above", "along", "both", "color", "house", "almost", "sorry", "anymore", "brother", "okay", "dear", "game", "fade", "already", "apart", "warm", "beauty", "heard", "notice", "question", "shine", "began", "piece", "whole", "shadow", "secret", "street", "within", "finger", "point", "morning", "whisper", "child", "moon", "green", "story", "glass", "kid", "silence", "since", "soft", "yourself", "empty", "shall", "angel", "answer", "baby", "bright", "dad", "path", "worry", "hour", "drop", "follow", "power", "war", "half", "flow", "heaven", "act", "chance", "fact", "least", "tired", "children", "near", "quite", "afraid", "rise", "sea", "taste", "window", "cover", "nice", "trust", "lot", "sad", "cool", "force", "peace", "return", "blind", "easy", "ready", "roll", "rose", "drive", "held", "music", "beneath", "hang", "mom", "paint", "emotion", "quiet", "clear", "cloud", "few", "pretty", "bird", "outside", "paper", "picture", "front", "rock", "simple", "anyone", "meant", "reality", "road", "sense", "waste", "bit", "leaf", "thank", "happiness", "meet", "men", "smoke", "truly", "decide", "self", "age", "book", "form", "alive", "carry", "escape", "damn", "instead", "able", "ice", "minute", "throw", "catch", "leg", "ring", "course", "goodbye", "lead", "poem", "sick", "corner", "desire", "known", "problem", "remind", "shoulder", "suppose", "toward", "wave", "drink", "jump", "woman", "pretend", "sister", "week", "human", "joy", "crack", "grey", "pray", "surprise", "dry", "knee", "less", "search", "bleed", "caught", "clean", "embrace", "future", "king", "son", "sorrow", "chest", "hug", "remain", "sat", "worth", "blow", "daddy", "final", "parent", "tight", "also", "create", "lonely", "safe", "cross", "dress", "evil", "silent", "bone", "fate", "perhaps", "anger", "class", "scar", "snow", "tiny", "tonight", "continue", "control", "dog", "edge", "mirror", "month", "suddenly", "comfort", "given", "loud", "quickly", "gaze", "plan", "rush", "stone", "town", "battle", "ignore", "spirit", "stood", "stupid", "yours", "brown", "build", "dust", "hey", "kept", "pay", "phone", "twist", "although", "ball", "beyond", "hidden", "nose", "taken", "fail", "float", "pure", "somehow", "wash", "wrap", "angry", "cheek", "creature", "forgotten", "heat", "rip", "single", "space", "special", "weak", "whatever", "yell", "anyway", "blame", "job", "choose", "country", "curse", "drift", "echo", "figure", "grew", "laughter", "neck", "suffer", "worse", "yeah", "disappear", "foot", "forward", "knife", "mess", "somewhere", "stomach", "storm", "beg", "idea", "lift", "offer", "breeze", "field", "five", "often", "simply", "stuck", "win", "allow", "confuse", "enjoy", "except", "flower", "seek", "strength", "calm", "grin", "gun", "heavy", "hill", "large", "ocean", "shoe", "sigh", "straight", "summer", "tongue", "accept", "crazy", "everyday", "exist", "grass", "mistake", "sent", "shut", "surround", "table", "ache", "brain", "destroy", "heal", "nature", "shout", "sign", "stain", "choice", "doubt", "glance", "glow", "mountain", "queen", "stranger", "throat", "tomorrow", "city", "either", "fish", "flame", "rather", "shape", "spin", "spread", "ash", "distance", "finish", "image", "imagine", "important", "nobody", "shatter", "warmth", "became", "feed", "flesh", "funny", "lust", "shirt", "trouble", "yellow", "attention", "bare", "bite", "money", "protect", "amaze", "appear", "born", "choke", "completely", "daughter", "fresh", "friendship", "gentle", "probably", "six", "deserve", "expect", "grab", "middle", "nightmare", "river", "thousand", "weight", "worst", "wound", "barely", "bottle", "cream", "regret", "relationship", "stick", "test", "crush", "endless", "fault", "itself", "rule", "spill", "art", "circle", "join", "kick", "mask", "master", "passion", "quick", "raise", "smooth", "unless", "wander", "actually", "broke", "chair", "deal", "favorite", "gift", "note", "number", "sweat", "box", "chill", "clothes", "lady", "mark", "park", "poor", "sadness", "tie", "animal", "belong", "brush", "consume", "dawn", "forest", "innocent", "pen", "pride", "stream", "thick", "clay", "complete", "count", "draw", "faith", "press", "silver", "struggle", "surface", "taught", "teach", "wet", "bless", "chase", "climb", "enter", "letter", "melt", "metal", "movie", "stretch", "swing", "vision", "wife", "beside", "crash", "forgot", "guide", "haunt", "joke", "knock", "plant", "pour", "prove", "reveal", "steal", "stuff", "trip", "wood", "wrist", "bother", "bottom", "crawl", "crowd", "fix", "forgive", "frown", "grace", "loose", "lucky", "party", "release", "surely", "survive", "teacher", "gently", "grip", "speed", "suicide", "travel", "treat", "vein", "written", "cage", "chain", "conversation", "date", "enemy", "however", "interest", "million", "page", "pink", "proud", "sway", "themselves", "winter", "church", "cruel", "cup", "demon", "experience", "freedom", "pair", "pop", "purpose", "respect", "shoot", "softly", "state", "strange", "bar", "birth", "curl", "dirt", "excuse", "lord", "lovely", "monster", "order", "pack", "pants", "pool", "scene", "seven", "shame", "slide", "ugly", "among", "blade", "blonde", "closet", "creek", "deny", "drug", "eternity", "gain", "grade", "handle", "key", "linger", "pale", "prepare", "swallow", "swim", "tremble", "wheel", "won", "cast", "cigarette", "claim", "college", "direction", "dirty", "gather", "ghost", "hundred", "loss", "lung", "orange", "present", "swear", "swirl", "twice", "wild", "bitter", "blanket", "doctor", "everywhere", "flash", "grown", "knowledge", "numb", "pressure", "radio", "repeat", "ruin", "spend", "unknown", "buy", "clock", "devil", "early", "false", "fantasy", "pound", "precious", "refuse", "sheet", "teeth", "welcome", "add", "ahead", "block", "bury", "caress", "content", "depth", "despite", "distant", "marry", "purple", "threw", "whenever", "bomb", "dull", "easily", "grasp", "hospital", "innocence", "normal", "receive", "reply", "rhyme", "shade", "someday", "sword", "toe", "visit", "asleep", "bought", "center", "consider", "flat", "hero", "history", "ink", "insane", "muscle", "mystery", "pocket", "reflection", "shove", "silently", "smart", "soldier", "spot", "stress", "train", "type", "view", "whether", "bus", "energy", "explain", "holy", "hunger", "inch", "magic", "mix", "noise", "nowhere", "prayer", "presence", "shock", "snap", "spider", "study", "thunder", "trail", "admit", "agree", "bag", "bang", "bound", "butterfly", "cute", "exactly", "explode", "familiar", "fold", "further", "pierce", "reflect", "scent", "selfish", "sharp", "sink", "spring", "stumble", "universe", "weep", "women", "wonderful", "action", "ancient", "attempt", "avoid", "birthday", "branch", "chocolate", "core", "depress", "drunk", "especially", "focus", "fruit", "honest", "match", "palm", "perfectly", "pillow", "pity", "poison", "roar", "shift", "slightly", "thump", "truck", "tune", "twenty", "unable", "wipe", "wrote", "coat", "constant", "dinner", "drove", "egg", "eternal", "flight", "flood", "frame", "freak", "gasp", "glad", "hollow", "motion", "peer", "plastic", "root", "screen", "season", "sting", "strike", "team", "unlike", "victim", "volume", "warn", "weird", "attack", "await", "awake", "built", "charm", "crave", "despair", "fought", "grant", "grief", "horse", "limit", "message", "ripple", "sanity", "scatter", "serve", "split", "string", "trick", "annoy", "blur", "boat", "brave", "clearly", "cling", "connect", "fist", "forth", "imagination", "iron", "jock", "judge", "lesson", "milk", "misery", "nail", "naked", "ourselves", "poet", "possible", "princess", "sail", "size", "snake", "society", "stroke", "torture", "toss", "trace", "wise", "bloom", "bullet", "cell", "check", "cost", "darling", "during", "footstep", "fragile", "hallway", "hardly", "horizon", "invisible", "journey", "midnight", "mud", "nod", "pause", "relax", "shiver", "sudden", "value", "youth", "abuse", "admire", "blink", "breast", "bruise", "constantly", "couple", "creep", "curve", "difference", "dumb", "emptiness", "gotta", "honor", "plain", "planet", "recall", "rub", "ship", "slam", "soar", "somebody", "tightly", "weather", "adore", "approach", "bond", "bread", "burst", "candle", "coffee", "cousin", "crime", "desert", "flutter", "frozen", "grand", "heel", "hello", "language", "level", "movement", "pleasure", "powerful", "random", "rhythm", "settle", "silly", "slap", "sort", "spoken", "steel", "threaten", "tumble", "upset", "aside", "awkward", "bee", "blank", "board", "button", "card", "carefully", "complain", "crap", "deeply", "discover", "drag", "dread", "effort", "entire", "fairy", "giant", "gotten", "greet", "illusion", "jeans", "leap", "liquid", "march", "mend", "nervous", "nine", "replace", "rope", "spine", "stole", "terror", "accident", "apple", "balance", "boom", "childhood", "collect", "demand", "depression", "eventually", "faint", "glare", "goal", "group", "honey", "kitchen", "laid", "limb", "machine", "mere", "mold", "murder", "nerve", "painful", "poetry", "prince", "rabbit", "shelter", "shore", "shower", "soothe", "stair", "steady", "sunlight", "tangle", "tease", "treasure", "uncle", "begun", "bliss", "canvas", "cheer", "claw", "clutch", "commit", "crimson", "crystal", "delight", "doll", "existence", "express", "fog", "football", "gay", "goose", "guard", "hatred", "illuminate", "mass", "math", "mourn", "rich", "rough", "skip", "stir", "student", "style", "support", "thorn", "tough", "yard", "yearn", "yesterday", "advice", "appreciate", "autumn", "bank", "beam", "bowl", "capture", "carve", "collapse", "confusion", "creation", "dove", "feather", "girlfriend", "glory", "government", "harsh", "hop", "inner", "loser", "moonlight", "neighbor", "neither", "peach", "pig", "praise", "screw", "shield", "shimmer", "sneak", "stab", "subject", "throughout", "thrown", "tower", "twirl", "wow", "army", "arrive", "bathroom", "bump", "cease", "cookie", "couch", "courage", "dim", "guilt", "howl", "hum", "husband", "insult", "led", "lunch", "mock", "mostly", "natural", "nearly", "needle", "nerd", "peaceful", "perfection", "pile", "price", "remove", "roam", "sanctuary", "serious", "shiny", "shook", "sob", "stolen", "tap", "vain", "void", "warrior", "wrinkle", "affection", "apologize", "blossom", "bounce", "bridge", "cheap", "crumble", "decision", "descend", "desperately", "dig", "dot", "flip", "frighten", "heartbeat", "huge", "lazy", "lick", "odd", "opinion", "process", "puzzle", "quietly", "retreat", "score", "sentence", "separate", "situation", "skill", "soak", "square", "stray", "taint", "task", "tide", "underneath", "veil", "whistle", "anywhere", "bedroom", "bid", "bloody", "burden", "careful", "compare", "concern", "curtain", "decay", "defeat", "describe", "double", "dreamer", "driver", "dwell", "evening", "flare", "flicker", "grandma", "guitar", "harm", "horrible", "hungry", "indeed", "lace", "melody", "monkey", "nation", "object", "obviously", "rainbow", "salt", "scratch", "shown", "shy", "stage", "stun", "third", "tickle", "useless", "weakness", "worship", "worthless", "afternoon", "beard", "boyfriend", "bubble", "busy", "certain", "chin", "concrete", "desk", "diamond", "doom", "drawn", "due", "felicity", "freeze", "frost", "garden", "glide", "harmony", "hopefully", "hunt", "jealous", "lightning", "mama", "mercy", "peel", "physical", "position", "pulse", "punch", "quit", "rant", "respond", "salty", "sane", "satisfy", "savior", "sheep", "slept", "social", "sport", "tuck", "utter", "valley", "wolf", "aim", "alas", "alter", "arrow", "awaken", "beaten", "belief", "brand", "ceiling", "cheese", "clue", "confidence", "connection", "daily", "disguise", "eager", "erase", "essence", "everytime", "expression", "fan", "flag", "flirt", "foul", "fur", "giggle", "glorious", "ignorance", "law", "lifeless", "measure", "mighty", "muse", "north", "opposite", "paradise", "patience", "patient", "pencil", "petal", "plate", "ponder", "possibly", "practice", "slice", "spell", "stock", "strife", "strip", "suffocate", "suit", "tender", "tool", "trade", "velvet", "verse", "waist", "witch", "aunt", "bench", "bold", "cap", "certainly", "click", "companion", "creator", "dart", "delicate", "determine", "dish", "dragon", "drama", "drum", "dude", "everybody", "feast", "forehead", "former", "fright", "fully", "gas", "hook", "hurl", "invite", "juice", "manage", "moral", "possess", "raw", "rebel", "royal", "scale", "scary", "several", "slight", "stubborn", "swell", "talent", "tea", "terrible", "thread", "torment", "trickle", "usually", "vast", "violence", "weave", "acid", "agony", "ashamed", "awe", "belly", "blend", "blush", "character", "cheat", "common", "company", "coward", "creak", "danger", "deadly", "defense", "define", "depend", "desperate", "destination", "dew", "duck", "dusty", "embarrass", "engine", "example", "explore", "foe", "freely", "frustrate", "generation", "glove", "guilty", "health", "hurry", "idiot", "impossible", "inhale", "jaw", "kingdom", "mention", "mist", "moan", "mumble", "mutter", "observe", "ode", "pathetic", "pattern", "pie", "prefer", "puff", "rape", "rare", "revenge", "rude", "scrape", "spiral", "squeeze", "strain", "sunset", "suspend", "sympathy", "thigh", "throne", "total", "unseen", "weapon", "weary" ] n = 1626 # Note about US patent no 5892470: Here each word does not represent a given digit. # Instead, the digit represented by a word is variable, it depends on the previous word. def mn_encode( message ): assert len(message) % 8 == 0 out = [] for i in range(len(message)/8): word = message[8*i:8*i+8] x = int(word, 16) w1 = (x%n) w2 = ((x/n) + w1)%n w3 = ((x/n/n) + w2)%n out += [ words[w1], words[w2], words[w3] ] return out def mn_decode( wlist ): out = '' for i in range(len(wlist)/3): word1, word2, word3 = wlist[3*i:3*i+3] w1 = words.index(word1) w2 = (words.index(word2))%n w3 = (words.index(word3))%n x = w1 +n*((w2-w1)%n) +n*n*((w3-w2)%n) out += '%08x'%x return out if __name__ == '__main__': import sys if len( sys.argv ) == 1: print 'I need arguments: a hex string to encode, or a list of words to decode' elif len( sys.argv ) == 2: print ' '.join(mn_encode(sys.argv[1])) else: print mn_decode(sys.argv[1:])
mit
QianBIG/odoo
addons/auth_openid/controllers/__init__.py
443
1033
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 OpenERP SA (<http://openerp.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/>. # ############################################################################## import main # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
fhe-odoo/odoo
addons/product_margin/product_margin.py
194
8823
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import fields, osv class product_product(osv.osv): _inherit = "product.product" def _product_margin(self, cr, uid, ids, field_names, arg, context=None): res = {} if context is None: context = {} for val in self.browse(cr, uid, ids, context=context): res[val.id] = {} date_from = context.get('date_from', time.strftime('%Y-01-01')) date_to = context.get('date_to', time.strftime('%Y-12-31')) invoice_state = context.get('invoice_state', 'open_paid') if 'date_from' in field_names: res[val.id]['date_from'] = date_from if 'date_to' in field_names: res[val.id]['date_to'] = date_to if 'invoice_state' in field_names: res[val.id]['invoice_state'] = invoice_state invoice_types = () states = () if invoice_state == 'paid': states = ('paid',) elif invoice_state == 'open_paid': states = ('open', 'paid') elif invoice_state == 'draft_open_paid': states = ('draft', 'open', 'paid') if "force_company" in context: company_id = context['force_company'] else: company_id = self.pool.get("res.users").browse(cr, uid, uid, context=context).company_id.id #Cost price is calculated afterwards as it is a property sqlstr="""select sum(l.price_unit * l.quantity)/sum(nullif(l.quantity * pu.factor / pu2.factor,0)) as avg_unit_price, sum(l.quantity * pu.factor / pu2.factor) as num_qty, sum(l.quantity * (l.price_subtotal/(nullif(l.quantity,0)))) as total, sum(l.quantity * pu.factor * pt.list_price / pu2.factor) as sale_expected from account_invoice_line l left join account_invoice i on (l.invoice_id = i.id) left join product_product product on (product.id=l.product_id) left join product_template pt on (pt.id = l.product_id) left join product_uom pu on (pt.uom_id = pu.id) left join product_uom pu2 on (l.uos_id = pu2.id) where l.product_id = %s and i.state in %s and i.type IN %s and (i.date_invoice IS NULL or (i.date_invoice>=%s and i.date_invoice<=%s and i.company_id=%s)) """ invoice_types = ('out_invoice', 'in_refund') cr.execute(sqlstr, (val.id, states, invoice_types, date_from, date_to, company_id)) result = cr.fetchall()[0] res[val.id]['sale_avg_price'] = result[0] and result[0] or 0.0 res[val.id]['sale_num_invoiced'] = result[1] and result[1] or 0.0 res[val.id]['turnover'] = result[2] and result[2] or 0.0 res[val.id]['sale_expected'] = result[3] and result[3] or 0.0 res[val.id]['sales_gap'] = res[val.id]['sale_expected']-res[val.id]['turnover'] prod_obj = self.pool.get("product.product") ctx = context.copy() ctx['force_company'] = company_id prod = prod_obj.browse(cr, uid, val.id, context=ctx) invoice_types = ('in_invoice', 'out_refund') cr.execute(sqlstr, (val.id, states, invoice_types, date_from, date_to, company_id)) result = cr.fetchall()[0] res[val.id]['purchase_avg_price'] = result[0] and result[0] or 0.0 res[val.id]['purchase_num_invoiced'] = result[1] and result[1] or 0.0 res[val.id]['total_cost'] = result[2] and result[2] or 0.0 res[val.id]['normal_cost'] = prod.standard_price * res[val.id]['purchase_num_invoiced'] res[val.id]['purchase_gap'] = res[val.id]['normal_cost'] - res[val.id]['total_cost'] if 'total_margin' in field_names: res[val.id]['total_margin'] = res[val.id]['turnover'] - res[val.id]['total_cost'] if 'expected_margin' in field_names: res[val.id]['expected_margin'] = res[val.id]['sale_expected'] - res[val.id]['normal_cost'] if 'total_margin_rate' in field_names: res[val.id]['total_margin_rate'] = res[val.id]['turnover'] and res[val.id]['total_margin'] * 100 / res[val.id]['turnover'] or 0.0 if 'expected_margin_rate' in field_names: res[val.id]['expected_margin_rate'] = res[val.id]['sale_expected'] and res[val.id]['expected_margin'] * 100 / res[val.id]['sale_expected'] or 0.0 return res _columns = { 'date_from': fields.function(_product_margin, type='date', string='Margin Date From', multi='product_margin'), 'date_to': fields.function(_product_margin, type='date', string='Margin Date To', multi='product_margin'), 'invoice_state': fields.function(_product_margin, type='selection', selection=[ ('paid','Paid'),('open_paid','Open and Paid'),('draft_open_paid','Draft, Open and Paid') ], string='Invoice State',multi='product_margin', readonly=True), 'sale_avg_price' : fields.function(_product_margin, type='float', string='Avg. Unit Price', multi='product_margin', help="Avg. Price in Customer Invoices."), 'purchase_avg_price' : fields.function(_product_margin, type='float', string='Avg. Unit Price', multi='product_margin', help="Avg. Price in Supplier Invoices "), 'sale_num_invoiced' : fields.function(_product_margin, type='float', string='# Invoiced in Sale', multi='product_margin', help="Sum of Quantity in Customer Invoices"), 'purchase_num_invoiced' : fields.function(_product_margin, type='float', string='# Invoiced in Purchase', multi='product_margin', help="Sum of Quantity in Supplier Invoices"), 'sales_gap' : fields.function(_product_margin, type='float', string='Sales Gap', multi='product_margin', help="Expected Sale - Turn Over"), 'purchase_gap' : fields.function(_product_margin, type='float', string='Purchase Gap', multi='product_margin', help="Normal Cost - Total Cost"), 'turnover' : fields.function(_product_margin, type='float', string='Turnover' ,multi='product_margin', help="Sum of Multiplication of Invoice price and quantity of Customer Invoices"), 'total_cost' : fields.function(_product_margin, type='float', string='Total Cost', multi='product_margin', help="Sum of Multiplication of Invoice price and quantity of Supplier Invoices "), 'sale_expected' : fields.function(_product_margin, type='float', string='Expected Sale', multi='product_margin', help="Sum of Multiplication of Sale Catalog price and quantity of Customer Invoices"), 'normal_cost' : fields.function(_product_margin, type='float', string='Normal Cost', multi='product_margin', help="Sum of Multiplication of Cost price and quantity of Supplier Invoices"), 'total_margin' : fields.function(_product_margin, type='float', string='Total Margin', multi='product_margin', help="Turnover - Standard price"), 'expected_margin' : fields.function(_product_margin, type='float', string='Expected Margin', multi='product_margin', help="Expected Sale - Normal Cost"), 'total_margin_rate' : fields.function(_product_margin, type='float', string='Total Margin Rate(%)', multi='product_margin', help="Total margin * 100 / Turnover"), 'expected_margin_rate' : fields.function(_product_margin, type='float', string='Expected Margin (%)', multi='product_margin', help="Expected margin * 100 / Expected Sale"), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
decvalts/cartopy
lib/cartopy/tests/test_shapereader.py
1
5622
# (C) British Crown Copyright 2011 - 2018, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # cartopy 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 cartopy. If not, see <https://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) import numpy as np from numpy.testing import assert_array_almost_equal import pytest import cartopy.io.shapereader as shp @pytest.mark.natural_earth class TestLakes(object): def setup_class(self): LAKES_PATH = shp.natural_earth(resolution='110m', category='physical', name='lakes') self.reader = shp.Reader(LAKES_PATH) names = [record.attributes['name'] for record in self.reader.records()] # Choose a nice small lake self.lake_name = 'Lago de\rNicaragua' self.lake_index = names.index(self.lake_name) self.test_lake_geometry = \ list(self.reader.geometries())[self.lake_index] self.test_lake_record = list(self.reader.records())[self.lake_index] def test_geometry(self): lake_geometry = self.test_lake_geometry assert lake_geometry.type == 'MultiPolygon' assert len(lake_geometry) == 1 polygon = lake_geometry[0] expected = np.array([(-84.85548682324658, 11.147898667846633), (-85.29013729525353, 11.176165676310276), (-85.79132117383625, 11.509737046754324), (-85.8851655748783, 11.900100816287136), (-85.5653401354239, 11.940330918826362), (-85.03684526237491, 11.5216484643976), (-84.85548682324658, 11.147898667846633), (-84.85548682324658, 11.147898667846633)]) assert_array_almost_equal(expected, polygon.exterior.coords) assert len(polygon.interiors) == 0 def test_record(self): lake_record = self.test_lake_record assert lake_record.attributes.get('name') == self.lake_name expected = sorted(['admin', 'featurecla', 'min_label', 'min_zoom', 'name', 'name_alt', 'scalerank']) actual = sorted(lake_record.attributes.keys()) assert actual == expected assert lake_record.geometry == self.test_lake_geometry def test_bounds(self): # tests that a file which has a record with a bbox can # use the bbox without first creating the geometry record = next(self.reader.records()) assert not record._geometry, \ 'The geometry was loaded before it was needed.' assert len(record._bounds) == 4 assert record._bounds == record.bounds assert not record._geometry, \ 'The geometry was loaded in order to create the bounds.' @pytest.mark.natural_earth class TestRivers(object): def setup_class(self): RIVERS_PATH = shp.natural_earth(resolution='110m', category='physical', name='rivers_lake_centerlines') self.reader = shp.Reader(RIVERS_PATH) names = [record.attributes['name'] for record in self.reader.records()] # Choose a nice small river self.river_name = 'Peace' self.river_index = names.index(self.river_name) self.test_river_geometry = \ list(self.reader.geometries())[self.river_index] self.test_river_record = list(self.reader.records())[self.river_index] def test_geometry(self): geometry = self.test_river_geometry assert geometry.type == 'MultiLineString' assert len(geometry) == 1 linestring = geometry[0] coords = linestring.coords assert round(abs(coords[0][0] - -124.83563045947423), 7) == 0 assert round(abs(coords[0][1] - 56.75692352968272), 7) == 0 assert round(abs(coords[1][0] - -124.20045039940291), 7) == 0 assert round(abs(coords[1][1] - 56.243492336646824), 7) == 0 def test_record(self): records = list(self.reader.records()) assert len(records) == len(self.reader) # Choose a nice small lake river_record = records[self.river_index] expected_attributes = {'featurecla': 'River', 'min_label': 3.1, 'min_zoom': 2.1, 'name': self.river_name, 'name_en': self.river_name, 'scalerank': 2} for key, value in river_record.attributes.items(): if key == 'name_alt': # This value changed between pyshp 1.2.10 and 1.2.11, test it # as a special case, it should be an empty string once the # leading/trailing space is removed: assert not len(value.strip()) else: assert value == expected_attributes[key] assert river_record.geometry == self.test_river_geometry
gpl-3.0
pepetreshere/odoo
odoo/addons/test_inherits/tests/test_inherits.py
2
6466
# -*- coding: utf-8 -*- from odoo.tests import common from odoo.exceptions import ValidationError class test_inherits(common.TransactionCase): def test_create_3_levels_inherits(self): """ Check that we can create an inherits on 3 levels """ pallet = self.env['test.pallet'].create({ 'name': 'B', 'field_in_box': 'box', 'field_in_pallet': 'pallet', }) self.assertTrue(pallet) self.assertEqual(pallet.name, 'B') self.assertEqual(pallet.field_in_box, 'box') self.assertEqual(pallet.field_in_pallet, 'pallet') def test_create_3_levels_inherits_with_defaults(self): unit = self.env['test.unit'].create({ 'name': 'U', 'state': 'a', 'size': 1, }) ctx = { 'default_state': 'b', # 'state' is inherited from 'test.unit' 'default_size': 2, # 'size' is inherited from 'test.box' } pallet = self.env['test.pallet'].with_context(ctx).create({ 'name': 'P', 'unit_id': unit.id, # grand-parent field is set }) # default 'state' should be ignored, but default 'size' should not self.assertEqual(pallet.state, 'a') self.assertEqual(pallet.size, 2) def test_read_3_levels_inherits(self): """ Check that we can read an inherited field on 3 levels """ pallet = self.env.ref('test_inherits.pallet_a') self.assertEqual(pallet.read(['name']), [{'id': pallet.id, 'name': 'Unit A'}]) def test_write_3_levels_inherits(self): """ Check that we can create an inherits on 3 levels """ pallet = self.env.ref('test_inherits.pallet_a') pallet.write({'name': 'C'}) self.assertEqual(pallet.name, 'C') def test_write_4_one2many(self): """ Check that we can write on an inherited one2many field. """ box = self.env.ref('test_inherits.box_a') box.write({'line_ids': [(0, 0, {'name': 'Line 1'})]}) self.assertTrue(all(box.line_ids._ids)) self.assertEqual(box.line_ids.mapped('name'), ['Line 1']) self.assertEqual(box.line_ids, box.unit_id.line_ids) box.flush() box.invalidate_cache(['line_ids']) box.write({'line_ids': [(0, 0, {'name': 'Line 2'})]}) self.assertTrue(all(box.line_ids._ids)) self.assertEqual(box.line_ids.mapped('name'), ['Line 1', 'Line 2']) self.assertEqual(box.line_ids, box.unit_id.line_ids) box.flush() box.invalidate_cache(['line_ids']) box.write({'line_ids': [(1, box.line_ids[0].id, {'name': 'First line'})]}) self.assertTrue(all(box.line_ids._ids)) self.assertEqual(box.line_ids.mapped('name'), ['First line', 'Line 2']) self.assertEqual(box.line_ids, box.unit_id.line_ids) def test_write_5_field_readonly(self): """ Check that we can write on an inherited readonly field. """ self.assertTrue(self.env['test.box']._fields['readonly_name']) box = self.env.ref('test_inherits.box_a') box.write({'readonly_name': "Superuser's box"}) self.assertEqual(box.readonly_name, "Superuser's box") self.assertEqual(box.unit_id.readonly_name, "Superuser's box") def test_ir_model_data_inherits(self): """ Check the existence of the correct ir.model.data """ IrModelData = self.env['ir.model.data'] field = IrModelData.search([('name', '=', 'field_test_unit__name')]) self.assertEqual(len(field), 1) self.assertEqual(field.module, 'test_inherits') field = IrModelData.search([('name', '=', 'field_test_box__name')]) self.assertEqual(len(field), 1) self.assertEqual(field.module, 'test_inherits') def test_constraint_inherits(self): """Validate constraints on inherits when the parent is not updated""" Model = self.env['test.another_box'] with self.assertRaises(ValidationError): another_box = Model.create({'val1': 1, 'val2': 2}) another_box = Model.create({'val1': 1, 'val2': 1}) with self.assertRaises(ValidationError): another_box.write({'val2': 2}) another_box.write({'val1': 2, 'val2': 2}) def test_constraint_inherits_parent_change(self): """Validate constraints on inherits when parent is updated too""" UnitModel = self.env['test.another_unit'] BoxModel = self.env['test.another_box'] unit1 = UnitModel.create({'val1': 1}) box = BoxModel.create({'another_unit_id': unit1.id, 'val2': 1}) unit2 = UnitModel.create({'val1': 2}) box.write({'another_unit_id': unit2.id, 'val2': 2}) unit3 = UnitModel.create({'val1': 3}) box.write({'another_unit_id': unit3.id, 'val1': 4, 'val2': 4}) unit4 = UnitModel.create({'val1': 5}) with self.assertRaises(ValidationError): box.write({'another_unit_id': unit4.id, 'val2': 6}) unit5 = UnitModel.create({'val1': 7}) with self.assertRaises(ValidationError): box.write({'another_unit_id': unit5.id, 'val1': 8, 'val2': 7}) def test_display_name(self): """ Check the 'display_name' of an inherited translated 'name'. """ self.env['res.lang']._activate_lang('fr_FR') # concrete check pallet_en = self.env['test.pallet'].create({'name': 'Bread'}) pallet_fr = pallet_en.with_context(lang='fr_FR') pallet_fr.box_id.unit_id.name = 'Pain' self.assertEqual(pallet_en.display_name, 'Bread') self.assertEqual(pallet_fr.display_name, 'Pain') # check model Unit = type(self.env['test.unit']) Box = type(self.env['test.box']) Pallet = type(self.env['test.pallet']) self.assertTrue(Unit.name.translate) self.assertIn('lang', Unit.display_name.depends_context) self.assertIn('lang', Box.display_name.depends_context) self.assertIn('lang', Pallet.display_name.depends_context) def test_multi_write_m2o_inherits(self): """Verify that an inherits m2o field can be written to in batch""" unit_foo = self.env['test.unit'].create({'name': 'foo'}) boxes = self.env['test.box'].create([{'unit_id': unit_foo.id}] * 5) unit_bar = self.env['test.unit'].create({'name': 'bar'}) boxes.unit_id = unit_bar self.assertEqual(boxes.mapped('unit_id.name'), ['bar'])
agpl-3.0
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGLContext/events/event.py
2
2010
"""Base class for all OpenGLContext event objects.""" class Event(object): """Base class for all local event objects. This is an abstract class from which all local event objects are derived. It defines the base API for each event type, as understood by the event dispatch system. Attributes: type -- string value representing type of event REQUIRED! Examples: "mousebutton", "mousemove", "keyboard", "keypress" renderingPass -- pointer to the OpenGLContext.renderpass.RenderPass object associated with this event modifiers -- three-tuple of booleans: (shift, control, alt) context -- pointer to the rendering context """ type = "" context = None renderingPass = None modifiers = (0,0,0) # keyboard modifiers, three-tuple of shift, control, alt def __init__(self): """Initialize common event parameters""" self.visitedNodes = {} def visited (self, key, value = None): """Check for or register visitation of the given key key -- an opaque hashable value, normally the node and field/event as a tuple. value -- if provided, sets the current value, otherwise signals that the current value should be returned return value: previous key value (possibly None) """ if value is None: self.visitedNodes.get(key) else: previousValue = self.visitedNodes.get(key) self.visitedNodes[key] = value return previousValue def getKey (self): """Calculate the key for routing within the event manager. Each subclass will define the appropriate data values for inclusion in the key (note that the key must be a hashable value). """ def getModifiers( self ): """Retrieve a tuple of the active modifier keys Format is three Boolean values, (shift, control, alt) """ return self.modifiers
lgpl-3.0
Jgarcia-IAS/localizacion
openerp/addons/pad/pad.py
84
4296
# -*- coding: utf-8 -*- from openerp.osv import fields, osv import random import re import string import urllib2 import logging from openerp import SUPERUSER_ID from openerp.tools.translate import _ from openerp.tools import html2plaintext from py_etherpad import EtherpadLiteClient _logger = logging.getLogger(__name__) class pad_common(osv.osv_memory): _name = 'pad.common' def pad_is_configured(self, cr, uid, context=None): user = self.pool.get('res.users').browse(cr, uid, uid, context=context) return bool(user.company_id.pad_server) def pad_generate_url(self, cr, uid, context=None): company = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context).company_id pad = { "server" : company.pad_server, "key" : company.pad_key, } # make sure pad server in the form of http://hostname if not pad["server"]: return pad if not pad["server"].startswith('http'): pad["server"] = 'http://' + pad["server"] pad["server"] = pad["server"].rstrip('/') # generate a salt s = string.ascii_uppercase + string.digits salt = ''.join([s[random.randint(0, len(s) - 1)] for i in range(10)]) #path # etherpad hardcodes pad id length limit to 50 path = '-%s-%s' % (self._name, salt) path = '%s%s' % (cr.dbname.replace('_','-')[0:50 - len(path)], path) # contruct the url url = '%s/p/%s' % (pad["server"], path) #if create with content if "field_name" in context and "model" in context and "object_id" in context: myPad = EtherpadLiteClient( pad["key"], pad["server"]+'/api') try: myPad.createPad(path) except urllib2.URLError: raise osv.except_osv(_("Error"), _("Pad creation failed, \ either there is a problem with your pad server URL or with your connection.")) #get attr on the field model model = self.pool[context["model"]] field = model._fields[context['field_name']] real_field = field.pad_content_field #get content of the real field for record in model.browse(cr, uid, [context["object_id"]]): if record[real_field]: myPad.setText(path, (html2plaintext(record[real_field]).encode('utf-8'))) #Etherpad for html not functional #myPad.setHTML(path, record[real_field]) return { "server": pad["server"], "path": path, "url": url, } def pad_get_content(self, cr, uid, url, context=None): content = '' if url: try: page = urllib2.urlopen('%s/export/html'%url).read() mo = re.search('<body>(.*)</body>',page) if mo: content = mo.group(1) except: _logger.warning("No url found '%s'.", url) return content # TODO # reverse engineer protocol to be setHtml without using the api key def write(self, cr, uid, ids, vals, context=None): self._set_pad_value(cr, uid, vals, context) return super(pad_common, self).write(cr, uid, ids, vals, context=context) def create(self, cr, uid, vals, context=None): self._set_pad_value(cr, uid, vals, context) return super(pad_common, self).create(cr, uid, vals, context=context) # Set the pad content in vals def _set_pad_value(self, cr, uid, vals, context=None): for k,v in vals.items(): field = self._fields[k] if hasattr(field,'pad_content_field'): vals[field.pad_content_field] = self.pad_get_content(cr, uid, v, context=context) def copy(self, cr, uid, id, default=None, context=None): if not default: default = {} for k, field in self._fields.iteritems(): if hasattr(field,'pad_content_field'): pad = self.pad_generate_url(cr, uid, context) default[k] = pad.get('url') return super(pad_common, self).copy(cr, uid, id, default, context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
Lasanha/Gambiarra
libs/olpcgames/buildmanifest.py
3
1036
#! /usr/bin/env python """Stupid little script to automate generation of MANIFEST and po/POTFILES.in Really this should have been handled by using distutils, but oh well, distutils is a hoary beast and I can't fault people for not wanting to spend days spelunking around inside it to find the solutions... """ from distutils.filelist import FileList import os def fileList( template ): """Produce a formatted file-list for storing in a file""" files = FileList() for line in filter(None,template.splitlines()): files.process_template_line( line ) content = '\n'.join( files.files ) return content def main( ): """Do the quicky finding of files for our manifests""" content = fileList( open('MANIFEST.in').read() ) open( 'MANIFEST','w').write( content ) content = fileList( open('POTFILES.in').read() ) try: os.makedirs( 'po' ) except OSError, err: pass open( os.path.join('po','POTFILES.in'), 'w').write( content ) if __name__ == "__main__": main()
gpl-2.0
trevor/calendarserver
txweb2/dav/util.py
1
6744
# -*- test-case-name: txweb2.test.test_util -*- ## # Copyright (c) 2005-2014 Apple Inc. All rights reserved. # # 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. # # DRI: Wilfredo Sanchez, wsanchez@apple.com ## """ Utilities This API is considered private to static.py and is therefore subject to change. """ __all__ = [ "allDataFromStream", "davXMLFromStream", "noDataFromStream", "normalizeURL", "joinURL", "parentForURL", "unimplemented", "bindMethods", ] from urlparse import urlsplit, urlunsplit import posixpath # Careful; this module is not documented as public API from twisted.python.failure import Failure from twisted.internet.defer import succeed from twext.python.log import Logger from txweb2.stream import readStream from txdav.xml.parser import WebDAVDocument log = Logger() ## # Reading request body ## def allDataFromStream(stream, filter=None): data = [] def gotAllData(_): if not data: return None result = "".join([str(x) for x in data]) if filter is None: return result else: return filter(result) return readStream(stream, data.append).addCallback(gotAllData) def davXMLFromStream(stream): # FIXME: # This reads the request body into a string and then parses it. # A better solution would parse directly and incrementally from the # request stream. if stream is None: return succeed(None) def parse(xml): try: doc = WebDAVDocument.fromString(xml) doc.root_element.validate() return doc except ValueError: log.error("Bad XML:\n%s" % (xml,)) raise return allDataFromStream(stream, parse) def noDataFromStream(stream): def gotData(data): if data: raise ValueError("Stream contains unexpected data.") return readStream(stream, gotData) ## # URLs ## def normalizeURL(url): """ Normalized a URL. @param url: a URL. @return: the normalized representation of C{url}. The returned URL will never contain a trailing C{"/"}; it is up to the caller to determine whether the resource referred to by the URL is a collection and add a trailing C{"/"} if so. """ def cleanup(path): # For some silly reason, posixpath.normpath doesn't clean up '//' at the # start of a filename, so let's clean it up here. if path[0] == "/": count = 0 for char in path: if char != "/": break count += 1 path = path[count - 1:] return path.encode("utf-8") (scheme, host, path, query, fragment) = urlsplit(cleanup(url)) path = cleanup(posixpath.normpath(path)) return urlunsplit((scheme, host, path, query, fragment)) def joinURL(*urls): """ Appends URLs in series. @param urls: URLs to join. @return: the normalized URL formed by combining each URL in C{urls}. The returned URL will contain a trailing C{"/"} if and only if the last given URL contains a trailing C{"/"}. """ if len(urls) > 0 and len(urls[-1]) > 0 and urls[-1][-1] == "/": trailing = "/" else: trailing = "" url = normalizeURL("/".join([url for url in urls])) if url == "/": return "/" else: return url + trailing def parentForURL(url): """ Extracts the URL of the containing collection resource for the resource corresponding to a given URL. This removes any query or fragment pieces. @param url: an absolute (server-relative is OK) URL. @return: the normalized URL of the collection resource containing the resource corresponding to C{url}. The returned URL will always contain a trailing C{"/"}. """ (scheme, host, path, _ignore_query, _ignore_fragment) = urlsplit(normalizeURL(url)) index = path.rfind("/") if index is 0: if path == "/": return None else: path = "/" else: if index is -1: raise ValueError("Invalid URL: %s" % (url,)) else: path = path[:index] + "/" return urlunsplit((scheme, host, path, None, None)) ## # Python magic ## def unimplemented(obj): """ Throw an exception signifying that the current method is unimplemented and should not have been invoked. """ import inspect caller = inspect.getouterframes(inspect.currentframe())[1][3] raise NotImplementedError("Method %s is unimplemented in subclass %s" % (caller, obj.__class__)) def bindMethods(module, clazz, prefixes=("preconditions_", "http_", "report_")): """ Binds all functions in the given module (as defined by that module's C{__all__} attribute) which start with any of the given prefixes as methods of the given class. @param module: the module in which to search for functions. @param clazz: the class to bind found functions to as methods. @param prefixes: a sequence of prefixes to match found functions against. """ for submodule_name in module.__all__: try: __import__(module.__name__ + "." + submodule_name) except ImportError: log.error("Unable to import module %s" % (module.__name__ + "." + submodule_name,)) Failure().raiseException() submodule = getattr(module, submodule_name) for method_name in submodule.__all__: for prefix in prefixes: if method_name.startswith(prefix): method = getattr(submodule, method_name) setattr(clazz, method_name, method) break
apache-2.0
c0defreak/python-for-android
python3-alpha/extra_modules/gdata/sites/client.py
46
18156
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """SitesClient extends gdata.client.GDClient to streamline Sites API calls.""" __author__ = 'e.bidelman (Eric Bidelman)' import atom.data import gdata.client import gdata.sites.data import gdata.gauth # Feed URI templates CONTENT_FEED_TEMPLATE = '/feeds/content/%s/%s/' REVISION_FEED_TEMPLATE = '/feeds/revision/%s/%s/' ACTIVITY_FEED_TEMPLATE = '/feeds/activity/%s/%s/' SITE_FEED_TEMPLATE = '/feeds/site/%s/' ACL_FEED_TEMPLATE = '/feeds/acl/site/%s/%s/' class SitesClient(gdata.client.GDClient): """Client extension for the Google Sites API service.""" host = 'sites.google.com' # default server for the API domain = 'site' # default site domain name api_version = '1.1' # default major version for the service. auth_service = 'jotspot' auth_scopes = gdata.gauth.AUTH_SCOPES['jotspot'] ssl = True def __init__(self, site=None, domain=None, auth_token=None, **kwargs): """Constructs a new client for the Sites API. Args: site: string (optional) Name (webspace) of the Google Site domain: string (optional) Domain of the (Google Apps hosted) Site. If no domain is given, the Site is assumed to be a consumer Google Site, in which case the value 'site' is used. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: The other parameters to pass to gdata.client.GDClient constructor. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) self.site = site if domain is not None: self.domain = domain def __make_kind_category(self, label): if label is None: return None return atom.data.Category( scheme=gdata.sites.data.SITES_KIND_SCHEME, term='%s#%s' % (gdata.sites.data.SITES_NAMESPACE, label), label=label) __MakeKindCategory = __make_kind_category def __upload(self, entry, media_source, auth_token=None, **kwargs): """Uploads an attachment file to the Sites API. Args: entry: gdata.sites.data.ContentEntry The Atom XML to include. media_source: gdata.data.MediaSource The file payload to be uploaded. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to gdata.client.post(). Returns: The created entry. """ uri = self.make_content_feed_uri() return self.post(entry, uri, media_source=media_source, auth_token=auth_token, **kwargs) def _get_file_content(self, uri): """Fetches the file content from the specified URI. Args: uri: string The full URL to fetch the file contents from. Returns: The binary file content. Raises: gdata.client.RequestError: on error response from server. """ server_response = self.request('GET', uri) if server_response.status != 200: raise gdata.client.RequestError({'status': server_response.status, 'reason': server_response.reason, 'body': server_response.read()}) return server_response.read() _GetFileContent = _get_file_content def make_content_feed_uri(self): return CONTENT_FEED_TEMPLATE % (self.domain, self.site) MakeContentFeedUri = make_content_feed_uri def make_revision_feed_uri(self): return REVISION_FEED_TEMPLATE % (self.domain, self.site) MakeRevisionFeedUri = make_revision_feed_uri def make_activity_feed_uri(self): return ACTIVITY_FEED_TEMPLATE % (self.domain, self.site) MakeActivityFeedUri = make_activity_feed_uri def make_site_feed_uri(self, site_name=None): if site_name is not None: return (SITE_FEED_TEMPLATE % self.domain) + site_name else: return SITE_FEED_TEMPLATE % self.domain MakeSiteFeedUri = make_site_feed_uri def make_acl_feed_uri(self): return ACL_FEED_TEMPLATE % (self.domain, self.site) MakeAclFeedUri = make_acl_feed_uri def get_content_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the content feed containing the current state of site. Args: uri: string (optional) A full URI to query the Content feed with. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.ContentFeed """ if uri is None: uri = self.make_content_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.ContentFeed, auth_token=auth_token, **kwargs) GetContentFeed = get_content_feed def get_revision_feed(self, entry_or_uri_or_id, auth_token=None, **kwargs): """Retrieves the revision feed containing the revision history for a node. Args: entry_or_uri_or_id: string or gdata.sites.data.ContentEntry A full URI, content entry node ID, or a content entry object of the entry to retrieve revision information for. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.RevisionFeed """ uri = self.make_revision_feed_uri() if isinstance(entry_or_uri_or_id, gdata.sites.data.ContentEntry): uri = entry_or_uri_or_id.FindRevisionLink() elif entry_or_uri_or_id.find('/') == -1: uri += entry_or_uri_or_id else: uri = entry_or_uri_or_id return self.get_feed(uri, desired_class=gdata.sites.data.RevisionFeed, auth_token=auth_token, **kwargs) GetRevisionFeed = get_revision_feed def get_activity_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the activity feed containing recent Site activity. Args: uri: string (optional) A full URI to query the Activity feed. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.ActivityFeed """ if uri is None: uri = self.make_activity_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.ActivityFeed, auth_token=auth_token, **kwargs) GetActivityFeed = get_activity_feed def get_site_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the site feed containing a list of sites a user has access to. Args: uri: string (optional) A full URI to query the site feed. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.SiteFeed """ if uri is None: uri = self.make_site_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.SiteFeed, auth_token=auth_token, **kwargs) GetSiteFeed = get_site_feed def get_acl_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the acl feed containing a site's sharing permissions. Args: uri: string (optional) A full URI to query the acl feed. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.AclFeed """ if uri is None: uri = self.make_acl_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.AclFeed, auth_token=auth_token, **kwargs) GetAclFeed = get_acl_feed def create_site(self, title, description=None, source_site=None, theme=None, uri=None, auth_token=None, **kwargs): """Creates a new Google Site. Note: This feature is only available to Google Apps domains. Args: title: string Title for the site. description: string (optional) A description/summary for the site. source_site: string (optional) The site feed URI of the site to copy. This parameter should only be specified when copying a site. theme: string (optional) The name of the theme to create the site with. uri: string (optional) A full site feed URI to override where the site is created/copied. By default, the site will be created under the currently set domain (e.g. self.domain). auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to gdata.client.post(). Returns: gdata.sites.data.SiteEntry of the created site. """ new_entry = gdata.sites.data.SiteEntry(title=atom.data.Title(text=title)) if description is not None: new_entry.summary = gdata.sites.data.Summary(text=description) # Add the source link if we're making a copy of a site. if source_site is not None: source_link = atom.data.Link(rel=gdata.sites.data.SITES_SOURCE_LINK_REL, type='application/atom+xml', href=source_site) new_entry.link.append(source_link) if theme is not None: new_entry.theme = gdata.sites.data.Theme(text=theme) if uri is None: uri = self.make_site_feed_uri() return self.post(new_entry, uri, auth_token=auth_token, **kwargs) CreateSite = create_site def create_page(self, kind, title, html='', page_name=None, parent=None, auth_token=None, **kwargs): """Creates a new page (specified by kind) on a Google Site. Args: kind: string The type of page/item to create. For example, webpage, listpage, comment, announcementspage, filecabinet, etc. The full list of supported kinds can be found in gdata.sites.gdata.SUPPORT_KINDS. title: string Title for the page. html: string (optional) XHTML for the page's content body. page_name: string (optional) The URL page name to set. If not set, the title will be normalized and used as the page's URL path. parent: string or gdata.sites.data.ContentEntry (optional) The parent entry or parent link url to create the page under. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to gdata.client.post(). Returns: gdata.sites.data.ContentEntry of the created page. """ new_entry = gdata.sites.data.ContentEntry( title=atom.data.Title(text=title), kind=kind, content=gdata.sites.data.Content(text=html)) if page_name is not None: new_entry.page_name = gdata.sites.data.PageName(text=page_name) # Add parent link to entry if it should be uploaded as a subpage. if isinstance(parent, gdata.sites.data.ContentEntry): parent_link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent.GetSelfLink().href) new_entry.link.append(parent_link) elif parent is not None: parent_link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent) new_entry.link.append(parent_link) return self.post(new_entry, self.make_content_feed_uri(), auth_token=auth_token, **kwargs) CreatePage = create_page def create_webattachment(self, src, content_type, title, parent, description=None, auth_token=None, **kwargs): """Creates a new webattachment within a filecabinet. Args: src: string The url of the web attachment. content_type: string The MIME type of the web attachment. title: string The title to name the web attachment. parent: string or gdata.sites.data.ContentEntry (optional) The parent entry or url of the filecabinet to create the attachment under. description: string (optional) A summary/description for the attachment. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to gdata.client.post(). Returns: gdata.sites.data.ContentEntry of the created page. """ new_entry = gdata.sites.data.ContentEntry( title=atom.data.Title(text=title), kind='webattachment', content=gdata.sites.data.Content(src=src, type=content_type)) if isinstance(parent, gdata.sites.data.ContentEntry): link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent.GetSelfLink().href) elif parent is not None: link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent) new_entry.link.append(link) # Add file decription if it was specified if description is not None: new_entry.summary = gdata.sites.data.Summary(type='text', text=description) return self.post(new_entry, self.make_content_feed_uri(), auth_token=auth_token, **kwargs) CreateWebAttachment = create_webattachment def upload_attachment(self, file_handle, parent, content_type=None, title=None, description=None, folder_name=None, auth_token=None, **kwargs): """Uploads an attachment to a parent page. Args: file_handle: MediaSource or string A gdata.data.MediaSource object containing the file to be uploaded or the full path name to the file on disk. parent: gdata.sites.data.ContentEntry or string The parent page to upload the file to or the full URI of the entry's self link. content_type: string (optional) The MIME type of the file (e.g 'application/pdf'). This should be provided if file is not a MediaSource object. title: string (optional) The title to name the attachment. If not included, the filepath or media source's filename is used. description: string (optional) A summary/description for the attachment. folder_name: string (optional) The name of an existing folder to upload the attachment to. This only applies when the parent parameter points to a filecabinet entry. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.__upload(). Returns: A gdata.sites.data.ContentEntry containing information about the created attachment. """ if isinstance(parent, gdata.sites.data.ContentEntry): link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent.GetSelfLink().href) else: link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent) if not isinstance(file_handle, gdata.data.MediaSource): ms = gdata.data.MediaSource(file_path=file_handle, content_type=content_type) else: ms = file_handle # If no title specified, use the file name if title is None: title = ms.file_name new_entry = gdata.sites.data.ContentEntry(kind='attachment') new_entry.title = atom.data.Title(text=title) new_entry.link.append(link) # Add file decription if it was specified if description is not None: new_entry.summary = gdata.sites.data.Summary(type='text', text=description) # Upload the attachment to a filecabinet folder? if parent.Kind() == 'filecabinet' and folder_name is not None: folder_category = atom.data.Category( scheme=gdata.sites.data.FOLDER_KIND_TERM, term=folder_name) new_entry.category.append(folder_category) return self.__upload(new_entry, ms, auth_token=auth_token, **kwargs) UploadAttachment = upload_attachment def download_attachment(self, uri_or_entry, file_path): """Downloads an attachment file to disk. Args: uri_or_entry: string The full URL to download the file from. file_path: string The full path to save the file to. Raises: gdata.client.RequestError: on error response from server. """ uri = uri_or_entry if isinstance(uri_or_entry, gdata.sites.data.ContentEntry): uri = uri_or_entry.content.src f = open(file_path, 'wb') try: f.write(self._get_file_content(uri)) except gdata.client.RequestError as e: f.close() raise e f.flush() f.close() DownloadAttachment = download_attachment
apache-2.0
gleim/DAO
deploy/prepare.py
4
5796
#!/usr/bin/python2 import json import subprocess import argparse import os import inspect contracts_dir = "../" currentdir = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe())) ) os.sys.path.insert(0, os.path.dirname(currentdir)) from tests.utils import determine_binary, edit_dao_source, rm_file, to_wei class TestDeployContext(): def __init__(self, args): self.args = args self.args.solc = determine_binary(args.solc, 'solc', True) def compile_contract(self, contract_name): if self.args.no_limits and contract_name == "DAO.sol": contract_path = edit_dao_source( self.args.contracts_dir, False, # keep limits self.args.min_proposal_debate, self.args.min_split_debate, True, # halve min quorum test, remove year limit self.args.split_execution_period, True, # Normal pricing True, # Don't edit creationGracePeriod ) else: contract_path = os.path.join( self.args.contracts_dir, contract_name ) print(" Compiling {}...".format(contract_path)) data = subprocess.check_output([ self.args.solc, contract_path, "--optimize", "--combined-json", "abi,bin" ]) return json.loads(data) def cleanup(self): try: rm_file(os.path.join(self.args.contracts_dir, "DAOcopy.sol")) rm_file( os.path.join(self.args.contracts_dir, "TokenCreationCopy.sol") ) except: pass if __name__ == "__main__": p = argparse.ArgumentParser(description='DAO deployment script') p.add_argument( '--solc', help='Full path to the solc binary to use' ) p.add_argument( '--creation-duration-mins', type=int, default=60, help='Deployed DAO creation duration in minutes' ) p.add_argument( '--contracts-dir', default="..", help='The directory where the contracts are located' ) p.add_argument( '--no-limits', action='store_true', help='If given then a version of DAO.sol without limits is compiled' ) p.add_argument( '--curator', default="0x08144824954c65b12f68b75072488e634ac4e67a", # Griff testnet help='Account to set as the curator' ) p.add_argument( '--default-proposal-deposit', type=int, default=1, help='The proposal deposit (in ether) for every proposal of the DAO' ) p.add_argument( '--split-execution-period', type=int, default=20, help=( 'Number of seconds after the voting deadline for which a split ' 'proposal is executable' ) ) p.add_argument( '--min-proposal-debate', type=int, default=3600, help=( 'Minumum number of seconds that a generic proposal can have' ) ) p.add_argument( '--min-split-debate', type=int, default=3600, help=( 'Minumum number of seconds that a split proposal can have' ) ) p.add_argument( '--offer-contractor', default="0x08144824954c65b12f68b75072488e634ac4e67a", # Griff testnet help='Account to set as the SampleOffer contractor' ) p.add_argument( '--offer-total-costs', type=int, default=50, help='Total costs of the SampleOffer in ether' ) p.add_argument( '--offer-onetime-costs', type=int, default=10, help='Onetime costs of the SampleOffer in ether' ) p.add_argument( '--offer-min-daily-withdraw', type=int, default=1, help='Minimum daily withrdawal limit' ) p.add_argument( '--offer-client-dao-address', default="0x159fe90ac850c895e4fd144e705923cfa042d974", # A testnet DAO help='The address of the DAO to set as the client of the SampleOffer' ) args = p.parse_args() ctx = TestDeployContext(args) comp = ctx.compile_contract("DAO.sol") comp2 = ctx.compile_contract("SampleOffer.sol") with open("prepare.js", "w") as f: f.write("dao_abi = {};\n".format(comp['contracts']['DAO']['abi'])) f.write("dao_bin = '{}';\n".format(comp['contracts']['DAO']['bin'])) f.write("creator_abi = {};\n".format( comp['contracts']['DAO_Creator']['abi']) ) f.write("creator_bin = '{}';\n".format( comp['contracts']['DAO_Creator']['bin']) ) f.write("offer_abi = {};\n".format( comp2['contracts']['SampleOffer']['abi']) ) f.write("offer_bin = '{}';\n".format( comp2['contracts']['SampleOffer']['bin']) ) f.write("seconds_from_now = {};\n".format( args.creation_duration_mins * 60) ) f.write("curator = \"{}\";\n".format(args.curator)) f.write("default_proposal_deposit = {};\n".format( args.default_proposal_deposit) ) f.write("contractor = \"{}\";\n".format(args.offer_contractor)) f.write("offer_total_costs = {};\n".format( to_wei(args.offer_total_costs) )) f.write("offer_onetime_costs = {};\n".format( to_wei(args.offer_onetime_costs) )) f.write("offer_min_daily_withdraw = {};\n".format( to_wei(args.offer_min_daily_withdraw) )) f.write("offer_client_dao_address = '{}';\n".format( args.offer_client_dao_address )) ctx.cleanup()
lgpl-3.0
zhengnanlee/shadowsocks
shadowsocks/crypto/salsa20_ctr.py
26
4894
#!/usr/bin/env python # Copyright (c) 2014 clowwindy # # 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. import time import struct import logging import sys slow_xor = False imported = False BLOCK_SIZE = 16384 def run_imports(): global imported, slow_xor, salsa20, numpy if not imported: imported = True try: import numpy except ImportError: logging.error('can not import numpy, using SLOW XOR') logging.error('please install numpy if you use salsa20') slow_xor = True try: import salsa20 except ImportError: logging.error('you have to install salsa20 before you use salsa20') sys.exit(1) def numpy_xor(a, b): if slow_xor: return py_xor_str(a, b) dtype = numpy.byte if len(a) % 4 == 0: dtype = numpy.uint32 elif len(a) % 2 == 0: dtype = numpy.uint16 ab = numpy.frombuffer(a, dtype=dtype) bb = numpy.frombuffer(b, dtype=dtype) c = numpy.bitwise_xor(ab, bb) r = c.tostring() return r def py_xor_str(a, b): c = [] for i in xrange(0, len(a)): c.append(chr(ord(a[i]) ^ ord(b[i]))) return ''.join(c) class Salsa20Cipher(object): """a salsa20 CTR implemetation, provides m2crypto like cipher API""" def __init__(self, alg, key, iv, op, key_as_bytes=0, d=None, salt=None, i=1, padding=1): run_imports() if alg != 'salsa20-ctr': raise Exception('unknown algorithm') self._key = key self._nonce = struct.unpack('<Q', iv)[0] self._pos = 0 self._next_stream() def _next_stream(self): self._nonce &= 0xFFFFFFFFFFFFFFFF self._stream = salsa20.Salsa20_keystream(BLOCK_SIZE, struct.pack('<Q', self._nonce), self._key) self._nonce += 1 def update(self, data): results = [] while True: remain = BLOCK_SIZE - self._pos cur_data = data[:remain] cur_data_len = len(cur_data) cur_stream = self._stream[self._pos:self._pos + cur_data_len] self._pos = self._pos + cur_data_len data = data[remain:] results.append(numpy_xor(cur_data, cur_stream)) if self._pos >= BLOCK_SIZE: self._next_stream() self._pos = 0 if not data: break return ''.join(results) ciphers = { 'salsa20-ctr': (32, 8, Salsa20Cipher), } def test(): from os import urandom import random rounds = 1 * 1024 plain = urandom(BLOCK_SIZE * rounds) import M2Crypto.EVP # cipher = M2Crypto.EVP.Cipher('aes_128_cfb', 'k' * 32, 'i' * 16, 1, # key_as_bytes=0, d='md5', salt=None, i=1, # padding=1) # decipher = M2Crypto.EVP.Cipher('aes_128_cfb', 'k' * 32, 'i' * 16, 0, # key_as_bytes=0, d='md5', salt=None, i=1, # padding=1) cipher = Salsa20Cipher('salsa20-ctr', 'k' * 32, 'i' * 8, 1) decipher = Salsa20Cipher('salsa20-ctr', 'k' * 32, 'i' * 8, 1) results = [] pos = 0 print 'salsa20 test start' start = time.time() while pos < len(plain): l = random.randint(100, 32768) c = cipher.update(plain[pos:pos + l]) results.append(c) pos += l pos = 0 c = ''.join(results) results = [] while pos < len(plain): l = random.randint(100, 32768) results.append(decipher.update(c[pos:pos + l])) pos += l end = time.time() print 'speed: %d bytes/s' % (BLOCK_SIZE * rounds / (end - start)) assert ''.join(results) == plain if __name__ == '__main__': test()
mit
Team02-TeamGuinness/BIOE421_RoboHand
Printrun/testtools/gcodeviewer.py
20
2012
#!/usr/bin/env python # This file is part of the Printrun suite. # # Printrun 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. # # Printrun 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 Printrun. If not, see <http://www.gnu.org/licenses/>. import sys import os import logging logging.basicConfig(level=logging.INFO) import wx sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) from printrun.gcview import GcodeViewFrame from printrun import gcoder app = wx.App(redirect = False) build_dimensions = [200, 200, 100, -100, -100, 0] build_dimensions = [200, 200, 100, 0, 0, 0] frame = GcodeViewFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size = (800, 800), build_dimensions = build_dimensions) gcode = gcoder.GCode(open(sys.argv[1])) print "Gcode loaded" frame.addfile(gcode) first_move = None for i in range(len(gcode.lines)): if gcode.lines[i].is_move: first_move = gcode.lines[i] break last_move = None for i in range(len(gcode.lines) - 1, -1, -1): if gcode.lines[i].is_move: last_move = gcode.lines[i] break nsteps = 20 steptime = 50 lines = [first_move] \ + [gcode.lines[int(float(i) * (len(gcode.lines) - 1) / nsteps)] for i in range(1, nsteps)] + [last_move] current_line = 0 def setLine(): global current_line frame.set_current_gline(lines[current_line]) current_line = (current_line + 1) % len(lines) timer.Start() timer = wx.CallLater(steptime, setLine) timer.Start() frame.Show(True) app.MainLoop() app.Destroy()
gpl-2.0
dsyang/buck
python-dsl/buck_parser/glob_mercurial.py
12
5295
"""Glob implementation using mercurial manifest.""" from pathlib import _Accessor, PosixPath from .glob_internal import glob_internal from .util import Diagnostic, memoized import itertools import os.path class DiagnosticsFileObject(object): def __init__(self, diagnostics): self.diagnostics = diagnostics def write(self, value): self.diagnostics.append(Diagnostic( message=value, level='warning', source='mercurial', exception=None)) def flush(self): pass class ManifestTrie(object): """Basic trie implementation from a hg repository manifest and working copy status Lazily parses path strings of children as the trie is traversed. """ @classmethod def from_repo(cls, repo_info, project_root): entries = {} hgroot, manifest, status = repo_info base_path = os.path.relpath(project_root, hgroot) if base_path: base_path += '/' removed = set(status.removed).union(status.deleted) entries = ( path[len(base_path):] for path in itertools.chain(manifest, status.added, status.unknown) if path.startswith(base_path) and path not in removed) return cls(entries) def __init__(self, entries): parsed = {} for path in filter(None, entries): parent, _, remainder = path.partition('/') parsed.setdefault(parent, []).append(remainder) self._entries = parsed or None # None is a leaf node def listdir(self): return list(self._entries) def is_dir(self): return self._entries is not None def traverse(self, name): entry = self._entries[name] if not isinstance(entry, type(self)): self._entries[name] = entry = type(self)(entry) return entry class ManifestAccessor(_Accessor): def listdir(self, path): return path._manifest_trie.listdir() class ManifestPath(PosixPath): """Minimal Path implementation sourced from a manifest""" __slots__ = ('_manifest_trie',) def __new__(cls, *args, **kwargs): self = cls._from_parts(args, init=False) self._init() self._manifest_trie = kwargs.pop('manifest_trie', None) return self def _init(self): self._accessor = ManifestAccessor() def _make_child_relpath(self, part): child = super(ManifestPath, self)._make_child_relpath(part) try: child._manifest_trie = self._manifest_trie.traverse(part) except KeyError: child._manifest_trie = None return child def is_dir(self): return self._manifest_trie.is_dir() def is_file(self): return not self.is_dir() def exists(self): return self._manifest_trie is not None def relative_to(self, *other): # produce a PosixPath object again result = super(PosixPath, self).relative_to(*other) return PosixPath._from_parsed_parts(result._drv, result._root, result._parts) def load_mercurial_repo_info(build_env, search_base, allow_safe_import): if not build_env.use_mercurial_glob: return for parent in itertools.chain((search_base,), search_base.parents): if parent.joinpath('.hg').is_dir(): break else: # No parent found return return _load_mercurial_repo_info_for_root(build_env, parent, allow_safe_import) @memoized(deepcopy=False, keyfunc=lambda build_env, hgroot, *a: str(hgroot)) def _load_mercurial_repo_info_for_root(build_env, hgroot, allow_safe_import): os.environ['HGPLAIN'] = '' # any output should be plain with allow_safe_import(): from mercurial import ui, hg # Mercurial imports extensions when creating the UI and accessing a new repository. try: # Explicitly load configuration ui_ = ui.ui.load() except AttributeError: # Older Mercurial version, configuration is loaded implicitly ui_ = ui.ui() ui_.fout = DiagnosticsFileObject(build_env.diagnostics) ui_.ferr = DiagnosticsFileObject(build_env.diagnostics) ui_.quiet = True repo = hg.repository(ui_, str(hgroot)) manifest = repo['.'].manifest() status = repo.status(unknown=True) return (repo.root, manifest, status) @memoized( deepcopy=False, keyfunc=lambda repo_info, project_root: (repo_info[0], project_root)) def _load_manifest_trie(repo_info, project_root): return ManifestTrie.from_repo(repo_info, project_root) def glob_mercurial_manifest( includes, excludes, project_root_relative_excludes, include_dotfiles, search_base, project_root, repo_info): # pull file information from the mercurial manifest; this doesn't require # any filesystem access beyond access to the mercurial repository itself. trie = _load_manifest_trie(repo_info, project_root) try: for p in search_base.relative_to(project_root).parts: trie = trie.traverse(p) except KeyError: # no such path in the manifest, short-circuit return [] return glob_internal( includes, excludes, project_root_relative_excludes, include_dotfiles, ManifestPath(search_base, manifest_trie=trie), project_root)
apache-2.0